package com.ruoyi.ibs.customerselect.service.Impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.CustInfoBusiness;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.ibs.dashboard.service.NotificationService;
import com.ruoyi.ibs.customerselect.domain.BusinessCustLevelImportExcelDTO;
import com.ruoyi.ibs.customerselect.domain.BusinessCustLevelImportTaskVO;
import com.ruoyi.ibs.customerselect.domain.*;
import com.ruoyi.ibs.customerselect.domain.vo.GridRelateVO;
import com.ruoyi.ibs.customerselect.mapper.CustInfoBusinessMapper;
import com.ruoyi.ibs.customerselect.mapper.GridSelectMapper;
import com.ruoyi.ibs.customerselect.mapper.GridSummarCountMapper;
import com.ruoyi.ibs.customerselect.mapper.MerchantMcspInfoMapper;
import com.ruoyi.ibs.customerselect.service.IMyCustomerService;
import com.ruoyi.ibs.customerselect.service.MyCustomerGridSelectService;
import com.ruoyi.ibs.grid.domain.vo.LaLuVo;
import com.ruoyi.ibs.grid.mapper.AnchorCustMapper;
import com.ruoyi.ibs.grid.mapper.AnchorMapper;
import com.ruoyi.ibs.grid.mapper.GridAdminDivisionRelateMapper;
import com.ruoyi.ibs.grid.service.impl.GridSelectServiceImpl;
import com.ruoyi.ibs.list.domain.CustDeptUserGrid;
import com.ruoyi.ibs.list.domain.CustInfoMerchant;
import com.ruoyi.ibs.list.domain.CustInfoRetail;
import com.ruoyi.ibs.list.mapper.CustDeptUserGridMapper;
import com.ruoyi.ibs.list.mapper.CustInfoMerchantMapper;
import com.ruoyi.ibs.list.mapper.CustInfoRetailMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 我的客户 服务实现
 *
 * @author ruoyi
 */
@Service
public class MyCustomerServiceImpl implements IMyCustomerService {

    private static final String BUSINESS_CUST_LEVEL_IMPORT_TASK_KEY = "BUSINESS_CUST_LEVEL_IMPORT_TASK_";
    private static final int BUSINESS_CUST_LEVEL_IMPORT_BATCH_SIZE = 1000;
    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private CustInfoBusinessMapper custInfoBusinessMapper;

    @Autowired
    private CustInfoMerchantMapper custInfoMerchantMapper;

    @Autowired
    private CustInfoRetailMapper custInfoRetailMapper;
    @Autowired
    private CustDeptUserGridMapper custDeptUserGridMapper;

    @Autowired
    private GridAdminDivisionRelateMapper gridAdminDivisionRelateMapper;

    @Autowired
    private AnchorCustMapper anchorCustMapper;

    @Autowired
    private AnchorMapper anchorMapper;

    @Autowired
    private GridSummarCountMapper gridSummarCountMapper;

    @Autowired
    private MerchantMcspInfoMapper merchantMcspInfoMapper;

    @Resource
    private GridSelectMapper gridSelectMapper;

    @Resource
    private MyCustomerGridSelectService myCustomerGridSelectService;

    @Resource
    private RedisCache redisCache;

    @Resource
    private NotificationService notificationService;

    @Resource(name = "excelImportExecutor")
    private ExecutorService excelImportExecutor;

    private static Logger logger = LoggerFactory.getLogger(MyCustomerServiceImpl.class);

