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

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.ibs.customerselect.mapper.CustInfoBusinessMapper;
import com.ruoyi.ibs.grid.domain.vo.AnchorDetail;
import com.ruoyi.ibs.grid.mapper.AnchorMapper;
import com.ruoyi.ibs.grid.service.AnchorService;
import com.ruoyi.ibs.grid.util.CustExcelUtil;
import com.ruoyi.ibs.list.domain.*;
import com.ruoyi.ibs.list.mapper.*;
import com.ruoyi.ibs.list.service.ICustInfoRetailService;
import com.ruoyi.system.mapper.SysIndustryMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static com.ruoyi.common.utils.SecurityUtils.*;
import static com.ruoyi.ibs.list.domain.Constans.*;

/**
 * 对私客户信息Service业务层处理
 *
 * @author ruoyi
 * @date 2024-09-19
 */
@Service
public class CustInfoRetailServiceImpl implements ICustInfoRetailService {
    @Autowired
    private CustInfoRetailMapper custInfoRetailMapper;
    @Autowired
    private CustInfoBusinessMapper custInfoBusinessMapper;
    @Autowired
    private CustInfoMerchantMapper custInfoMerchantMapper;
    @Autowired
    private FamilyMembersMapper familyMembersMapper;
    @Autowired
    private SignedProductsMapper signedProductsMapper;
    @Autowired
    private OtherBankRateMapper otherBankRateMapper;
    @Autowired
    private SocialSecurityMapper socialSecurityMapper;
    @Autowired
    private AnchorService anchorService;
    @Autowired
    private SysIndustryMapper sysIndustryMapper;
    @Autowired
    private AnchorMapper anchorMapper;

    /**
     * 查询对私客户信息
     *
     * @param id 对私客户信息主键
     * @return 对私客户信息
     */
    @Override
    public CustInfoRetail selectCustInfoRetailById(Long id) {
        CustInfoRetail custInfoRetail = custInfoRetailMapper.selectCustInfoRetailById(id);
        //custInfoRetail.setJsonLabel(JSONObject.parseObject(custInfoRetail.getLabel()));
        return custInfoRetail;
    }
    @Override
    public CustInfoRetail selectCustInfoRetailBycustIdc(String custIdc) {
        CustInfoRetail custInfoRetail = custInfoRetailMapper.selectCustInfoRetailBycustIdc(custIdc);
        //custInfoRetail.setJsonLabel(JSONObject.parseObject(custInfoRetail.getLabel()));
        return custInfoRetail;
    }

    @Override
    public CustInfoRetailFoldVo selectCustInfoRetailFoldVoBycustIdc(String custIdc) {
        CustInfoRetailFoldVo custInfoRetailFoldVo = new CustInfoRetailFoldVo();
        if (custIdc!=null&&!custIdc.equals("")){
            SocialSecurity socialSecurity = new SocialSecurity();
            socialSecurity.setCustIdc(custIdc);
            List<SocialSecurity> socialSecurities = socialSecurityMapper.selectSocialSecurityList(socialSecurity);
            if (socialSecurities!=null&&socialSecurities.size()>0){
                custInfoRetailFoldVo.setSocialSecurity(socialSecurities.get(0));
            }
            OtherBankRate otherBankRate = new OtherBankRate();
            otherBankRate.setCustIdc(custIdc);
            List<OtherBankRate> otherBankRates = otherBankRateMapper.selectOtherBankRateList(otherBankRate);
            custInfoRetailFoldVo.setOtherBankRates(otherBankRates);

        }

        return custInfoRetailFoldVo;
    }

