package com.ruoyi.ibs.grid.service.impl;

import com.ruoyi.ibs.enumertion.CustTypeEnum;
import com.ruoyi.ibs.grid.domain.dto.virtual.VirtualCustDTO;
import com.ruoyi.ibs.grid.mapper.CustInfoMapper;
import com.ruoyi.ibs.grid.service.VirtualGridCustService;
import com.ruoyi.ibs.grid.util.ArrayListUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author 吴凯程
 * @Date 2025/4/27
 **/
@Service
@Slf4j
@EnableAsync
public class VirtualGridCustServiceImpl implements VirtualGridCustService {

    @Resource
    private CustInfoMapper custInfoMapper;
    /**
     * @param virtualCustDTOList
     */
    @Override
    @Async
    public void updateToCustInfo(String dept, List<VirtualCustDTO> virtualCustDTOList, String updateBy, String updateTime) {
        log.info("自定义名单网格 开始存入数据库");
//        virtualCustDTOList = virtualCustDTOList.stream().filter(virtualCustDTO -> Objects.nonNull(virtualCustDTO.getPhoneNum())).collect(Collectors.toList());
        List<List<VirtualCustDTO>> lists = ArrayListUtil.sliceArrayList(virtualCustDTOList, 1000);
        for (List<VirtualCustDTO> list : lists) {
            for (CustTypeEnum custTypeEnum : CustTypeEnum.values()) {
                String custIds = list.stream().filter(virtualCustDTO -> virtualCustDTO.getCustType().equals(custTypeEnum.getName()))
                        .map(virtualCustDTO -> virtualCustDTO.getCustId()).collect(Collectors.joining(","));
                if (custIds.isEmpty()) {
                    continue;
                }
                List<String> existCustIds = custInfoMapper.selectExistCustByCustId(dept, custTypeEnum.getCode(), custIds);
                List<VirtualCustDTO> newClients = list.stream().filter(virtualCustDTO -> !existCustIds.contains(virtualCustDTO.getCustId())).collect(Collectors.toList());
                if(!newClients.isEmpty()){
                    if (custTypeEnum.getCode().equals(CustTypeEnum.PERSONAL.getCode())){
                        custInfoMapper.insertToRetailByVirtualCustDTO(dept, newClients, updateBy, updateTime);
                    }else if (custTypeEnum.getCode().equals(CustTypeEnum.MERCHANT.getCode())){
                        custInfoMapper.insertToMerchantByVirtualCustDTO(dept, newClients, updateBy, updateTime);
                    }else if (custTypeEnum.getCode().equals(CustTypeEnum.ENTERPRISE.getCode())){
                        custInfoMapper.insertToBusinessByVirtualCustDTO(dept, newClients, updateBy, updateTime);
                    }
                }
            }
        }
        log.info("结束");
    }


}