    /**
     * 查询我的客户基本信息
     *
     * @param sysCustomerBasedata 客户信息
     * @return 客户信息集合
     */
    @Override
    @DataScope(deptAlias = "f", deptIdAlias = "dept_id", userAlias = "f", userIdAlias = "user_id")
    public List<CustBaseInfo> selectSysCustomerBasedataList(CustBaseInfo sysCustomerBasedata) {
        sysCustomerBasedata.setHead(false);
        if (SecurityUtils.userRole().equals("head") || SecurityUtils.userRole().equals("public")||SecurityUtils.userRole().equals("private")||SecurityUtils.userRole().equals("ops")) {
            sysCustomerBasedata.setHead(true);
            if (SecurityUtils.userRole().equals("private")){
                sysCustomerBasedata.setOpsDept("0");
            }else if (SecurityUtils.userRole().equals("public")){
                sysCustomerBasedata.setOpsDept("1");
            }else if (SecurityUtils.userRole().equals("ops")){
                sysCustomerBasedata.setOpsDept("2");
            }
        }
        //   增加判断，  是否   放开搜索权限
        if(StringUtils.isNotNull(sysCustomerBasedata.getCustId()) && sysCustomerBasedata.getCustId().length() ==  21) {
            ArrayList<SysDictData> sysDictTypeArrayList = new ArrayList<SysDictData>(redisCache.getCacheObject("sys_dict:sys_cust_search"));
            if (sysDictTypeArrayList != null && sysDictTypeArrayList.size() > 0) {
                Set<String> orgs = sysDictTypeArrayList.stream().map(SysDictData::getDictLabel).collect(Collectors.toSet());
                if (orgs.contains(SecurityUtils.getUsername().substring(0, 3))) {
                    sysCustomerBasedata.setHead(true);
                }
            }
        }

        sysCustomerBasedata.setStart((sysCustomerBasedata.getNum() - 1) * sysCustomerBasedata.getSize());
        sysCustomerBasedata.setEnd(sysCustomerBasedata.getNum() * sysCustomerBasedata.getSize());
        List<CustBaseInfo> sysCustomerBasedataList = new ArrayList<>();
        List<CustInfoBusiness> custInfoBusinessList = null;
        List<CustInfoRetail> custInfoRetailList = null;
        List<CustInfoMerchant> custInfoMerchantList = null;
        Long UserDept = GridSelectServiceImpl.getUserDept();//根据当前用户权限修改其可查客户
        sysCustomerBasedata.setUserDeptId(UserDept);

        StringBuilder metricStrBuilder = new StringBuilder();
        if (sysCustomerBasedata.getContinuousParams() != null && sysCustomerBasedata.getContinuousParams().size() > 0){
            for (ContinuousParam info : sysCustomerBasedata.getContinuousParams()){
                if (metricStrBuilder.length() > 0) {
                    metricStrBuilder.append(",");
                }
                metricStrBuilder.append(gridSummarCountMapper.selectDictLabelByDictValue(info.getKey()));
            }
        }
        if (sysCustomerBasedata.getDiscreteParams() != null && sysCustomerBasedata.getDiscreteParams().size() > 0){
            for (DiscreteParam info:sysCustomerBasedata.getDiscreteParams()){
                if (metricStrBuilder.length() > 0) {
                    metricStrBuilder.append(",");
                }
                metricStrBuilder.append(gridSummarCountMapper.selectDictLabelByDictValue(info.getKey()));
            }
        }

        if (sysCustomerBasedata.getCustType().equals("2")) {//客户类型传全部则将其改为空值跳过sql校验
            sysCustomerBasedata.setCustType(null);
        }
        if (sysCustomerBasedata.getCustTag().equals("111")) {//客户类型传全部则将其改为空值跳过sql校验
            sysCustomerBasedata.setCustTag(null);
        }
        if (SecurityUtils.userRole().equals("public")||SecurityUtils.userRole().equals("private")||SecurityUtils.userRole().equals("ops")||SecurityUtils.userRole().equals("branch")){
            sysCustomerBasedata.setDeptId(SecurityUtils.getDeptId());
        } else if (SecurityUtils.userRole().equals("outlet")) {
            sysCustomerBasedata.setOutletsId(SecurityUtils.getDeptId());
        }else if (SecurityUtils.userRole().equals("manager")){
            sysCustomerBasedata.setUserId(SecurityUtils.getUserId());
            sysCustomerBasedata.setUserName(SecurityUtils.getUsername());
        }
        if (sysCustomerBasedata.getCustPattern().equals("2")) {/* 客户标签为企业*/

            //custInfoBusinessList = custInfoBusinessMapper.selectCustInfoBusinessList(sysCustomerBasedata);
            if (sysCustomerBasedata.isHead() ||SecurityUtils.userRole().equals("private")||SecurityUtils.userRole().equals("public")|SecurityUtils.userRole().equals("ops")){
                custInfoBusinessList = custInfoBusinessMapper.selectCustInfoBusinessListHead(sysCustomerBasedata);
            }else {
                custInfoBusinessList = custInfoBusinessMapper.selectCustInfoBusinessListOps(sysCustomerBasedata);
            }

            logger.info("查出共" + custInfoBusinessList.size() + "笔：");
            for (int i = 0; i < custInfoBusinessList.size(); i++) {
                sysCustomerBasedata = new CustBaseInfo();
                BeanUtils.copyProperties(custInfoBusinessList.get(i), sysCustomerBasedata);

                //获取该客户经纬度
//                String custId = custInfoBusinessList.get(i).getCustId();
//                LaLuVo laLuVo = anchorMapper.selectLaLu(custId);
//                if (laLuVo != null && laLuVo.getLat() != null && laLuVo.getLng() != null) {
//                    sysCustomerBasedata.setLatitude(laLuVo.getLat());
//                    sysCustomerBasedata.setLongitude(laLuVo.getLng());
//                }
//                sysCustomerBasedata.setBelongUserName(gridAdminDivisionRelateMapper.getGridUserName(custInfoBusinessList.get(i).getCustId(), custInfoBusinessList.get(i).getRegionCode()));
//                sysCustomerBasedata.setManageUserName(custInfoBusinessList.get(i).getBelongUserName());
                sysCustomerBasedataList.add(sysCustomerBasedata);
            }
            sysCustomerBasedataList = setSysCustomerBasedataGrid(sysCustomerBasedataList);
        } else if (sysCustomerBasedata.getCustPattern().equals("1")) {/* 客户标签为商户*/
            if (sysCustomerBasedata.isHead()||SecurityUtils.userRole().equals("private")||SecurityUtils.userRole().equals("public")|SecurityUtils.userRole().equals("ops")){
                custInfoMerchantList = custInfoMerchantMapper.selectMyCustInfoMerchantListHead(sysCustomerBasedata);
            }else {
                custInfoMerchantList = custInfoMerchantMapper.selectMyCustInfoMerchantListOps(sysCustomerBasedata);
            }
            logger.info("查出共" + custInfoMerchantList.size() + "笔：");
            for (int i = 0; i < custInfoMerchantList.size(); i++) {
                sysCustomerBasedata = new CustBaseInfo();
                BeanUtils.copyProperties(custInfoMerchantList.get(i), sysCustomerBasedata);

                //获取该客户经纬度
//                String custId = custInfoMerchantList.get(i).getCustId();
//                LaLuVo laLuVo = anchorMapper.selectLaLu(custId);
//                if (laLuVo != null && laLuVo.getLat() != null && laLuVo.getLng() != null) {
//                    sysCustomerBasedata.setLatitude(laLuVo.getLat());
//                    sysCustomerBasedata.setLongitude(laLuVo.getLng());
//                }
//                sysCustomerBasedata.setBelongUserName(gridAdminDivisionRelateMapper.getGridUserName(custInfoMerchantList.get(i).getCustId(), custInfoMerchantList.get(i).getRegionCode()));
//                sysCustomerBasedata.setManageUserName(custInfoMerchantList.get(i).getBelongUserName());
                sysCustomerBasedataList.add(sysCustomerBasedata);
            }
            sysCustomerBasedataList = setSysCustomerBasedataGrid(sysCustomerBasedataList);
        } else if (sysCustomerBasedata.getCustPattern().equals("0")) {/* 客户标签为个人*/

            if (sysCustomerBasedata.isHead()||SecurityUtils.userRole().equals("private")||SecurityUtils.userRole().equals("public")|SecurityUtils.userRole().equals("ops")){
                custInfoRetailList = custInfoRetailMapper.selectMyCustInfoRetailListHead(sysCustomerBasedata);
            }else {
                custInfoRetailList = custInfoRetailMapper.selectMyCustInfoRetailListOps(sysCustomerBasedata);
            }
            logger.info("查出共" + custInfoRetailList.size() + "笔：");
            for (int i = 0; i < custInfoRetailList.size(); i++) {
                sysCustomerBasedata = new CustBaseInfo();
                BeanUtils.copyProperties(custInfoRetailList.get(i), sysCustomerBasedata);
                sysCustomerBasedata.setCustScale("0");

                //获取该客户经纬度
//                String custId = custInfoRetailList.get(i).getCustId();
//                LaLuVo laLuVo = anchorMapper.selectLaLu(custId);
//                if (laLuVo != null && laLuVo.getLat() != null && laLuVo.getLng() != null) {
//                    sysCustomerBasedata.setLatitude(laLuVo.getLat());
//                    sysCustomerBasedata.setLongitude(laLuVo.getLng());
//                }

//                sysCustomerBasedata.setBelongUserName(gridAdminDivisionRelateMapper.getGridUserName(custInfoRetailList.get(i).getCustId(), custInfoRetailList.get(i).getRegionCode()));
//                sysCustomerBasedata.setManageUserName(custInfoRetailList.get(i).getBelongUserName());
                sysCustomerBasedataList.add(sysCustomerBasedata);
            }
            sysCustomerBasedataList = setSysCustomerBasedataGrid(sysCustomerBasedataList);
        }
        for (CustBaseInfo custBaseInfo : sysCustomerBasedataList) {
            custBaseInfo.setPerMetric(metricStrBuilder.toString());
        }
        List<String> custIds = sysCustomerBasedataList.stream().map(CustBaseInfo::getCustId).collect(Collectors.toList());
        if (!custIds.isEmpty()){
            List<GridRelateVO> drawGridRelate = gridSelectMapper.getDrawGridRelate(custIds);
            List<GridRelateVO> regionGridRelate = gridSelectMapper.getRegionGridRelate(custIds);
            List<GridRelateVO> virtualGridRelate = myCustomerGridSelectService.getVirtualGridRelate(custIds);
            for (CustBaseInfo custBaseInfo : sysCustomerBasedataList) {
                custBaseInfo.setPerMetric(metricStrBuilder.toString());
                drawGridRelate.stream().filter(gridRelateVO -> gridRelateVO.getCustId().equals(custBaseInfo.getCustId())).findFirst().ifPresent(gridRelateVO -> {
                    custBaseInfo.setDrawBranchNames(gridRelateVO.getBranchNames());
                    custBaseInfo.setDrawOutletNames(gridRelateVO.getOutletNames());
                    custBaseInfo.setDrawUserNames(gridRelateVO.getUserNames());
                    custBaseInfo.setDrawGridName(gridRelateVO.getGridNames());
                });
                regionGridRelate.stream().filter(gridRelateVO -> gridRelateVO.getCustId().equals(custBaseInfo.getCustId())).findFirst().ifPresent(gridRelateVO -> {
                    custBaseInfo.setRegionBranchNames(gridRelateVO.getBranchNames());
                    custBaseInfo.setRegionOutletNames(gridRelateVO.getOutletNames());
                    custBaseInfo.setRegionUserNames(gridRelateVO.getUserNames());
                    custBaseInfo.setRegionTopGridName(gridRelateVO.getTopGridName());
                    custBaseInfo.setRegionSecGridName(gridRelateVO.getSecGridName());

                    custBaseInfo.setBelongBranchName(gridRelateVO.getBranchNames());
                    custBaseInfo.setBelongOutletName(gridRelateVO.getOutletNames());
                    custBaseInfo.setBelongUserNameList(gridRelateVO.getUserNames());
                });
                virtualGridRelate.stream().filter(gridRelateVO -> gridRelateVO.getCustId().equals(custBaseInfo.getCustId())).findFirst().ifPresent(gridRelateVO -> {
                    custBaseInfo.setVirtualBranchNames(gridRelateVO.getBranchNames());
                    custBaseInfo.setVirtualOutletNames(gridRelateVO.getOutletNames());
                    custBaseInfo.setVirtualUserNames(gridRelateVO.getUserNames());
                    custBaseInfo.setVirtualGridName(gridRelateVO.getGridNames());
                });
            }
        }
        return sysCustomerBasedataList;
    }

