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.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 java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 组织维表(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) {
        if ("劳务分包".equals(bo.getCustomerClass())) {
            bo.setServiceTeamLogo("N");
        }
        if ("劳务分包队伍".equals(bo.getCustomerClass())) {
            bo.setCustomerClass("劳务分包");
            bo.setServiceTeamLogo("Y");
        }
        Page<CustomerInfoVo> page = baseMapper.queryListByType(query.build(), bo);
        if (CollectionUtils.isNotEmpty(page.getRecords())) {
            page.getRecords().parallelStream().forEach(item -> {
                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 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;
    }

    @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);
        //如果数据库中存在该供应商,则填充相应信息
        DCustomer originCustomer = baseMapper.selectList(new LambdaQueryWrapper<DCustomer>()
                .eq(DCustomer::getCusomerName, bo.getCusomerName())
                .orderByDesc(DCustomer::getApproveDate2)).get(0);
        if (ObjectUtil.isNotNull(originCustomer)) {
            //财务客商编码
            customer.setFinCustomerCode(originCustomer.getFinCustomerCode());
            //法人代表
            customer.setRepresentative(originCustomer.getRepresentative());
            //工商注册号
            customer.setRegisterNo(originCustomer.getRegisterNo());
            //注册资金
            customer.setRegisterCapital(originCustomer.getRegisterCapital());
            //注册地区域
            customer.setRegisterRegion(originCustomer.getRegisterRegion());
            //省份
            customer.setRegisterProvince(originCustomer.getRegisterProvince());
            //城市
            customer.setRegisterCity(originCustomer.getRegisterCity());
            //联系人
            customer.setContactPerson(originCustomer.getContactPerson());
            //电话
            customer.setContactPhone(originCustomer.getContactPhone());
            //一体化客商类型
            customer.setFinCustomerType(originCustomer.getFinCustomerType());
            //客商性质
            customer.setCustomerKind(originCustomer.getCustomerKind());
            //是否业主
            customer.setIsowner(originCustomer.getIsowner());
            //是否供应商
            customer.setIscustomer(originCustomer.getIscustomer());
            //税率类型
            customer.setTaxType(originCustomer.getTaxType());
            //是否冻结
            customer.setIsfreeze(originCustomer.getIsfreeze());
        } else {
            //填充省市信息
            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.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);
    }
}