    @Override
    public CustInfoRetailVo selectCustInfoRetailVoByCustId(String custId) {
        CustInfoRetailVo custInfoRetailVo = new CustInfoRetailVo();
        CustInfoRetail custInfoRetail = selectCustInfoRetailByCustId(custId);
        if (custInfoRetail==null){
            throw new IllegalArgumentException("非我行客户");
        }
        SignedProducts signedProducts = signedProductsMapper.selectSignedProductsByCurrdeposFlag(custInfoRetail.getCustId());
        if (signedProducts!=null){
            custInfoRetailVo.setSignedProducts(Constans.convertSignedProducts(signedProducts));
        }
//        custInfoRetailVo.setGridUserName(getNickNames(custInfoRetail.getCustId()));
//        custInfoRetailVo.setGridName(getGridNames(custInfoRetail.getCustId()));
        custInfoRetailVo.setCmpmUserName(getCmpmNickNames(custInfoRetail.getCustId()));
        custInfoRetailVo.setCmpmUserLists(getCmpmUserList(custInfoRetail.getCustId()));
        if (custInfoRetail!=null){
            custInfoRetailVo.setCustInfoRetail(custInfoRetail);
            custInfoRetailVo = custInfoRetailVoSetGrid(custInfoRetailVo);
            if (custInfoRetail.getCustIdc()!=null&& !custInfoRetail.getCustIdc().equals("")){
                CustInfoBusiness custInfoBusiness = new CustInfoBusiness();
                custInfoBusiness.setCustIdc(custInfoRetail.getCustIdc());
                List<CustInfoBusiness> custInfoBusinesses = custInfoBusinessMapper.selectCustInfoBusinessLists(custInfoBusiness);
                CustInfoMerchant custInfoMerchant = new CustInfoMerchant();
                custInfoMerchant.setCustIdc(custInfoRetail.getCustIdc());
                List<CustInfoMerchant> custInfoMerchants = custInfoMerchantMapper.selectCustInfoMerchantList(custInfoMerchant);
                custInfoRetailVo.setBusinessList(custInfoBusinesses);
                custInfoRetailVo.setMerchantList(custInfoMerchants);
                if (custInfoRetail.getCustIdc()!=null&& !custInfoRetail.getCustIdc().equals("")){
                    FamilyMembers familyMembers = new FamilyMembers();
                    familyMembers.setCustId(custInfoRetail.getCustId());
                    List<FamilyMembers> familyMembersList = familyMembersMapper.selectFamilyMembersList(familyMembers);
                    custInfoRetailVo.setFamilyMembers(familyMembersList);
                }

            }
            custInfoRetailVo.setCommunity(custInfoRetailMapper.selectCommunityBycustId(custInfoRetail.getCustId()));
            if (custInfoRetail.getCustIdc()!=null){
                custInfoRetailVo.setAddressDetails(anchorMapper.selectCustAddressList(custInfoRetail.getCustIdc()));
            }

        }
        return custInfoRetailVo;
    }
    public List<CmpmUserList> getCmpmUserList(String custId){
        String roleName = userRole();
        List<CmpmUserList> list = new ArrayList<>();
        if (custId==null||custId.equals("")){
            return null;
        }
        if (ROLE_HEAD.equals(roleName)||ROLE_HeadPrivate.equals(roleName)||ROLE_HeadOps.equals(roleName)) {
            list = custInfoRetailMapper.selectCmpmNickName2(custId, null,null);
        }else if ("branch".equals(roleName)){
            list = custInfoRetailMapper.selectCmpmNickName2(custId,getDeptId(),null);
        }else {
            list = custInfoRetailMapper.selectCmpmNickName2(custId,getDeptId(),getUsername());
        }
        CmpmUserList cmpmUserList1 = new CmpmUserList("信用卡营销客户经理","无","203","205");
        CmpmUserList cmpmUserList2 = new CmpmUserList("信用卡责任客户经理","无","203","207");
        CmpmUserList cmpmUserList3 = new CmpmUserList("代发工资有效户客户经理","无","204","202");
        CmpmUserList cmpmUserList4 = new CmpmUserList("国际业务结算客户经理","无","207","201");
        CmpmUserList cmpmUserList5 = new CmpmUserList("国际业务贸易融资客户经理","无","207","202");
        CmpmUserList cmpmUserList6 = new CmpmUserList("存款客户经理","无","101","001");
        CmpmUserList cmpmUserList7 = new CmpmUserList("贷款客户经理","无","103","001");
        String custType = custId.substring(0,3);
        //此处重写CmpmUserList的equals和hashcode方法，改为只判断codeNoLevel1和2.故list.contains方法可用
        if (custType.equals("101")){
            if(!list.contains(cmpmUserList1)){
                list.add(cmpmUserList1);
            }
            if(!list.contains(cmpmUserList2)){
                list.add(cmpmUserList2);
            }
            if(!list.contains(cmpmUserList4)){
                list.add(cmpmUserList4);
            }
            if(!list.contains(cmpmUserList5)){
                list.add(cmpmUserList5);
            }
            if(!list.contains(cmpmUserList6)){
                list.add(cmpmUserList6);
            }
            if(!list.contains(cmpmUserList7)){
                list.add(cmpmUserList7);
            }
        }else if(custType.equals("202")){
            if(!list.contains(cmpmUserList3)){
                list.add(cmpmUserList3);
            }
            if(!list.contains(cmpmUserList4)){
                list.add(cmpmUserList4);
            }
            if(!list.contains(cmpmUserList5)){
                list.add(cmpmUserList5);
            }
            if(!list.contains(cmpmUserList6)){
                list.add(cmpmUserList6);
            }
            if(!list.contains(cmpmUserList7)){
                list.add(cmpmUserList7);
            }
        }
        return list;
    }
//    @Override
//    public String getNickNames(String custId){
//        String roleName = userRole();
//        List<String> names = new ArrayList<>();
//        if (custId==null||custId.equals("")){
//            return "";
//        }
//        if ("head".equals(roleName)||"admin".equals(roleName)) {
//            names = custInfoRetailMapper.selectNickName(custId, null,null,"0");
//        }else if ("branch".equals(roleName)){
//            names = custInfoRetailMapper.selectNickName(custId,getDeptId(),null);
//        }else {
//            names = custInfoRetailMapper.selectNickName(custId,getDeptId(),getUsername());
//        }
//        String res = "";
//        for (int i = 0; i < names.size(); i++) {
//            if (!names.get(i).equals("")){
//                res = res+names.get(i)+",";
//            }
//
//        }
//        if (names.size()>0){
//            res = res.substring(0,res.length()-1);
//        }
//        return res;
//    }
//
//    @Override
//    public String getGridNames(String custId) {
//        String roleName = userRole();
//        List<GridInfo> gridNames = new ArrayList<>();
//        if (custId==null||custId.equals("")){
//            return "";
//        }
//        if ("head".equals(roleName)||"admin".equals(roleName)) {
//            gridNames = custInfoRetailMapper.selectGridName(custId, null,null);
//        }else if ("branch".equals(roleName)){
//            gridNames = custInfoRetailMapper.selectGridName(custId,getDeptId(),null);
//        }else {
//            gridNames = custInfoRetailMapper.selectGridName(custId,getDeptId(),getUsername());
//        }
//
//        String res = "";
//        Set<String> gridSet = new HashSet<>();
//        for (int i = 0; i < gridNames.size(); i++) {
//            if (StringUtils.isNotBlank(gridNames.get(i).getGridName())){
//                gridSet.add(gridNames.get(i).getGridName());
//            }
//            if (StringUtils.isNotBlank(gridNames.get(i).getGridName2())){
//                gridSet.add(gridNames.get(i).getGridName2());
//            }
//
//        }
//        if (gridNames.size()>0){
//            for (String gridName : gridSet){
//                res = res+gridName+",";
//            }
//            res = res.substring(0,res.length()-1);
//        }
//        return res;
//    }