    public List<CustBaseInfo> setSysCustomerBasedataGrid(List<CustBaseInfo> custBaseInfos){
        List<String> custIdsList = custBaseInfos.stream().map(CustBaseInfo::getCustId).collect(Collectors.toList());
        if (custIdsList.size() > 0){
            List<CustDeptUserGrid> custDeptUserGridList = custDeptUserGridMapper.selectCustDeptUserGridListByCustIds(custIdsList);
            for (int i = 0; i < custBaseInfos.size(); i++) {
                if (StringUtils.isNotBlank(custBaseInfos.get(i).getCustId())){
                    String custId = custBaseInfos.get(i).getCustId();
                    List<CustDeptUserGrid> custDeptUserGridListByCustId = custDeptUserGridList.stream().filter(custDeptUserGrid -> custDeptUserGrid.getCustId().equals(custId)).collect(Collectors.toList());
                    custBaseInfos.get(i).setBelongUserNameList(custDeptUserGridListByCustId.stream().filter(custDeptUserGrid -> StringUtils.isNotBlank(custDeptUserGrid.getUserName())&&StringUtils.isNotBlank(custDeptUserGrid.getTellerId())).map(c->{
                        return c.getUserName()+"-"+c.getTellerId();
                    }).collect(Collectors.joining(",")));
                    custBaseInfos.get(i).setBelongBranchName(custDeptUserGridListByCustId.stream().filter(custDeptUserGrid -> StringUtils.isNotBlank(custDeptUserGrid.getDeptName())).map(CustDeptUserGrid::getDeptName).collect(Collectors.joining(",")));
                    custBaseInfos.get(i).setBelongOutletName(custDeptUserGridListByCustId.stream().filter(custDeptUserGrid -> StringUtils.isNotBlank(custDeptUserGrid.getOutlets())).map(CustDeptUserGrid::getOutlets).collect(Collectors.joining(",")));
                }
            }
        }
        return custBaseInfos;
    }

//    public CustBaseInfo setErrorDeptAndOutlets(CustBaseInfo custBaseInfo){
//        if (",".equals(custBaseInfo.getBelongBranchName())){
//            custBaseInfo.setBelongBranchName("");
//        }
//        if (",".equals(custBaseInfo.getBelongOutletName())){
//            custBaseInfo.setBelongOutletName("");
//        }
//        if (",".equals(custBaseInfo.getBelongUserNameList())){
//            custBaseInfo.setBelongUserNameList("");
//        }
//        return custBaseInfo;
//    }

