package com.dsk.cscec.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dsk.common.core.domain.PageQuery;
import com.dsk.common.core.page.TableDataInfo;
import com.dsk.common.excel.ExcelUtils;
import com.dsk.common.exception.ServiceException;
import com.dsk.common.utils.StringUtils;
import com.dsk.cscec.constant.AdvisoryBodyManageQueryConstants;
import com.dsk.cscec.domain.DCustomer;
import com.dsk.cscec.domain.bo.AddDCustomerLaborLeaderBo;
import com.dsk.cscec.domain.bo.AdvisoryBodyBo;
import com.dsk.cscec.domain.bo.CustomerCooperationBo;
import com.dsk.cscec.domain.bo.CustomerInfoBo;
import com.dsk.cscec.domain.vo.*;
import com.dsk.cscec.mapper.AdvisoryBodyMapper;
import com.dsk.cscec.mapper.DCustomerMapper;
import com.dsk.cscec.mapper.DSubcontractMapper;
import com.dsk.cscec.service.ICustomerInfoService;
import com.dsk.search.service.BusinessOpportunityRadarService;
import jodd.util.StringUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 组织维表(DCustomer)表服务实现类
 *
 * @author
 * @since 2023-12-10
 */
@Service
public class CustomerInfoServiceImpl extends ServiceImpl<DCustomerMapper, DCustomer> implements ICustomerInfoService {
    @Resource
    private DSubcontractMapper subcontractMapper;
    @Resource
    private BusinessOpportunityRadarService opportunityRadarService;
    @Resource
    private AdvisoryBodyMapper advisoryBodyMapper;
    @Resource
    private DSubcontractMapper dSubcontractMapper;

    @Override
    public TableDataInfo<CustomerInfoVo> queryPageList(CustomerInfoBo bo, PageQuery query) {
        List<String> customerStateList = Arrays.asList("合格");
        if ("劳务分包".equals(bo.getCustomerClass())) {
            bo.setCustomerClass("劳务分包");
            bo.setServiceTeamLogo("N");
            bo.setCustomerState(customerStateList);
        }
        if ("劳务分包队伍".equals(bo.getCustomerClass())) {
            bo.setCustomerClass("劳务分包");
            bo.setServiceTeamLogo("Y");
            bo.setCustomerState(customerStateList);
        }
        Page<CustomerInfoVo> page = baseMapper.queryListByType(query.build(), bo);
        AtomicInteger sortNum = new AtomicInteger(1);
        if (CollectionUtils.isNotEmpty(page.getRecords())) {
            page.getRecords().forEach(item -> {
                if (StringUtils.isNotBlank(bo.getCustomerName())) {
                    item.setCustomerNameExport(StringUtils.removeRed(item.getCustomerName()));
                }
                item.setNum(sortNum.getAndIncrement());
                DCustomerListVo vo = subcontractMapper.selectStatisticByCustomerId(item.getCustomerId());
                //企业合作数量
                item.setEnterpriseCooperationCount(vo.getEnterpriseCooperationCount());
                //项目合作数量
                item.setProjectCooperationCount(vo.getProjectCooperationCount());
                //关键字标红
                if (!ObjectUtils.isEmpty(bo.getCustomerName())) {
                    item.setCustomerName(StringUtils.markInRed(item.getCustomerName(), bo.getCustomerName()));
                }
                try {
                    Map<String, Object> map = opportunityRadarService.enterpriseByName(item.getCustomerName());
                    if (!ObjectUtils.isEmpty(map.get("data"))) {
                        Map<String, Object> data = BeanUtil.beanToMap(map.get("data"));
                        Integer companyId = MapUtil.getInt(data, "jskEid");
                        item.setCompanyId(companyId);
                    }
                } catch (Exception e) {
                    log.error("CustomerInfoServiceImpl.queryPageList() error:" + e);
                }
                //关键字标红
                if (!ObjectUtils.isEmpty(bo.getLeaderName())) {
                    item.setLeaderName(StringUtils.markInRed(item.getLeaderName(), bo.getLeaderName()));
                }
            });
        }
        return TableDataInfo.build(page);
    }