    public CustInfoRetailVo custInfoRetailVoSetGrid(CustInfoRetailVo custInfoRetailVo){
            String custId = custInfoRetailVo.getCustInfoRetail().getCustId();
            String roleName = userRole();
            List<String> LsNames = new ArrayList<>();
            if (custId==null||custId.equals("")){
                return custInfoRetailVo;
            }
            List<GridInfo> gridInfos = new ArrayList<>();
            if (ROLE_HEAD.equals(roleName)||ROLE_HeadPrivate.equals(roleName)||ROLE_HeadOps.equals(roleName)||ROLE_HeadPublic.equals(roleName)) {
                 gridInfos = custInfoRetailMapper.selectGridInfo(custId, null,null);
            }else if ("branch".equals(roleName)){
                 gridInfos = custInfoRetailMapper.selectGridInfo(custId,getDeptId(),null);
            }else {
                 gridInfos = custInfoRetailMapper.selectGridInfo(custId,getDeptId(),getUsername());
            }
        //零售部行政网格信息
         String XzLsGridUserName = "";
         String XzLsGridName= "";
        //公司部行政网格信息
         String XzGsGridUserName= "";
         String XZGsGridName= "";
        //运管部行政网格信息
         String XzYgGridUserName= "";
         String XZYgGridName= "";
         Set<String> gridSetLs = new HashSet<>();
         Set<String> gridSetGs = new HashSet<>();
         Set<String> gridSetYg = new HashSet<>();
         for (int i = 0; i < gridInfos.size(); i++) {
             if ("0".equals(gridInfos.get(i).getOpsDept())){
                 if (!gridInfos.get(i).getUserName().equals("")){
                     XzLsGridUserName = XzLsGridUserName+gridInfos.get(i).getUserName()+",";
                 }
                 if (StringUtils.isNotBlank(gridInfos.get(i).getGridName())&&StringUtils.isNotBlank(gridInfos.get(i).getGridName2())){
                     gridSetLs.add(gridInfos.get(i).getGridName()+"-"+gridInfos.get(i).getGridName2());
                 }
                 if (StringUtils.isNotBlank(gridInfos.get(i).getGridName())&&StringUtils.isBlank(gridInfos.get(i).getGridName2())){
                     gridSetLs.add(gridInfos.get(i).getGridName());
                 }
             }
             if ("1".equals(gridInfos.get(i).getOpsDept())){
                 if (!gridInfos.get(i).getUserName().equals("")){
                     XzGsGridUserName = XzGsGridUserName+gridInfos.get(i).getUserName()+",";
                 }
                 if (StringUtils.isNotBlank(gridInfos.get(i).getGridName())&&StringUtils.isNotBlank(gridInfos.get(i).getGridName2())){
                     gridSetGs.add(gridInfos.get(i).getGridName()+"-"+gridInfos.get(i).getGridName2());
                 }
                 if (StringUtils.isNotBlank(gridInfos.get(i).getGridName())&&StringUtils.isBlank(gridInfos.get(i).getGridName2())){
                     gridSetGs.add(gridInfos.get(i).getGridName());
                 }
             }
             if ("2".equals(gridInfos.get(i).getOpsDept())){
                 if (!gridInfos.get(i).getUserName().equals("")){
                     XzYgGridUserName = XzYgGridUserName+gridInfos.get(i).getUserName()+",";
                 }
                 if (StringUtils.isNotBlank(gridInfos.get(i).getGridName())&&StringUtils.isNotBlank(gridInfos.get(i).getGridName2())){
                     gridSetYg.add(gridInfos.get(i).getGridName()+"-"+gridInfos.get(i).getGridName2());
                 }
                 if (StringUtils.isNotBlank(gridInfos.get(i).getGridName())&&StringUtils.isBlank(gridInfos.get(i).getGridName2())){
                     gridSetYg.add(gridInfos.get(i).getGridName());
                 }
             }

            }
         custInfoRetailVo.setXzLsGridUserName(strReplace(XzLsGridUserName));
         custInfoRetailVo.setXzGsGridUserName(strReplace(XzGsGridUserName));
         custInfoRetailVo.setXzYgGridUserName(strReplace(XzYgGridUserName));
        for (String gridName : gridSetLs){
            XzLsGridName = XzLsGridName+gridName+",";
        }
        for(String gridName : gridSetGs){
            XZGsGridName = XZGsGridName+gridName+",";
        }
        for(String gridName : gridSetYg){
            XZYgGridName = XZYgGridName+gridName+",";
        }
        custInfoRetailVo.setXzLsGridName(strReplace(XzLsGridName));
        custInfoRetailVo.setXzGsGridName(strReplace(XZGsGridName));
        custInfoRetailVo.setXzYgGridName(strReplace(XZYgGridName));
        return custInfoRetailVo;
    }