    /**
     * @param code
     * @return
     */
    @Override
    public Long countCustRetailByRegion(String code) {
//        QueryWrapper<CustInfoRetail> queryWrapper = new QueryWrapper<>();
//        queryWrapper.select("distinct cust_id").lambda().likeRight(CustInfoRetail::getRegionCode, code);
        String deptCode = String.valueOf(SecurityUtils.getDeptId()).substring(0, 3);
        return custInfoRetailMapper.countByCode(code, deptCode);
    }

    /**
     * @param code
     * @return
     */
    @Override
    public Long countCustBusinessByRegion(String code) {
//        QueryWrapper<CustInfoBusiness> queryWrapper = new QueryWrapper<>();
//        queryWrapper.select("distinct cust_id").lambda().likeRight(CustInfoBusiness::getRegionCode, code);
        String deptCode = String.valueOf(SecurityUtils.getDeptId()).substring(0, 3);

        return custInfoBusinessMapper.countByCode(code, deptCode);
    }

    /**
     * @param code
     * @return
     */
    @Override
    public Long countCustMerchantByRegion(String code) {
//        QueryWrapper<CustInfoMerchant> queryWrapper = new QueryWrapper<>();
//        queryWrapper.select("distinct cust_id").lambda().likeRight(CustInfoMerchant::getRegionCode, code);
        String deptCode = String.valueOf(SecurityUtils.getDeptId()).substring(0, 3);
        return custInfoMerchantMapper.countByCode(code, deptCode);
    }