    /**
     * 导出供应商分类列表
     */
    @Override
    public void exportCustomerList(CustomerInfoBo bo, HttpServletResponse response) {
        String customerClass = bo.getCustomerClass();
        List<CustomerInfoVo> originList = this.queryPageList(bo, new PageQuery()).getRows();
        switch (customerClass) {
            case "专业分包":
                new ExcelUtils<>(CustomerInfoProfessionalSubtractVo.class).exportExcel(
                        response,
                        BeanUtil.copyToList(originList, CustomerInfoProfessionalSubtractVo.class),
                        customerClass,
                        "大数据经营管理支撑服务平台供应商导出",
                        true);
                break;
            case "租赁":
                new ExcelUtils<>(CustomerInfoMechanicConstructionVo.class).exportExcel(
                        response,
                        BeanUtil.copyToList(originList, CustomerInfoMechanicConstructionVo.class),
                        customerClass,
                        "大数据经营管理支撑服务平台供应商导出",
                        true);
                break;
            case "分供":
                new ExcelUtils<>(CustomerInfoMaterialDeviceVo.class).exportExcel(
                        response,
                        BeanUtil.copyToList(originList, CustomerInfoMaterialDeviceVo.class),
                        customerClass,
                        "大数据经营管理支撑服务平台供应商导出",
                        true);
                break;
            case "劳务分包":
                List<CustomerInfoLaborCompanyVo> laborCompanyVos = BeanUtil.copyToList(originList, CustomerInfoLaborCompanyVo.class);
                new ExcelUtils<>(CustomerInfoLaborCompanyVo.class).exportExcel(
                        response,
                        laborCompanyVos,
                        customerClass,
                        "大数据经营管理支撑服务平台供应商导出",
                        true);
                break;
            case "劳务分包队伍":
                List<CustomerInfoLaborQueueVo> laborQueueVoList = BeanUtil.copyToList(originList, CustomerInfoLaborQueueVo.class);
                new ExcelUtils<>(CustomerInfoLaborQueueVo.class).exportExcel(
                        response,
                        laborQueueVoList,
                        customerClass,
                        "大数据经营管理支撑服务平台供应商导出",
                        true);
                break;
            default:
                throw new ServiceException("供应商类别参数错误");
        }
    }

    @Override
    public CustomerApproveVo queryApproveByBo(CustomerInfoBo bo) {
        if (ObjectUtil.isNull(bo.getCustomerKey()) && StringUtil.isBlank(bo.getCustomerName()) && StringUtil.isBlank(bo.getUnifySocialCode())) {
            Assert.isTrue(false, "参数不能为空");
        }
        LambdaQueryWrapper<DCustomer> lqw = Wrappers.lambdaQuery();
        lqw.eq(DCustomer::getRecommendOrgId, AdvisoryBodyManageQueryConstants.LEVEL1_COMPANY_ID);
        lqw.eq(ObjectUtil.isNotNull(bo.getCustomerKey()), DCustomer::getCustomerKey, bo.getCustomerKey());
        lqw.eq(StringUtil.isNotBlank(bo.getUnifySocialCode()), DCustomer::getUnifySocialCode, bo.getUnifySocialCode());
        lqw.eq(StringUtil.isNotBlank(bo.getCustomerName()), DCustomer::getCustomerName, bo.getCustomerName());
        lqw.orderByDesc(DCustomer::getApproveDate2);
        lqw.last("limit 1");
        DCustomer dCustomer = baseMapper.selectOne(lqw);
        if (ObjectUtil.isNotEmpty(dCustomer)) {
            //营业执照url
            dCustomer.setBusinessLicenseList(baseMapper.selectBusinessLicense(dCustomer.getCustomerId()));
            //组织机构代码证url
            dCustomer.setOrgCertificateList(baseMapper.selectOrgCertificate(dCustomer.getCustomerId()));
            //税务登记证url
            dCustomer.setTaxCertificateList(baseMapper.selectTaxCertificate(dCustomer.getCustomerId()));
            //资质证书url
            dCustomer.setQualificationCertificateList(baseMapper.selectQualificationCertificate(dCustomer.getCustomerId()));
            //安全生产url
            dCustomer.setSafetyCertificateList(baseMapper.selectSafetyCertificate(dCustomer.getCustomerId()));
            //增值税一般纳税人资格证明url
//            dCustomer.setRatepayerCertificateList(baseMapper.selectRatepayerCertificate(dCustomer.getCustomerId()));
            //业绩报告url
            dCustomer.setPerformanceCertificateList(baseMapper.selectPerformanceCertificate(dCustomer.getCustomerId()));
            //考察报告url
            dCustomer.setInspectionCertificateList(baseMapper.selectInspectionCertificate(dCustomer.getCustomerId()));
            //其他url
            dCustomer.setOtherCertificateList(baseMapper.selectOtherCertificate(dCustomer.getCustomerId()));

        }
        CustomerApproveVo vo = BeanUtil.toBean(dCustomer, CustomerApproveVo.class);
        return vo;
    }