    public String strReplace(String str){
        if (str.length()>1&&str.charAt(str.length()-1)==','){
            str = str.substring(0,str.length()-1);
        }
        return str;
    }

    //获取绩效管护客户经理
    public String getCmpmNickNames(String custId){
        String roleName = userRole();
        List<String> names = new ArrayList<>();
        if (custId==null||custId.equals("")){
            return "";
        }
        if (ROLE_HEAD.equals(roleName)||ROLE_HeadPrivate.equals(roleName)||ROLE_HeadOps.equals(roleName)) {
            names = custInfoRetailMapper.selectCmpmNickName(custId, null,null);
        }else if ("branch".equals(roleName)){
            names = custInfoRetailMapper.selectCmpmNickName(custId,getDeptId(),null);
        }else {
            names = custInfoRetailMapper.selectCmpmNickName(custId,getDeptId(),getUsername());
        }
        String res = "";
        for (int i = 0; i < names.size(); i++) {
            if (!names.get(i).equals("")){
                res = res+names.get(i)+",";
            }

        }
        if (names.size()>0){
            res = res.substring(0,res.length()-1);
        }
        return res;
    }

    /**
     * 查询对私客户信息列表
     *
     * @param custInfoRetail 对私客户信息
     * @return 对私客户信息
     */
    @Override
    public List<CustInfoRetail> selectCustInfoRetailList(CustInfoRetail custInfoRetail) {
        return custInfoRetailMapper.selectCustInfoRetailList(custInfoRetail);
    }