    /**
     * @param code
     * @param deptCode
     * @return
     */
    @Override
    public List<Long> countAllByCode(String code, String deptCode) {
        Long merchantCount = custInfoMerchantMapper.countByCode(code, deptCode);
        Long businessCount = custInfoBusinessMapper.countByCode(code, deptCode);
        Long retailCount = custInfoRetailMapper.countByCode(code, deptCode);
        return Arrays.asList(retailCount, merchantCount, businessCount);
    }


    /**
     * 我的客户数据变更
     *
     * @param custInfoUpdateFromAnchor 客户信息
     * @return 客户信息集合
     */
    @Override
    public int custInfoUpdate(CustInfoUpdateFromAnchor custInfoUpdateFromAnchor) {
        int result = 0;//0-失败；1-成功
        custInfoUpdateFromAnchor.setUpdateTime(new Date());
        String BusiCode = anchorCustMapper.getIndustryCode(custInfoUpdateFromAnchor.getBelongBusiness());
        if (BusiCode != null) {
            custInfoUpdateFromAnchor.setBelongBusiness(anchorCustMapper.getIndustryCode(custInfoUpdateFromAnchor.getBelongBusiness()));
        }
        if (custInfoUpdateFromAnchor.getCustType().equals("0")) {//个人
            if (custInfoUpdateFromAnchor.getAddressName() != null) {
                if (custInfoUpdateFromAnchor.getAddressName().equals("家庭地址")) {
                    custInfoUpdateFromAnchor.setAddressName("cust_location");
                } else if (custInfoUpdateFromAnchor.getAddressName().equals("工作地址")) {
                    custInfoUpdateFromAnchor.setAddressName("job_location");
                }  else if (custInfoUpdateFromAnchor.getAddressName().equals("常住地址")) {
                    custInfoUpdateFromAnchor.setAddressName("normal_location");
                }  else if (custInfoUpdateFromAnchor.getAddressName().equals("身份证地址")) {
                    custInfoUpdateFromAnchor.setAddressName("idc_location");
                }  else if (custInfoUpdateFromAnchor.getAddressName().equals("联系地址")) {
                    custInfoUpdateFromAnchor.setAddressName("relation_location");
                } else {
                    custInfoUpdateFromAnchor.setAddressName("register_location");
                }
            }
            Long CustNum = custInfoRetailMapper.getRetailNumByLegalId(custInfoUpdateFromAnchor.getLegalId());
            if (CustNum > 0) {//修改
                result = custInfoRetailMapper.updateRetailByAnchor(custInfoUpdateFromAnchor);
            } else {//新增
                result = custInfoRetailMapper.insertRetailByAnchor(custInfoUpdateFromAnchor);
            }
        } else if (custInfoUpdateFromAnchor.getCustType().equals("1")) {//商户
            if (custInfoUpdateFromAnchor.getAddressName() != null) {
                if (custInfoUpdateFromAnchor.getAddressName().equals("经营地址")) {
                    custInfoUpdateFromAnchor.setAddressName("cust_location");
                } else {
                    custInfoUpdateFromAnchor.setAddressName("register_location");
                }
            }
            Long CustNum = custInfoMerchantMapper.getMerchantNumByLegalId(custInfoUpdateFromAnchor.getLegalId());
            if (CustNum > 0) {//修改
                result = custInfoMerchantMapper.updateMerchantByAnchor(custInfoUpdateFromAnchor);
            } else {//新增
                result = custInfoMerchantMapper.insertMerchantByAnchor(custInfoUpdateFromAnchor);
            }
        } else if (custInfoUpdateFromAnchor.getCustType().equals("2")) {//企业
            if (custInfoUpdateFromAnchor.getAddressName() != null) {
                if (custInfoUpdateFromAnchor.getAddressName().equals("经营地址")) {
                    custInfoUpdateFromAnchor.setAddressName("cust_location");
                } else {
                    custInfoUpdateFromAnchor.setAddressName("register_location");
                }
            }
            Long CustNum = custInfoBusinessMapper.getBusinessNumByLegalId(custInfoUpdateFromAnchor.getLegalId());
            if (CustNum > 0) {//修改
                result = custInfoBusinessMapper.updateBusinessByAnchor(custInfoUpdateFromAnchor);
            } else {//新增
                result = custInfoBusinessMapper.insertBusinessByAnchor(custInfoUpdateFromAnchor);
            }
        }
        return result;
    }