    //可能要切表  使用合作项目查询的接口下载excel那里也是
    @Override
    public TableDataInfo<AdvisoryBodyVo> queryAdvisoryList(AdvisoryBodyBo bo, PageQuery query) {
        bo.setContractOrgId(AdvisoryBodyManageQueryConstants.LEVEL1_COMPANY_ID);
        Page<AdvisoryBodyVo> page = advisoryBodyMapper.queryListByBo(query.build(), bo);
        page.getRecords().parallelStream().forEach(vo -> {
            try {
                Map<String, Object> map = opportunityRadarService.enterpriseByName(vo.getOwnerName());
                if (!ObjectUtils.isEmpty(map.get("data"))) {
                    Map<String, Object> data = BeanUtil.beanToMap(map.get("data"));
                    Integer companyId = MapUtil.getInt(data, "jskEid");
                    vo.setOwnerCid(companyId);
                }
                map = opportunityRadarService.enterpriseByName(vo.getContractOrgName());
                if (!ObjectUtils.isEmpty(map.get("data"))) {
                    Map<String, Object> data = BeanUtil.beanToMap(map.get("data"));
                    Integer companyId = MapUtil.getInt(data, "jskEid");
                    vo.setContractOrgCid(companyId);
                }
            } catch (Exception e) {
                log.error("CustomerInfoServiceImpl.queryAdvisoryList() error:" + e);
            }
        });
        return TableDataInfo.build(page);
    }

    @Override
    public TableDataInfo<CustomerCooperationVo> queryCooperationList(CustomerCooperationBo bo, PageQuery query) {
        if (StringUtil.isBlank(bo.getCustomerId()) && StringUtil.isBlank(bo.getCustomerName())) {
            Assert.isTrue(false, "供应商不能为空");
        }
        bo.setSignOrgId(AdvisoryBodyManageQueryConstants.LEVEL1_COMPANY_ID);
        Page<CustomerCooperationVo> page = dSubcontractMapper.selectCooperationList(query.build(), bo);
        return TableDataInfo.build(page);
    }

    @Override
    public Map<String, Object> cooperationStatistic(String companyName) {
        if (StringUtil.isBlank(companyName)) {
            return new HashMap<>();
        }
        AdvisoryBodyBo advisoryBodyBo = new AdvisoryBodyBo();
        advisoryBodyBo.setContractOrgId(AdvisoryBodyManageQueryConstants.LEVEL1_COMPANY_ID);
        advisoryBodyBo.setAdvisoryBodyName(companyName);

        LambdaQueryWrapper<DCustomer> lqw = Wrappers.lambdaQuery();
        lqw.eq(DCustomer::getRecommendOrgId, AdvisoryBodyManageQueryConstants.LEVEL1_COMPANY_ID);
        lqw.eq(StringUtil.isNotBlank(companyName), DCustomer::getCustomerName, companyName);

        CustomerCooperationBo customerCooperationBo = new CustomerCooperationBo();
        customerCooperationBo.setSignOrgId(AdvisoryBodyManageQueryConstants.LEVEL1_COMPANY_ID);
        customerCooperationBo.setCustomerName(companyName);

        Map<String, Object> result = new HashMap<>();
        result.put("advisoryList", advisoryBodyMapper.countByBo(advisoryBodyBo));
        result.put("cooperationList", subcontractMapper.countByBo(customerCooperationBo));
        result.put("approveInfo", baseMapper.exists(lqw) ? 1 : 0);
//        result.put("施工业绩", 0);
//        result.put("在施工程情况", 0);
        return result;
    }

    /**
     * 查询供应商基本情况
     */
    @Override
    public Map<String, Long> queryBasicInfo() {
        HashMap<String, Long> infoMap = new HashMap<>();
        //专业分包数量
        Long zyfbCount = baseMapper.selectCount(new LambdaQueryWrapper<DCustomer>()
                .eq(DCustomer::getRecommendOrgId, "F17305B4EA4444CBAB12892C7B99E475")
                .eq(DCustomer::getCustomerClass, "专业分包"));
        //机械施工数量
        Long jxsgCount = baseMapper.selectCount(new LambdaQueryWrapper<DCustomer>()
                .eq(DCustomer::getRecommendOrgId, "F17305B4EA4444CBAB12892C7B99E475")
                .eq(DCustomer::getCustomerClass, "租赁"));
        //物资设备数量
        Long wzsbCount = baseMapper.selectCount(new LambdaQueryWrapper<DCustomer>()
                .eq(DCustomer::getRecommendOrgId, "F17305B4EA4444CBAB12892C7B99E475")
                .eq(DCustomer::getCustomerClass, "分供"));
        //劳务分包数量
        Long lwfbCount = baseMapper.selectCount(new LambdaQueryWrapper<DCustomer>()
                .eq(DCustomer::getRecommendOrgId, "F17305B4EA4444CBAB12892C7B99E475")
                .eq(DCustomer::getCustomerClass, "劳务分包")
                .eq(DCustomer::getServiceTeamLogo, "N"));
        //劳务分包队伍数量
        Long lwfbdwCount = baseMapper.selectCount(new LambdaQueryWrapper<DCustomer>()
                .eq(DCustomer::getRecommendOrgId, "F17305B4EA4444CBAB12892C7B99E475")
                .eq(DCustomer::getCustomerClass, "劳务分包")
                .eq(DCustomer::getServiceTeamLogo, "Y"));
        infoMap.put("customerTotal", zyfbCount + jxsgCount + wzsbCount + lwfbCount + lwfbdwCount);
        infoMap.put("zyfbCount", zyfbCount);
        infoMap.put("jxsgCount", jxsgCount);
        infoMap.put("wzsbCount", wzsbCount);
        infoMap.put("lwfbCount", lwfbCount);
        infoMap.put("lwfbdwCount", lwfbdwCount);
        return infoMap;
    }

