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

import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.utils.DateUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.ibs.custmap.domain.entity.CustInfoRadar;
import com.ruoyi.ibs.custmap.mapper.CustMapMapper;
import com.ruoyi.ibs.customerselect.mapper.CustInfoBusinessMapper;
import com.ruoyi.ibs.grid.domain.vo.AddressDetail;
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.CorporateShareholderMapper;
import com.ruoyi.ibs.list.mapper.CustInfoRetailMapper;
import com.ruoyi.ibs.list.mapper.Ent9vPortraitOrcMapper;
import com.ruoyi.ibs.list.mapper.FamilyMembersMapper;
import com.ruoyi.ibs.list.mapper.NineVFinalInfoOrcMapper;
import com.ruoyi.ibs.list.mapper.SignedProductsMapper;
import com.ruoyi.ibs.list.service.ICustInfoBusinessService;
import com.ruoyi.system.mapper.SysIndustryMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

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


/**
 * 企业客户基本信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-10-28
 */
@Service
public class CustInfoBusinessServiceImpl implements ICustInfoBusinessService
{
    @Autowired
    private CustInfoBusinessMapper custInfoBusinessMapper;
    @Autowired
    private CorporateShareholderMapper corporateShareholderMapper;
    @Autowired
    private SignedProductsMapper signedProductsMapper;
    @Autowired
    private CustInfoRetailServiceImpl custInfoRetailService;
    @Autowired
    private CustInfoRetailMapper custInfoRetailMapper;
    @Autowired
    private SysIndustryMapper sysIndustryMapper;
    @Autowired
    private AnchorService anchorService;
    @Autowired
    private AnchorMapper anchorMapper;
    @Resource
    RedisCache redisCache;

    @Autowired
    private FamilyMembersMapper familyMembersMapper;

    @Autowired
    private Ent9vPortraitOrcMapper ent9vPortraitOrcMapper;

    @Autowired
    private NineVFinalInfoOrcMapper nineVFinalInfoOrcMapper;

    @Autowired
    private CustMapMapper custMapMapper;

    /**
     * 查询企业客户基本信息
     * 
     * @param id 企业客户基本信息主键
     * @return 企业客户基本信息
     */
    @Override
    public CustInfoBusiness selectCustInfoBusinessById(Long id)
    {
        return custInfoBusinessMapper.selectCustInfoBusinessById(id);
    }