    @Override
    public List<CustInfoRetail> selectCustInfoRetailListByKeyword(String keyword,Long start,Long size) {
        String roleName = userRole();
        List<CustInfoRetail> custInfoRetails = new ArrayList<>();
        if (ROLE_HEAD.equals(roleName)||ROLE_HeadPrivate.equals(roleName)||ROLE_HeadOps.equals(roleName)){
            custInfoRetails = custInfoRetailMapper.selectCustInfoRetailListByKeyword(keyword,start,size);
        }
        else if (ROLE_BRANCH.equals(roleName)){
            custInfoRetails = custInfoRetailMapper.selectCustInfoRetailListByKeywordBranchAndManager(keyword,getDeptId(),null,null,null,start,size);
        }else if (ROLE_Outlet.equals(roleName)){
            custInfoRetails = custInfoRetailMapper.selectCustInfoRetailListByKeywordBranchAndManager(keyword,null,getDeptId(),null,null,start,size);
        }
        else {
            custInfoRetails = custInfoRetailMapper.selectCustInfoRetailListByKeywordBranchAndManager(keyword,null,null,getUserId(),null,start,size);
        }
        return custInfoRetails;
    }

    /**
     * 新增对私客户信息
     *
     * @param custInfoRetail 对私客户信息
     * @return 结果
     */
    @Override
    public int insertCustInfoRetail(CustInfoRetail custInfoRetail) {
        return custInfoRetailMapper.insertCustInfoRetail(custInfoRetail);
    }

    @Override
    public AjaxResult insertCustInfoRetailVo(CustInfoRetail custInfoRetail, String relateMerchant, String relateBusiness , String fmyName, String fmyBusi, String fmyTel, String fmyRln) {
        if (custInfoRetail.getCustIdc()==null||"".equals(custInfoRetail.getCustIdc())
                ||custInfoRetail.getCustName()==null||"".equals(custInfoRetail.getCustName())){
            return AjaxResult.error("缺乏必要建档信息，无法建档成功");
        }
        CustInfoRetail retail = new CustInfoRetail();
        retail.setCustIdc(custInfoRetail.getCustIdc());
        List<CustInfoRetail> custInfoRetails = custInfoRetailMapper.selectCustInfoRetailList(retail);
        if (custInfoRetails!=null&&custInfoRetails.size()>0){
            return AjaxResult.error("当前客户身份证号已建档,无需重复建档");
        }
        custInfoRetail.setCustId("101"+custInfoRetail.getCustIdc());
        insertCustInfoRetail(custInfoRetail);
        if (relateMerchant!=null&&!relateMerchant.isEmpty()){
            CustInfoMerchant custInfoMerchant = new CustInfoMerchant();
            custInfoMerchant.setCustIdc(custInfoRetail.getCustIdc());
            custInfoMerchant.setCustName(relateMerchant);
            custInfoMerchant.setLpName(custInfoRetail.getCustName());
            custInfoMerchantMapper.insertCustInfoMerchant(custInfoMerchant);
        }
        if (relateBusiness!=null&&!relateBusiness.isEmpty()){
            CustInfoBusiness custInfoBusiness = new CustInfoBusiness();
            custInfoBusiness.setCustIdc(custInfoRetail.getCustIdc());
            custInfoBusiness.setCustName(relateBusiness);
            custInfoBusiness.setLpName(custInfoRetail.getCustName());
            custInfoBusinessMapper.insertCustInfoBusiness(custInfoBusiness);
        }
        if (fmyName!=null&&!fmyName.isEmpty()){
            FamilyMembers familyMember = new FamilyMembers();
            familyMember.setFmyName(fmyName);
            familyMember.setBelongBusi(fmyBusi);
            familyMember.setTel(fmyTel);
            familyMember.setFmyRln(fmyRln);
            familyMember.setCustId(custInfoRetail.getCustId());
            familyMembersMapper.insertFamilyMembers(familyMember);
        }
        return AjaxResult.success("建档成功");
    }