    /**
     * 校验劳务队长身份证号是否存在
     */
    @Override
    public List<CustomerInfoVo> checkLaborLeaderIdExist(String laborLeaderId) {
        List<DCustomer> leaderList = baseMapper.selectList(new LambdaQueryWrapper<DCustomer>()
                .eq(DCustomer::getLaborCaptainIdcard, laborLeaderId)
                .eq(DCustomer::getCustomerClass, "劳务分包")
                .eq(DCustomer::getServiceTeamLogo, "Y")
                .eq(DCustomer::getRecommendOrgId, AdvisoryBodyManageQueryConstants.LEVEL1_COMPANY_ID));
        if (!leaderList.isEmpty()) {
            List<CustomerInfoVo> voList = BeanUtil.copyToList(leaderList, CustomerInfoVo.class);
            voList.parallelStream().forEach(item -> {
                DCustomerListVo vo = subcontractMapper.selectStatisticByCustomerId(item.getCustomerId());
                //企业合作数量
                item.setEnterpriseCooperationCount(vo.getEnterpriseCooperationCount());
                //项目合作数量
                item.setProjectCooperationCount(vo.getProjectCooperationCount());
                try {
                    Map<String, Object> map = opportunityRadarService.enterpriseByName(item.getCustomerName());
                    if (!ObjectUtils.isEmpty(map.get("data"))) {
                        Map<String, Object> data = BeanUtil.beanToMap(map.get("data"));
                        Integer companyId = MapUtil.getInt(data, "jskEid");
                        item.setCompanyId(companyId);
                    }
                } catch (Exception e) {
                    log.error("CustomerInfoServiceImpl.checkLaborLeaderIdExist() error:" + e);
                }
            });
            return voList;
        }
        return null;
    }

    /**
     * 添加劳务队队长
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer addLaborLeader(AddDCustomerLaborLeaderBo bo) {
        DCustomer customer = BeanUtil.toBean(bo, DCustomer.class);
        //如果数据库中存在该供应商,则填充相应信息
        Assert.isFalse(baseMapper.exists(new LambdaQueryWrapper<DCustomer>()
                .eq(DCustomer::getRecommendOrgId, AdvisoryBodyManageQueryConstants.LEVEL1_COMPANY_ID)
                .eq(DCustomer::getCustomerClass, "劳务分包")
                .eq(DCustomer::getCusomerName, bo.getCusomerName())), "该供应商已存在");

        //填充省市信息
        Map<String, Object> map = opportunityRadarService.enterpriseByName(bo.getCusomerName());
        if (!ObjectUtils.isEmpty(map.get("data"))) {
            Map<String, Object> data = BeanUtil.beanToMap(map.get("data"));
            //注册省份
            customer.setRegisterProvince(MapUtil.getStr(data, "province"));
            //注册城市
            customer.setRegisterCity(MapUtil.getStr(data, "city"));
            //注册资金
            customer.setRegisterCapital(MapUtil.getDouble(data, "registeredCapitalStr"));
            //法定代表人
            customer.setResponsiblePerson(MapUtil.getStr(data, "legalPerson"));
        }

        customer.setCustomerKey(baseMapper.selectOne(new LambdaQueryWrapper<DCustomer>()
                .orderByDesc(DCustomer::getCustomerKey)
                .last("LIMIT 1")).getCustomerKey() + 1);
        customer.setCustomerName(bo.getCusomerName());
        customer.setFinCustomerName(bo.getCusomerName());
        customer.setRecommendOrgId(AdvisoryBodyManageQueryConstants.LEVEL1_COMPANY_ID);
        customer.setRecommendOrg(AdvisoryBodyManageQueryConstants.LEVEL1_COMPANY_NAME);
        customer.setTaxNumber(bo.getUnifySocialCode());
        customer.setBusinessLicense(bo.getUnifySocialCode());
        customer.setOrgnizationCode(bo.getUnifySocialCode());
        DateTime now = new DateTime();
        customer.setApproveDate2(now);
        customer.setUpdateDate(now.toDateStr());
        customer.setLoadTime(now);
        customer.setCustomerClass("劳务分包");
        return baseMapper.insert(customer);
    }
}