    @Override
    public CustInfoBusinessVo selectCustInfoBusinessVoByCustId(String custId) {
        CustInfoBusiness custInfoBusiness = selectCustInfoBusinessByCustId(custId);
        CustInfoBusinessVo custInfoBusinessVo = new CustInfoBusinessVo();
        if (custInfoBusiness==null){
            QueryWrapper<CustInfoRadar> queryWrapper = new QueryWrapper<>();
            queryWrapper.select( "*, new_company_flag_"+getDeptId().toString().substring(0,3)+" as new_company_flag");
            queryWrapper.eq("cust_id",custId);
            CustInfoRadar custInfoRadars = custMapMapper.selectOne(queryWrapper);
            if(custInfoRadars == null) {
                throw new IllegalArgumentException("非我行客户");
            }
            radarsVoConvert(custInfoBusinessVo,custInfoRadars);
            return custInfoBusinessVo;
        }

        custInfoBusinessVo.setCustInfoBusiness(custInfoBusiness);
        custInfoBusinessVo = custInfoBusinessVoSetGrid(custInfoBusinessVo);
//        custInfoBusinessVo.setGridUserName(custInfoRetailService.getNickNames(custInfoBusiness.getCustId()));
//        custInfoBusinessVo.setGridName(custInfoRetailService.getGridNames(custInfoBusiness.getCustId()));
        custInfoBusinessVo.setCmpmUserName(custInfoRetailService.getCmpmNickNames(custInfoBusiness.getCustId()));
        custInfoBusinessVo.setCmpmUserLists(custInfoRetailService.getCmpmUserList(custInfoBusiness.getCustId()));
        SignedProducts signedProducts = signedProductsMapper.selectSignedProductsByCurrdeposFlag(custInfoBusiness.getCustId());
        if (signedProducts!=null){
            custInfoBusinessVo.setSignedProducts(Constans.convertSignedProducts(signedProducts));
        }
        if (custInfoBusiness.getSocialCreditCode()!=null&&!custInfoBusiness.getSocialCreditCode().equals("")){
            CorporateShareholder corporateShareholder = new CorporateShareholder();
            corporateShareholder.setSocialCreditCode(custInfoBusiness.getSocialCreditCode());
            corporateShareholder.setCustType(ENTERPRISE.getCode());
//            corporateShareholder.setCustomerType("1");
//            corporateShareholder.setLpName(custInfoBusiness.getLpName());
            List<CorporateShareholder> corporateShareholders = corporateShareholderMapper.selectCorporateShareholderList(corporateShareholder);
            custInfoBusinessVo.setCorporateShareholders(corporateShareholders);
        }
        custInfoBusinessVo.setCommunity(custInfoRetailMapper.selectCommunityBycustId(custInfoBusiness.getCustId()));
        if (custInfoBusiness.getSocialCreditCode()!=null){
            custInfoBusinessVo.setAddressDetails(anchorMapper.selectCustAddressList(custInfoBusiness.getSocialCreditCode()));

            Map<String,String> params = new HashMap<>();
            params.put("custId",custInfoBusiness.getCustId());
            params.put("deptId3",getDeptId().toString().substring(0,3));
            params.put("custType","gs");
            List<CustTagVo> tagVos = familyMembersMapper.selectCustEnumByCustId(params);
            custInfoBusinessVo.setTabEnmuVos( TreeNode.convertToTree(tagVos));
            //查询手动标签列表
            List<CustManualTagVO> tagCreateVos = familyMembersMapper.selectManualTag(params);
            custInfoBusinessVo.setTagManual(TreeNode.convertToTreeByParentId(tagCreateVos));

            // 仅当登录机构为825时，查询九维画像数据
            if ("825".equals(getHeadId())) {
                LambdaQueryWrapper<Ent9vPortraitOrc> portraitWrapper = new LambdaQueryWrapper<>();
                portraitWrapper.eq(Ent9vPortraitOrc::getUniscid, custInfoBusiness.getSocialCreditCode());
                custInfoBusinessVo.setEnt9vPortrait(ent9vPortraitOrcMapper.selectOne(portraitWrapper));

                LambdaQueryWrapper<NineVFinalInfoOrc> finalInfoWrapper = new LambdaQueryWrapper<>();
                finalInfoWrapper.eq(NineVFinalInfoOrc::getUniscid, custInfoBusiness.getSocialCreditCode());
                custInfoBusinessVo.setNineVFinalInfo(nineVFinalInfoOrcMapper.selectOne(finalInfoWrapper));
            }
        }
        return custInfoBusinessVo;
    }





    private void radarsVoConvert(CustInfoBusinessVo custInfoBusinessVo, CustInfoRadar custInfoRadars) {
        CustInfoBusiness custInfoBusiness = new CustInfoBusiness();
        BeanUtils.copyProperties(custInfoRadars,custInfoBusiness);
        custInfoBusiness.setBusinessScope(custInfoRadars.getScope());
        custInfoBusiness.setCustCapital(custInfoRadars.getRegistCapiValue().toString());
        custInfoBusiness.setCustLocation(custInfoRadars.getAddressDetail());
        custInfoBusinessVo.setCustInfoBusiness(custInfoBusiness);
        custInfoBusinessVo.setRadarCustFlag("1");
    }