    /**
     * 我的客户数据删除
     *
     * @param custInfoDeleteFromAnchor 客户信息
     * @return 客户信息集合
     */
    @Override
    public int custInfoDelete(CustInfoDeleteFromAnchor custInfoDeleteFromAnchor) {
        int result = 0;//0-失败；1-成功
        if (custInfoDeleteFromAnchor.getCustType().equals("0")) {//个人
            result = custInfoRetailMapper.deleteRetailByAnchor(custInfoDeleteFromAnchor);
        } else if (custInfoDeleteFromAnchor.getCustType().equals("1")) {//商户
            result = custInfoMerchantMapper.deleteMerchantByAnchor(custInfoDeleteFromAnchor);
        } else if (custInfoDeleteFromAnchor.getCustType().equals("2")) {//企业
            result = custInfoBusinessMapper.deleteBusinessByAnchor(custInfoDeleteFromAnchor);
        }
        return result;
    }

    public List<CustBaseInfo> selectAddress(List<CustBaseInfo> list){
        for (CustBaseInfo cbi:list
             ) {
            String custId = cbi.getCustId();
            LaLuVo laLuVo = anchorMapper.selectLaLu(custId);
            if (laLuVo != null && laLuVo.getLat() != null && laLuVo.getLng() != null) {
                cbi.setLatitude(laLuVo.getLat());
                cbi.setLongitude(laLuVo.getLng());
            }
        }
        return list;
    }

