package com.dsk.cscec.service.impl;

import cn.hutool.core.bean.BeanUtil;
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.QueryConstants;
import com.dsk.cscec.domain.DCustomer;
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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 组织维表(DCustomer)表服务实现类
 *
 * @author
 * @since 2023-12-10
 */
@Service
public class CustomerInfoServiceImpl extends ServiceImpl<DCustomerMapper, DCustomer> implements ICustomerInfoService {

    @Autowired
    private DSubcontractMapper subcontractMapper;

    @Autowired
    private BusinessOpportunityRadarService opportunityRadarService;

    @Autowired
    private AdvisoryBodyMapper advisoryBodyMapper;

    @Autowired
    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()));
                }
                //关键字标红
                if(!ObjectUtils.isEmpty(bo.getLeaderName())){
                    item.setCustomerName(StringUtils.markInRed(item.getLeaderName(), bo.getLeaderName()));
                }
                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);
                }
            });
        }
        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,QueryConstants.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(QueryConstants.LEVEL1_COMPANY_ID);
        Page<AdvisoryBodyVo> page = advisoryBodyMapper.queryListByBo(query.build(),bo);
        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(QueryConstants.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(QueryConstants.LEVEL1_COMPANY_ID);
        advisoryBodyBo.setAdvisoryBodyName(companyName);

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

        CustomerCooperationBo customerCooperationBo = new CustomerCooperationBo();
        customerCooperationBo.setSignOrgId(QueryConstants.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;
    }
}