    public CustInfoBusinessVo custInfoBusinessVoSetGrid(CustInfoBusinessVo custInfoBusinessVo){
        String custId = custInfoBusinessVo.getCustInfoBusiness().getCustId();
        String roleName = userRole();
        List<String> LsNames = new ArrayList<>();
        if (custId==null||custId.equals("")){
            return custInfoBusinessVo;
        }
        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());
                }
            }

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



    @Override
    public List<CustInfoBusiness> selectCustInfoBusinessList(CustInfoBusiness custInfoBusiness) {
        return custInfoBusinessMapper.selectCustInfoBusinessLists(custInfoBusiness);
    }

    /**
     * 查询企业客户基本信息列表
     * 
     * @param keyword 企业客户基本信息
     * @return 企业客户基本信息
     */
    @Override
    public List<CustInfoBusiness> selectCustInfoBusinessListByKeyword(String keyword)
    {
        String roleName = userRole();
        List<CustInfoBusiness> custInfoBusinesses = new ArrayList<>();
        if (ROLE_HEAD.equals(roleName)||ROLE_HeadPublic.equals(roleName)||ROLE_HeadOps.equals(roleName)){
            custInfoBusinesses = custInfoBusinessMapper.selectCustInfoBusinessListBykeyword(keyword);
        }
        else if (ROLE_BRANCH.equals(roleName)){
            custInfoBusinesses = custInfoBusinessMapper.selectCustInfoBusinessListBykeywordBranchAndManager(keyword,getDeptId(),null,null,null);;
        }else if (ROLE_Outlet.equals(roleName)){
            custInfoBusinesses = custInfoBusinessMapper.selectCustInfoBusinessListBykeywordBranchAndManager(keyword,null,getDeptId(),null,null);;
        }else {
            custInfoBusinesses = custInfoBusinessMapper.selectCustInfoBusinessListBykeywordBranchAndManager(keyword,null,null,getUserId(),null);
        }
        return custInfoBusinesses;
    }

    /**
     * 新增企业客户基本信息
     * 
     * @param custInfoBusiness 企业客户基本信息
     * @return 结果
     */
    @Override
    public int insertCustInfoBusiness(CustInfoBusiness custInfoBusiness)
    {
        custInfoBusiness.setCreateTime(DateUtils.getNowDate());
        return custInfoBusinessMapper.insertCustInfoBusiness(custInfoBusiness);
    }

    @Override
    public AjaxResult insertCustInfoBusinessVo(CustInfoBusiness custInfoBusiness, String relatePerson) {
        if (custInfoBusiness.getSocialCreditCode()==null||"".equals(custInfoBusiness.getSocialCreditCode())
        ||custInfoBusiness.getCustName()==null||"".equals(custInfoBusiness.getCustName())){
            return AjaxResult.error("缺乏必要建档信息，无法建档成功");
        }
        CustInfoBusiness infoBusiness = new CustInfoBusiness();
        infoBusiness.setSocialCreditCode(custInfoBusiness.getSocialCreditCode());
        List<CustInfoBusiness> custInfoBusinesses = custInfoBusinessMapper.selectCustInfoBusinessLists(infoBusiness);
        if (custInfoBusinesses!=null&&custInfoBusinesses.size()>0){
            return AjaxResult.error("当前企业统信码已建档,无需重复建档");
        }
        //查看是否存在同名企业，且法人身份证号与当前法人身份证号相同的企业数据，但是没有统信码和客户号的数据，若存在即为个人插入的关联企业数据，此时无需插入新数据，只需更新补全该数据
        CustInfoBusiness business = custInfoBusinessMapper.selectCustInfoBusinessByCustNameAndCustIdc(custInfoBusiness.getCustName(),custInfoBusiness.getCustIdc());
        if (business!=null){
            Long id = business.getId();
            if (business.getSocialCreditCode()==null||"".equals(business.getSocialCreditCode())){
                BeanUtils.copyProperties(custInfoBusiness,business);
                business.setCustId("202"+custInfoBusiness.getSocialCreditCode());
                business.setId(id);
                custInfoBusinessMapper.updateCustInfoBusiness(business);
                if (relatePerson!=null&&!relatePerson.isEmpty()) {
                    CorporateShareholder shareholder = new CorporateShareholder();
                    shareholder.setName(relatePerson);
                    shareholder.setCustomerType("1");
                    shareholder.setCustType(ENTERPRISE.getCode());
                    shareholder.setSocialCreditCode(custInfoBusiness.getSocialCreditCode());
                    corporateShareholderMapper.insertCorporateShareholder(shareholder);
                }
                return AjaxResult.success("当前法人下存在同名企业，但是缺乏统信码等必要信息，已自动补全");
            }else {
                return AjaxResult.error("当前法人下存在同名企业，无法重复为该企业建档");
            }

        }

        custInfoBusiness.setCustId("202"+custInfoBusiness.getSocialCreditCode());
        insertCustInfoBusiness(custInfoBusiness);
        if (relatePerson!=null&&!relatePerson.isEmpty()) {
            CorporateShareholder shareholder = new CorporateShareholder();
            shareholder.setName(relatePerson);
            shareholder.setCustomerType("1");
            shareholder.setCustType(ENTERPRISE.getCode());
            shareholder.setSocialCreditCode(custInfoBusiness.getSocialCreditCode());
            corporateShareholderMapper.insertCorporateShareholder(shareholder);
        }
        return AjaxResult.success("建档成功");
    }

    /**
     * 修改企业客户基本信息
     * 
     * @param custInfoBusiness 企业客户基本信息
     * @return 结果
     */
    @Override
    public AjaxResult updateCustInfoBusiness(CustInfoBusiness custInfoBusiness)
    {
        custInfoBusiness.setUpdateTime(DateUtils.getNowDate());
        if (custInfoBusiness.getLabel()!=null&&!custInfoBusiness.getLabel().isEmpty()){
            if (Constans.labelDuplicate(custInfoBusiness.getLabel())){
                return AjaxResult.error("客户标签不允许重复");
            }
        }
//
        if(StringUtils.isNotEmpty(custInfoBusiness.getLabel())){
            custInfoBusinessMapper.updateCustInfoBusinessLabel(custInfoBusiness);
        }else{
            custInfoBusinessMapper.updateCustInfoBusiness(custInfoBusiness);
        }

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

    /**
     * 批量删除企业客户基本信息
     * 
     * @param ids 需要删除的企业客户基本信息主键
     * @return 结果
     */
    @Override
    public int deleteCustInfoBusinessByIds(Long[] ids)
    {
        return custInfoBusinessMapper.deleteCustInfoBusinessByIds(ids);
    }

    /**
     * 删除企业客户基本信息信息
     * 
     * @param id 企业客户基本信息主键
     * @return 结果
     */
    @Override
    public int deleteCustInfoBusinessById(Long id)
    {
        return custInfoBusinessMapper.deleteCustInfoBusinessById(id);
    }

    @Override
    public CustInfoBusiness selectCustInfoBusinessByCustId(String custId) {
        return custInfoBusinessMapper.selectCustInfoBusinessByCustId(custId);
    }

    public void exportBusinessDetail(HttpServletResponse response, String  custId) throws Exception {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        CustInfoBusinessVo business = selectCustInfoBusinessVoByCustId(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++, "基础信息", "企业名称", business.getCustInfoBusiness().getCustName());
        CustExcelUtil.fillRow(sheet, rowNum++, "", "法人姓名", business.getCustInfoBusiness().getLpName());
        CustExcelUtil.fillRow(sheet, rowNum++, "", "性别", business.getCustInfoBusiness().getCustGender());
        CustExcelUtil.fillRow(sheet, rowNum++, "", "年龄", business.getCustInfoBusiness().getCustAge());
        CustExcelUtil.fillRow(sheet, rowNum++, "", "身份证号", business.getCustInfoBusiness().getCustIdc());
        if(business.getCustInfoBusiness().getBirthday()!=null) {
            CustExcelUtil.fillRow(sheet, rowNum++, "", "出生日期", sdf.format(business.getCustInfoBusiness().getBirthday()));
        }else{
            CustExcelUtil.fillRow(sheet, rowNum++, "", "出生日期", null);
        }
        CustExcelUtil.fillRow(sheet, rowNum++, "", "手机号",business.getCustInfoBusiness().getCustPhone());
        CustExcelUtil.fillRow(sheet, rowNum++, "", "行业名称",business.getCustInfoBusiness().getIndustry());
        CustExcelUtil.fillRow(sheet, rowNum++, "", "客户号",business.getCustInfoBusiness().getCustId());
        CustExcelUtil.fillRow(sheet, rowNum++, "", "客户内码", business.getCustInfoBusiness().getCustIsn());
        CustExcelUtil.fillRow(sheet, rowNum++, "", "统信码", business.getCustInfoBusiness().getSocialCreditCode());
        CustExcelUtil.fillRow(sheet, rowNum++, "", "注册地址", business.getCustInfoBusiness().getRegisterLocation());
        CustExcelUtil.fillRow(sheet, rowNum++, "", "经营地址", business.getCustInfoBusiness().getCustLocation());
        String status = "";
        if (business.getCustInfoBusiness().getStatus()==null||business.getCustInfoBusiness().getStatus().equals("")){
        }else{
            status=business.getCustInfoBusiness().getStatus();
        }
        String statusName="";
        switch (status) {
            case "1":
                statusName = "正常";
                break;
            case "2":
                statusName = "特殊";
                break;
            case "3":
                statusName = "其他";
                break;
            case "4":
                statusName = "黑名单客户";
                break;
            case "5":
                statusName = "灰名单";
                break;
            case "6":
                statusName = "未知";
                break;
            default:
                statusName="";
        }
        CustExcelUtil.fillRow(sheet, rowNum++, "", "经营状态", statusName);
        CustExcelUtil.fillRow(sheet, rowNum++, "", "经营范围", business.getCustInfoBusiness().getBusinessScope());
        CustExcelUtil.fillRow(sheet, rowNum++, "", "注册资本", business.getCustInfoBusiness().getCustCapital());
        CustExcelUtil.fillRow(sheet, rowNum++, "", "联系电话", business.getCustInfoBusiness().getTel());
        CustExcelUtil.fillRow(sheet, rowNum++, "", "网格客户经理", business.getGridUserName());
        CustExcelUtil.fillRow(sheet, rowNum++, "", "绩效客户经理", business.getCmpmUserName());
        if (business.getCustInfoBusiness().getUpdateTime() != null) {
            CustExcelUtil.fillRow(sheet, rowNum++, "", "更新时间", sdf.format(business.getCustInfoBusiness().getUpdateTime()));
        }else {
            CustExcelUtil.fillRow(sheet, rowNum++, "", "更新时间", "");
        }
        CustExcelUtil.mergeCells(sheet, startRow, rowNum - 1, 0, "基础信息");
        startRow = rowNum;

//        //经营状况待补充
//        CustExcelUtil.fillRow(sheet, rowNum++, "经营状况", "税务信息", "");
//        CustExcelUtil.fillRow(sheet, rowNum++, "", "融资信息", "");
//        CustExcelUtil.fillRow(sheet, rowNum++, "", "企业招投标信息", "");
//        CustExcelUtil.mergeCells(sheet, startRow, rowNum - 1, 0, "经营状况");
//        startRow = rowNum;
//
//        //经营风险待补充
//        CustExcelUtil.fillRow(sheet, rowNum++, "经营风险", "经营异常", "");
//        CustExcelUtil.fillRow(sheet, rowNum++, "", "行政处罚_信用中国", "");
//        CustExcelUtil.mergeCells(sheet, startRow, rowNum - 1, 0, "经营风险");
//        startRow = rowNum;
//
//        //工商信息待补充
//        CustExcelUtil.fillRow(sheet, rowNum++, "工商信息", "公司信息", "");
//        CustExcelUtil.fillRow(sheet, rowNum++, "", "注销吊销信息", "");
//        CustExcelUtil.mergeCells(sheet, startRow, rowNum - 1, 0, "工商信息");
//        startRow = rowNum;


        List<AddressDetail> addressDetails = anchorMapper.selectCustAddressList(custId.substring(3));
        if (!addressDetails.isEmpty()) {
            CustExcelUtil.fillRow(sheet, rowNum++, "地址信息", addressDetails.get(0).getAddressName(), addressDetails.get(0).getAddress());
            if (addressDetails.size() > 2) {
                for (int i = 1; i < addressDetails.size(); i++) {
                    CustExcelUtil.fillRow(sheet, rowNum++, "", addressDetails.get(i).getAddressName(), addressDetails.get(i).getAddress());
                }
                CustExcelUtil.mergeCells(sheet, startRow, rowNum - 1, 0, "地址信息");
            }

            startRow = rowNum;
        } else {
            CustExcelUtil.fillRow(sheet, rowNum++, "地址信息", "经营地址", "");
            CustExcelUtil.fillRow(sheet, rowNum++, "", "注册地址", "");
            CustExcelUtil.mergeCells(sheet, startRow, rowNum - 1, 0, "地址信息");
            startRow = rowNum;
        }

        List<Products> list = Constans.convertProducts(signedProductsMapper.selectSignedProductsByCurrdeposFlag(business.getCustInfoBusiness().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, "签约产品");


        //走访记录待补充，若多条，需合并单元格
//        startRow = rowNum;
        CustExcelUtil.fillRow(sheet, rowNum++, "走访记录", "走访内容", "");
//        CustExcelUtil.mergeCells(sheet, startRow, rowNum - 1, 0, "走访记录");



        CustExcelUtil.fillRow(sheet, rowNum++, "自定义备注", "客户标签", business.getCustInfoBusiness().getLabel());

        startRow = rowNum;
        if (business.getCorporateShareholders() != null && !business.getCorporateShareholders().isEmpty()) {
            String moduleName = "关联人";
            for (CorporateShareholder cpsh : business.getCorporateShareholders()
            ) {
                CustExcelUtil.fillRow(sheet, rowNum++, moduleName, "姓名", cpsh.getName());
                CustExcelUtil.fillRow(sheet, rowNum++, "", "身份证号 ", cpsh.getCustIdc());
                moduleName="";
            }
        } else {
                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 insertCustomersToBusinessByScCode(List<SysGroupCustomer> sysGroupCustomers){
        return custInfoBusinessMapper.insertCustomersToBusinessByScCode(sysGroupCustomers);
    }

    @Override
    public List<SysDictData> getRegStatus() {
        Map<String,String> params = new HashMap<>();
        List<SysDictData> sysDictTypeArrayList = new ArrayList<SysDictData>(redisCache.getCacheObject("sys_dict:reg_status"));

        return sysDictTypeArrayList;
    }
}