    /**
     * 修改对私客户信息
     *
     * @param custInfoRetail 对私客户信息
     * @return 结果
     */
    @Override
    public AjaxResult updateCustInfoRetail(CustInfoRetail custInfoRetail) {
        custInfoRetail.setUpdateTime(DateUtils.getNowDate());
        if (custInfoRetail.getLabel()!=null&&!custInfoRetail.getLabel().isEmpty()){
            if (Constans.labelDuplicate(custInfoRetail.getLabel())){
                return AjaxResult.error("客户标签不允许重复");
            }
        }

        if(StringUtils.isNotEmpty(custInfoRetail.getLabel())){
            custInfoRetailMapper.updateCustInfoRetailLabel(custInfoRetail);
        }else{
            custInfoRetailMapper.updateCustInfoRetail(custInfoRetail);
        }

         AnchorDetail anchorDetail = new AnchorDetail();
         anchorDetail.setLegalId(custInfoRetail.getCustIdc());
         anchorDetail.setAnchorName(custInfoRetail.getCustName());
         if (custInfoRetail.getBelongBusi()!=null){
             anchorDetail.setBelongBusiness(sysIndustryMapper.selectIndustryNameByCode(custInfoRetail.getBelongBusi()));
         }
         anchorService.update(anchorDetail);
         return AjaxResult.success("客户信息更新成功");
    }

    /**
     * 批量删除对私客户信息
     *
     * @param ids 需要删除的对私客户信息主键
     * @return 结果
     */
    @Override
    public int deleteCustInfoRetailByIds(Long[] ids) {
        return custInfoRetailMapper.deleteCustInfoRetailByIds(ids);
    }

    /**
     * 删除对私客户信息信息
     *
     * @param id 对私客户信息主键
     * @return 结果
     */
    @Override
    public int deleteCustInfoRetailById(Long id) {
        return custInfoRetailMapper.deleteCustInfoRetailById(id);
    }

    @Override
    public CustInfoRetail selectCustInfoRetailByCustId(String custId) {
        return custInfoRetailMapper.selectCustInfoRetailByCustId(custId);
    }
    @Override
    public void exportRetailDetail(HttpServletResponse response, String custId) throws Exception {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        CustInfoRetailVo retail = selectCustInfoRetailVoByCustId(custId);
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Merchant Information");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=商户视图详情.xlsx");
        // 创建标题行
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("模块名称");
        headerRow.createCell(1).setCellValue("字段");
        headerRow.createCell(2).setCellValue("字段内容");

        int rowNum = 1; // 从第二行开始填充数据
        int startRow = rowNum;

