package com.izouma.nineth.service;

import com.izouma.nineth.domain.User;
import com.izouma.nineth.domain.UserWareHouse;
import com.izouma.nineth.domain.WhiteListConfigInfo;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.enums.ItemType;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.UserRepo;
import com.izouma.nineth.repo.UserWareHouseRepo;
import com.izouma.nineth.repo.WhitelistConfigInfoRepo;
import com.izouma.nineth.utils.JpaUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
@AllArgsConstructor
public class WhitelistConfigInfoService {

    private UserWareHouseRepo userWareHouseRepo;
    private UserRepo userRepo;

    private final WhitelistConfigInfoRepo whitelistConfigInfoRepo;


    /**
     * 所有列表
     * @param pageQuery
     * @return
     */
    public Page<WhiteListConfigInfo>  all(PageQuery pageQuery){
        Specification<WhiteListConfigInfo> specification = JpaUtils.toSpecification(pageQuery, WhiteListConfigInfo.class);
        return whitelistConfigInfoRepo.findAll(specification, JpaUtils.toPageRequest(pageQuery));
    }



    /**
     * 批量保存
     * @param info
     * @return
     */
    @Transactional
    public WhiteListConfigInfo batchSave(WhiteListConfigInfo info){
        List<String> phones = Arrays.stream(info.getPhones().replaceAll("\\s+", ",")
                .split(","))
                .map(String::trim)
                .filter(s -> !StringUtils.isEmpty(s))
                .collect(Collectors.toList());

        List<User> list = userRepo.findByPhoneInAndDelFalse(phones);
        if(list.size() == 0){
            throw new BusinessException("添加失败，通过手机号搜索的用户结果为0");
        }

        if (info.getId() != null) {
            throw new BusinessException("不可以修改白名单配置信息");
        }

        WhiteListConfigInfo whiteListConfigInfo = whitelistConfigInfoRepo.save(info);

        List<UserWareHouse> userWareHouseList = new ArrayList<>();
        for (User user : list) {
            userWareHouseList.add(UserWareHouse.builder()
                    .userId(user.getId())
                    .itemId(info.getItemId())
                    .itemName(ItemType.getValue(info.getItemId()))
                    .text(info.getText())
                    .projectId(info.getProjectId())
                    .advancePurchaseCount(info.getAdvancePurchaseCount())
                    .targetCollectionId(info.getTargetCollectionId())
                    .targetCollectionIdList(info.getTargetCollectionIdList())
                    .disabled(true)
                    .phone(user.getPhone())
                    .minterId(info.getMinterId())
                    .overdueTime(info.getOverdueTime())
                    .whitelistConfigId(whiteListConfigInfo.getId())
                    .advancePurchaseTime(info.getAdvancePurchaseTime()).build());
        }
        userWareHouseRepo.saveAll(userWareHouseList);

        return whiteListConfigInfo;
    }

    /**
     * 删除
     * @param whiteListId
     */
    public void delById(Long whiteListId) {
        whitelistConfigInfoRepo.deleteById(whiteListId);
        userWareHouseRepo.softDeleteByConfigId(whiteListId);
    }
}