    public CustListSearchVo selectCustomListSearchVo(CustBaseInfo sysCustomerBasedata){
        CustListSearchVo custListSearchVo = new CustListSearchVo();
//        List<Map<String,Object>> continuousParams = new HashMap<>();
//        List<Map<String,Object>> discreteParams = new HashMap<>();
        List<Map<String,Object>> continuousParams = gridSummarCountMapper.selectContinuousParams(sysCustomerBasedata);
        List<Map<String,Object>> discreteParams = gridSummarCountMapper.selectDiscreteParams(sysCustomerBasedata);
        custListSearchVo.setContinuousParams(continuousParams);
        custListSearchVo.setDiscreteParams(discreteParams);
        return custListSearchVo;
    }

    @Override
    public MerchantMcspInfo selectmerchantMessage(String custId) {
        return merchantMcspInfoMapper.selectOne(new LambdaQueryWrapper<MerchantMcspInfo>().eq(MerchantMcspInfo::getCustId,custId));
    }

    @Override
    public String importBusinessCustLevelAsync(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            throw new ServiceException("导入文件不能为空");
        }
        byte[] fileBytes;
        try {
            fileBytes = file.getBytes();
        } catch (IOException e) {
            throw new ServiceException("读取导入文件失败");
        }
        String taskId = IdUtils.fastSimpleUUID();
        String userName = SecurityUtils.getUsername();
        String deptCode = SecurityUtils.getHeadId();
        BusinessCustLevelImportTaskVO taskVO = new BusinessCustLevelImportTaskVO();
        taskVO.setStatus("0");
        taskVO.setMessage("导入任务已提交，后台正在处理");
        taskVO.setTotalCount(0);
        taskVO.setSuccessCount(0);
        taskVO.setIgnoredCount(0);
        taskVO.setUserName(userName);
        taskVO.setCreateTime(formatNow());
        cacheBusinessCustLevelImportTask(taskId, taskVO);
        excelImportExecutor.submit(() -> doImportBusinessCustLevel(taskId, userName, deptCode, fileBytes));
        return taskId;
    }

    @Override
    public BusinessCustLevelImportTaskVO getBusinessCustLevelImportStatus(String taskId) {
        BusinessCustLevelImportTaskVO taskVO = redisCache.getCacheObject(getBusinessCustLevelImportTaskKey(taskId));
        if (taskVO == null) {
            throw new ServiceException("导入任务不存在或已过期");
        }
        return taskVO;
    }

    private void doImportBusinessCustLevel(String taskId, String userName, String deptCode, byte[] fileBytes) {
        BusinessCustLevelImportTaskVO taskVO = redisCache.getCacheObject(getBusinessCustLevelImportTaskKey(taskId));
        if (taskVO == null) {
            taskVO = new BusinessCustLevelImportTaskVO();
            taskVO.setUserName(userName);
            taskVO.setCreateTime(formatNow());
        }
        try {
            List<BusinessCustLevelImportExcelDTO> importRows = EasyExcel.read(new ByteArrayInputStream(fileBytes))
                    .head(BusinessCustLevelImportExcelDTO.class)
                    .sheet()
                    .doReadSync();

            Map<String, String> levelMap = new LinkedHashMap<>();
            if (importRows != null) {
                for (BusinessCustLevelImportExcelDTO row : importRows) {
                    String socialCreditCode = normalizeImportCell(row.getSocialCreditCode());
                    String custLevel = normalizeImportCell(row.getCustLevel());
                    if (StringUtils.isEmpty(socialCreditCode)) {
                        continue;
                    }
                    levelMap.put(socialCreditCode, custLevel);
                }
            }

            if (levelMap.isEmpty()) {
                throw new ServiceException("Excel中未识别到有效的统信码和价值分层数据");
            }

            List<String> existingSocialCreditCodes = getExistingBusinessSocialCreditCodes(new ArrayList<>(levelMap.keySet()), deptCode);
            Set<String> existingCodeSet = new HashSet<>(existingSocialCreditCodes);
            List<BusinessCustLevelImportExcelDTO> updateList = new ArrayList<>();
            for (Map.Entry<String, String> entry : levelMap.entrySet()) {
                if (!existingCodeSet.contains(entry.getKey())) {
                    continue;
                }
                BusinessCustLevelImportExcelDTO dto = new BusinessCustLevelImportExcelDTO();
                dto.setSocialCreditCode(entry.getKey());
                dto.setCustLevel(entry.getValue());
                updateList.add(dto);
            }

            batchUpdateBusinessCustLevel(updateList, deptCode);

            int totalCount = levelMap.size();
            int successCount = updateList.size();
            int ignoredCount = totalCount - successCount;
            String message = String.format("公司客户视图分层分类数据导入完成，成功更新%d条，忽略%d条", successCount, ignoredCount);

            taskVO.setStatus("1");
            taskVO.setMessage(message);
            taskVO.setTotalCount(totalCount);
            taskVO.setSuccessCount(successCount);
            taskVO.setIgnoredCount(ignoredCount);
            taskVO.setFinishTime(formatNow());
            cacheBusinessCustLevelImportTask(taskId, taskVO);
            notificationService.sendNotification(userName, message);
        } catch (Exception e) {
            String errorMsg = StringUtils.isNotEmpty(e.getMessage()) ? e.getMessage() : "导入失败，请检查文件内容";
            taskVO.setStatus("2");
            taskVO.setMessage(errorMsg);
            taskVO.setFinishTime(formatNow());
            cacheBusinessCustLevelImportTask(taskId, taskVO);
            notificationService.sendNotification(userName, "公司客户视图分层分类数据导入失败：" + errorMsg);
            logger.error("公司客户视图分层分类数据导入失败，taskId={}", taskId, e);
        }
    }

    private void batchUpdateBusinessCustLevel(List<BusinessCustLevelImportExcelDTO> updateList, String deptCode) {
        if (updateList == null || updateList.isEmpty()) {
            return;
        }
        for (int i = 0; i < updateList.size(); i += BUSINESS_CUST_LEVEL_IMPORT_BATCH_SIZE) {
            int endIndex = Math.min(i + BUSINESS_CUST_LEVEL_IMPORT_BATCH_SIZE, updateList.size());
            custInfoBusinessMapper.batchUpdateCustLevelBySocialCreditCode(updateList.subList(i, endIndex), deptCode);
        }
    }

    private List<String> getExistingBusinessSocialCreditCodes(List<String> socialCreditCodes, String deptCode) {
        if (socialCreditCodes == null || socialCreditCodes.isEmpty()) {
            return Collections.emptyList();
        }
        List<String> existingSocialCreditCodes = new ArrayList<>();
        for (int i = 0; i < socialCreditCodes.size(); i += BUSINESS_CUST_LEVEL_IMPORT_BATCH_SIZE) {
            int endIndex = Math.min(i + BUSINESS_CUST_LEVEL_IMPORT_BATCH_SIZE, socialCreditCodes.size());
            List<String> batchCodes = socialCreditCodes.subList(i, endIndex);
            List<String> batchResult = custInfoBusinessMapper.selectExistingSocialCreditCodes(batchCodes, deptCode);
            if (batchResult != null && !batchResult.isEmpty()) {
                existingSocialCreditCodes.addAll(batchResult);
            }
        }
        return existingSocialCreditCodes;
    }

    private void cacheBusinessCustLevelImportTask(String taskId, BusinessCustLevelImportTaskVO taskVO) {
        redisCache.setCacheObject(getBusinessCustLevelImportTaskKey(taskId), taskVO, 24, TimeUnit.HOURS);
    }

    private String getBusinessCustLevelImportTaskKey(String taskId) {
        return BUSINESS_CUST_LEVEL_IMPORT_TASK_KEY + taskId;
    }

    private String normalizeImportCell(String value) {
        if (value == null) {
            return null;
        }
        String trimmedValue = value.trim();
        return trimmedValue.isEmpty() ? null : trimmedValue;
    }

    private String formatNow() {
        return LocalDateTime.now().format(DATE_TIME_FORMATTER);
    }

}