        // 填充基础信息
        CustExcelUtil.fillRow(sheet, rowNum++, "基础信息", "姓名", retail.getCustInfoRetail().getCustName());
        CustExcelUtil.fillRow(sheet, rowNum++, "", "性别", retail.getCustInfoRetail().getCustGender());
        CustExcelUtil.fillRow(sheet, rowNum++, "", "年龄", retail.getCustInfoRetail().getCustAge());
        CustExcelUtil.fillRow(sheet, rowNum++, "", "身份证号", retail.getCustInfoRetail().getCustIdc());
        CustExcelUtil.fillRow(sheet, rowNum++, "", "出生日期", retail.getCustInfoRetail().getBirthday());
        CustExcelUtil.fillRow(sheet, rowNum++, "", "手机号", retail.getCustInfoRetail().getCustPhone());
        CustExcelUtil.fillRow(sheet, rowNum++, "", "婚姻状况", retail.getCustInfoRetail().getIsMarried());
        CustExcelUtil.fillRow(sheet, rowNum++, "", "年收入", retail.getCustInfoRetail().getCustSalary());
        CustExcelUtil.fillRow(sheet, rowNum++, "", "学历", retail.getCustInfoRetail().getCustEdu());
        CustExcelUtil.fillRow(sheet, rowNum++, "", "行业名称", retail.getCustInfoRetail().getBelongBusi());
        CustExcelUtil.fillRow(sheet, rowNum++, "", "客户号", retail.getCustInfoRetail().getCustId());
        CustExcelUtil.fillRow(sheet, rowNum++, "", "客户内码", retail.getCustInfoRetail().getCustIsn());
        CustExcelUtil.fillRow(sheet, rowNum++, "", "户籍地址", retail.getCustInfoRetail().getRegisterLocation());
        CustExcelUtil.fillRow(sheet, rowNum++, "", "工作地址", retail.getCustInfoRetail().getJobLocation());
        CustExcelUtil.fillRow(sheet, rowNum++, "", "住宅地址", retail.getCustInfoRetail().getCustLocation());
        CustExcelUtil.fillRow(sheet, rowNum++, "", "网格客户经理", retail.getGridUserName());
        CustExcelUtil.fillRow(sheet, rowNum++, "", "绩效客户经理", retail.getCmpmUserName());
        if (retail.getCustInfoRetail().getUpdateTime() != null) {
            CustExcelUtil.fillRow(sheet, rowNum++, "", "更新时间", sdf.format(retail.getCustInfoRetail().getUpdateTime()));
        }else {
            CustExcelUtil.fillRow(sheet, rowNum++, "", "更新时间", "");
        }
        //合并基础信息列单元格
        CustExcelUtil.mergeCells(sheet, startRow, rowNum - 1, 0, "基础信息");
        startRow = rowNum;

        //社保信息待补充，将对应列值输入到fieldValue中即可，String类型
        CustExcelUtil.fillRow(sheet, rowNum++, "社保信息", "单位性质分", "");
        CustExcelUtil.fillRow(sheet, rowNum++, "", "负面信息分", "");
        CustExcelUtil.fillRow(sheet, rowNum++, "", "缴纳时长分", "");
        CustExcelUtil.fillRow(sheet, rowNum++, "", "缴纳稳定分", "");
        CustExcelUtil.fillRow(sheet, rowNum++, "", "缴纳异常分", "");
        CustExcelUtil.fillRow(sheet, rowNum++, "", "客户资质分", "");
        CustExcelUtil.fillRow(sheet, rowNum++, "", "区域等级分", "");
        CustExcelUtil.fillRow(sheet, rowNum++, "", "社保类型分", "");
        CustExcelUtil.fillRow(sheet, rowNum++, "", "收入变化分", "");
        CustExcelUtil.fillRow(sheet, rowNum++, "", "收入水平分", "");
        CustExcelUtil.fillRow(sheet, rowNum++, "", "养老金获得分", "");
        CustExcelUtil.fillRow(sheet, rowNum++, "", "优质客户标签", "");
        //合并社保信息单元格
        CustExcelUtil.mergeCells(sheet, startRow, rowNum - 1, 0, "社保信息");
        startRow = rowNum;

        //公积金信息待补充，将对应列值输入到fieldValue中即可，String类型
        CustExcelUtil.fillRow(sheet, rowNum++, "公积金信息", "", "");
        startRow = rowNum;
        //征信信息待补充，若为list，则下面三行写入list循环中即可
        CustExcelUtil.fillRow(sheet, rowNum++, "征信信息", "他行名称", "");
        CustExcelUtil.fillRow(sheet, rowNum++, "", "他行利率", "");
        CustExcelUtil.fillRow(sheet, rowNum++, "", "测算利率", "");
        //社保信息单元格合并，合并语句写于for循环外
        CustExcelUtil.mergeCells(sheet, startRow, rowNum - 1, 0, "征信信息");
        startRow = rowNum;
        List<Products> list = Constans.convertProducts(signedProductsMapper.selectSignedProductsByCurrdeposFlag(retail.getCustInfoRetail().getCustId()));
        if (!list.isEmpty()) {
            CustExcelUtil.fillRow(sheet, rowNum++, "签约产品", list.get(0).getProductGroup(), list.get(0).getProductName());
            if (list.size() > 2) {
                for (int i = 1; i < list.size(); i++) {
                    CustExcelUtil.fillRow(sheet, rowNum++, "", list.get(i).getProductGroup(), list.get(i).getProductName());
                }
            }
        } else {
            CustExcelUtil.fillRow(sheet, rowNum++, "签约产品", "存款", "");
            CustExcelUtil.fillRow(sheet, rowNum++, "", "贷款", "");
            CustExcelUtil.fillRow(sheet, rowNum++, "", "理财", "");
            CustExcelUtil.fillRow(sheet, rowNum++, "", "中间业务", "");
        }
        //合并单元格
        CustExcelUtil.mergeCells(sheet, startRow, rowNum - 1, 0, "签约产品");


        CustExcelUtil.fillRow(sheet, rowNum++, "走访记录", "走访内容", "");

        CustExcelUtil.fillRow(sheet, rowNum++, "登记信息", "客户标签", retail.getCustInfoRetail().getLabel());
        startRow = rowNum;
        if (retail.getBusinessList() != null && !retail.getBusinessList().isEmpty()  ) {
            String moduleName = "关联企业";
            for (CustInfoBusiness business : retail.getBusinessList()
            ) {
                    CustExcelUtil.fillRow(sheet, rowNum++, moduleName, "企业名称", business.getCustName());
                    moduleName = "";
            }
            CustExcelUtil.mergeCells(sheet, startRow, rowNum - 1, 0, "关联企业");
            startRow = rowNum;
        } else {
            CustExcelUtil.fillRow(sheet, rowNum++, "关联企业", "企业名称", "");
        }
        if (retail.getMerchantList() != null && !retail.getMerchantList().isEmpty()) {
            String moduleName = "关联商户";
            for (CustInfoMerchant merchant : retail.getMerchantList()
            ) {
                CustExcelUtil.fillRow(sheet, rowNum++, moduleName, "商户名称", merchant.getCustName());
                moduleName="";
            }
            CustExcelUtil.mergeCells(sheet, startRow+1, rowNum - 1, 0, "关联商户");
        } else {
            CustExcelUtil.fillRow(sheet, rowNum++, "关联商户", "商户名称", "");
        }
        startRow = rowNum;
        if (retail.getFamilyMembers() != null && !retail.getFamilyMembers().isEmpty()) {
            String moduleName = "家庭成员";
            for (FamilyMembers family : retail.getFamilyMembers()
            ) {
                CustExcelUtil.fillRow(sheet, rowNum++, moduleName, "姓名", family.getFmyName());
                CustExcelUtil.fillRow(sheet, rowNum++, "", "关系", family.getFmyRln());
                CustExcelUtil.fillRow(sheet, rowNum++, "", "身份证号", family.getFmyCustIdc());
                CustExcelUtil.fillRow(sheet, rowNum++, "", "手机号", family.getTel());
                moduleName="";
            }
        } else {
            CustExcelUtil.fillRow(sheet, rowNum++, "家庭成员", "姓名", "");
            CustExcelUtil.fillRow(sheet, rowNum++, "", "关系", "");
            CustExcelUtil.fillRow(sheet, rowNum++, "", "身份证号", "");
            CustExcelUtil.fillRow(sheet, rowNum++, "", "手机号", "");
        }
        CustExcelUtil.mergeCells(sheet, startRow, rowNum - 1, 0, "家庭成员");

        //自动调整列宽
        for (int i = 0; i < 2; i++) {
            sheet.autoSizeColumn(i);
            //匹配中文字符调整
            sheet.setColumnWidth(i, sheet.getColumnWidth(i) * 17 / 10);
        }
        //第三列容易超出255.故单独设置
        if (sheet.getColumnWidth(2) * 17 / 10>255){
            sheet.autoSizeColumn(2);
            sheet.setColumnWidth(2, sheet.getColumnWidth(2) * 13 / 10);
        } else {
            sheet.autoSizeColumn(2);
            sheet.setColumnWidth(2, sheet.getColumnWidth(2) * 17 / 10);
        }
        try (OutputStream outputStream = response.getOutputStream()) {
            workbook.write(outputStream);
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        workbook.close();
    }

    public int insertCustomersToRetailByCustId(List<SysGroupCustomer> sysGroupCustomers){
        return custInfoRetailMapper.insertCustomersToRetailByCustId(sysGroupCustomers);
    }

    public List<String> selectCustInfoRetailBycustIdcList(List<String> idcConditionList){
        return custInfoRetailMapper.selectCustInfoRetailBycustIdcList(idcConditionList);
    }
}
