package com.dsk.cscec.service.impl;

import cn.hutool.core.bean.BeanUtil;
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.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dsk.common.core.domain.PageQuery;
import com.dsk.common.core.domain.R;
import com.dsk.common.core.page.TableDataInfo;
import com.dsk.common.helper.LoginHelper;
import com.dsk.common.utils.StringUtils;
import com.dsk.cscec.domain.DCustomer;
import com.dsk.cscec.domain.bo.DCustomerDynamicRiskChangeVo;
import com.dsk.cscec.domain.bo.DCustomerDynamicRiskStatisticsVo;
import com.dsk.cscec.domain.bo.DCustomerDynamicRiskTypeVo;
import com.dsk.cscec.domain.bo.DCustomerSearchBo;
import com.dsk.cscec.domain.vo.DCustomerListVo;
import com.dsk.cscec.mapper.DCustomerMapper;
import com.dsk.cscec.mapper.DSubcontractMapper;
import com.dsk.cscec.service.IDCustomerService;
import com.dsk.monitor.domain.vo.PushMonitorCompanyAddVo;
import com.dsk.search.service.BusinessOpportunityRadarService;
import com.dsk.system.utils.DskOpenApiUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 组织维表(DCustomer)表服务实现类
 *
 * @author lcl
 * @since 2023-12-08 14:57:26
 */
@Slf4j
@Service
public class DCustomerServiceImpl extends ServiceImpl<DCustomerMapper, DCustomer> implements IDCustomerService {

    @Resource
    private DSubcontractMapper subcontractMapper;
    @Autowired
    private BusinessOpportunityRadarService opportunityRadarService;


    @Resource
    private DskOpenApiUtil dskOpenApiUtil;

    @Override
    public TableDataInfo<DCustomerListVo> allSearchList(DCustomerSearchBo bo, PageQuery query) {
        dealWithCustomerClass(bo);
        ArrayList<Integer> companyIdList = new ArrayList<>();
        Page<DCustomerListVo> page = baseMapper.allSearchList(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());
                showCustomerClass(item);
                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");
                        companyIdList.add(companyId);
                        item.setCompanyId(companyId);
                    }
                } catch (Exception e) {
                    //
                }
                //关键字标红
                if (!ObjectUtils.isEmpty(bo.getCustomerName())) {
                    item.setCustomerName(StringUtils.markInRed(item.getCustomerName(), bo.getCustomerName()));
                }
            });
        }

        //填充供应商风险列表相关风险数量
        PushMonitorCompanyAddVo addVo = new PushMonitorCompanyAddVo();

        //列表中的企业无数据,下面三个cid有数据,用于测试
        //companyIdList.clear();
        //companyIdList.add(6034);
        //companyIdList.add(68152);
        //companyIdList.add(3068);

        addVo.setCid(companyIdList);
        Long userId = LoginHelper.getUserId();
        if (ObjectUtil.isNotEmpty(userId)) {
            addVo.setUserId(userId);
        }
        Map<String, Object> riskMap = dskOpenApiUtil.requestBody("/operate/monitor/riskList", BeanUtil.beanToMap(addVo, false, false));
        if (MapUtils.getInteger(riskMap, "code", 300) != 200) {
            return TableDataInfo.build(page);
        }
        Object riskData = MapUtils.getObject(riskMap, "data", null);
        if (ObjectUtil.isEmpty(riskData)) {
            return TableDataInfo.build(page);
        }
        a:
        for (Map<String, Object> risk : ((List<Map<String, Object>>) riskData)) {
            for (DCustomerListVo vo : page.getRecords()) {
                if (vo.getCompanyId().toString().equals(risk.get("cid").toString())) {
                    vo.setRiskTotal((Long) risk.get("riskCount"));
                    vo.setJudicatureRiskCount((Long) risk.get("sfCount"));
                    vo.setOperatingRiskCount((Long) risk.get("jyCount"));
                    vo.setBusinessRiskCount((Long) risk.get("gsCount"));
                    //TODO:不良行为与涉诉限用禁用需对接甲方数据
                    vo.setBadBehaviorCount(0L);
                    vo.setLimitedCount(0L);
                    continue a;
                }
            }
        }
        return TableDataInfo.build(page);
    }

    @Override
    public List<DCustomerListVo> exportList(DCustomerSearchBo bo) {
        dealWithCustomerClass(bo);
        PageQuery query = new PageQuery();
        List<DCustomerListVo> records = baseMapper.allSearchList(query.build(), bo).getRecords();
        if (CollectionUtils.isNotEmpty(records)) {
            for (int i = 0; i < records.size(); i++) records.get(i).setNum(i);
            records.parallelStream().forEach(item -> {
                DCustomerListVo vo = subcontractMapper.selectStatisticByCustomerId(item.getCustomerId());
                //企业合作数量
                item.setEnterpriseCooperationCount(vo.getEnterpriseCooperationCount());
                //项目合作数量
                item.setProjectCooperationCount(vo.getProjectCooperationCount());
                showCustomerClass(item);
            });
        }
        return records;
    }

    @Override
    public DCustomer info(String customerKey) {
        DCustomer customer = baseMapper.selectById(customerKey);
        setCertificate(customer);
        return customer;
    }

    private void setCertificate(DCustomer customer) {
        if (ObjectUtils.isEmpty(customer)) return;
        //营业执照url
        customer.setBusinessLicenseList(baseMapper.selectBusinessLicense(customer.getCustomerId()));
        //组织机构代码证url
        customer.setOrgCertificateList(baseMapper.selectOrgCertificate(customer.getCustomerId()));
        //税务登记证url
        customer.setTaxCertificateList(baseMapper.selectTaxCertificate(customer.getCustomerId()));
        //资质证书url
        customer.setQualificationCertificateList(baseMapper.selectQualificationCertificate(customer.getCustomerId()));
        //安全生产url
        customer.setSafetyCertificateList(baseMapper.selectSafetyCertificate(customer.getCustomerId()));
        //增值税一般纳税人资格证明url
//        customer.setRatepayerCertificateList(baseMapper.selectRatepayerCertificate(customer.getCustomerId()));
        //业绩报告url
        customer.setPerformanceCertificateList(baseMapper.selectPerformanceCertificate(customer.getCustomerId()));
        //考察报告url
        customer.setInspectionCertificateList(baseMapper.selectInspectionCertificate(customer.getCustomerId()));
        //其他url
        customer.setOtherCertificateList(baseMapper.selectOtherCertificate(customer.getCustomerId()));
    }

    private void dealWithCustomerClass(DCustomerSearchBo bo) {
        if (!ObjectUtils.isEmpty(bo.getCustomerClass())) {
            List<String> list = new ArrayList<>();
            Integer isTeam = null;
            for (String customerClass : bo.getCustomerClass()) {
                switch (customerClass) {
                    case "专业分包":
                        list.add("专业分包");
                        break;
                    case "物资设备":
                        list.add("分供");
                        break;
                    case "施工机械":
                        list.add("租赁");
                        break;
                    case "劳务分包":
                        if (isTeam == null) {
                            isTeam = 0;
                        } else if (isTeam == 1) {
                            isTeam = null;
                        }
                        list.add("劳务分包");
                        break;
                    case "劳务队伍":
                        if (isTeam == null) {
                            isTeam = 1;
                        } else if (isTeam == 0) {
                            isTeam = null;
                        }
                        list.add("劳务分包");
                        break;
                    default:
                        break;
                }
            }
            bo.setCustomerClass(list);
            bo.setIsTeam(isTeam);
        }
    }

    private void showCustomerClass(DCustomerListVo vo) {
        if (!ObjectUtils.isEmpty(vo.getCustomerClass())) {
            switch (vo.getCustomerClass()) {
                case "分供":
                    vo.setCustomerClass("物资设备");
                    break;
                case "租赁":
                    vo.setCustomerClass("施工机械");
                    break;
                case "劳务分包":
                    if (!ObjectUtils.isEmpty(vo.getLeaderName())) {
                        vo.setCustomerClass("劳务队伍");
                    }
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public R dynamicRiskStatistics(DCustomerDynamicRiskStatisticsVo riskStatisticsVo) {
        Long userId = LoginHelper.getUserId();
        if (ObjectUtil.isNotEmpty(userId)) {
            riskStatisticsVo.setUserId(userId);
        }
        riskStatisticsVo.setSystemCode("zjyj");
        Map<String, Object> map = dskOpenApiUtil.requestBody("/operate/monitor/dynamicRiskStatistics", BeanUtil.beanToMap(riskStatisticsVo, false, false));
        return BeanUtil.toBean(map, R.class);
    }

    @Override
    public R riskType(DCustomerDynamicRiskTypeVo riskTypeVo) {
        Long userId = LoginHelper.getUserId();
        if (ObjectUtil.isNotEmpty(userId)) {
            riskTypeVo.setUserId(userId);
        }
        //riskTypeVo.setCidList(this.queryCidByCustomerClass(riskTypeVo.getCustomerClass()));
        Map<String, Object> map = dskOpenApiUtil.requestBody("/operate/monitor/riskType", BeanUtil.beanToMap(riskTypeVo, false, false));
        return BeanUtil.toBean(map, R.class);
    }

    /**
     * 根据供应商类型查询cid
     *
     * @param customerClass 供应商类型
     * @return cidList
     */
    private List<Integer> queryCidByCustomerClass(String customerClass) {
        List<Integer> cidList = new ArrayList<>();
        List<DCustomer> customerList = new ArrayList<>();
        //customerClass = "专业分包";
        if (StringUtils.isEmpty(customerClass)) {
            customerList.addAll(baseMapper.selectList(new LambdaQueryWrapper<DCustomer>()
                    .select(DCustomer::getCustomerName)
                    .eq(DCustomer::getRecommendOrgId, "F17305B4EA4444CBAB12892C7B99E475")
                    .eq(DCustomer::getCustomerClass, "专业分包")));
            customerList.addAll(baseMapper.selectList(new LambdaQueryWrapper<DCustomer>()
                    .select(DCustomer::getCustomerName)
                    .eq(DCustomer::getRecommendOrgId, "F17305B4EA4444CBAB12892C7B99E475")
                    .eq(DCustomer::getCustomerClass, "租赁")));
            customerList.addAll(baseMapper.selectList(new LambdaQueryWrapper<DCustomer>()
                    .select(DCustomer::getCustomerName)
                    .eq(DCustomer::getRecommendOrgId, "F17305B4EA4444CBAB12892C7B99E475")
                    .eq(DCustomer::getCustomerClass, "分供")));
            customerList.addAll(baseMapper.selectList(new LambdaQueryWrapper<DCustomer>()
                    .select(DCustomer::getCustomerName)
                    .eq(DCustomer::getRecommendOrgId, "F17305B4EA4444CBAB12892C7B99E475")
                    .eq(DCustomer::getCustomerClass, "劳务分包")
                    .eq(DCustomer::getServiceTeamLogo, "N")));
            customerList.addAll(baseMapper.selectList(new LambdaQueryWrapper<DCustomer>()
                    .select(DCustomer::getCustomerName)
                    .eq(DCustomer::getRecommendOrgId, "F17305B4EA4444CBAB12892C7B99E475")
                    .eq(DCustomer::getCustomerClass, "劳务分包")
                    .eq(DCustomer::getServiceTeamLogo, "Y")));
        } else {
            //劳务队伍标志（Y/N）
            String serviceTeamLogo = null;
            if ("劳务分包".equals(customerClass)) {
                serviceTeamLogo = "N";
            }
            if ("劳务分包队伍".equals(customerClass)) {
                customerClass = "劳务分包";
                serviceTeamLogo = "Y";
            }
            customerList = baseMapper.selectList(new LambdaQueryWrapper<DCustomer>()
                    .select(DCustomer::getCustomerName)
                    .eq(DCustomer::getRecommendOrgId, "F17305B4EA4444CBAB12892C7B99E475")
                    .eq(DCustomer::getCustomerClass, customerClass)
                    .eq(StringUtils.isNoneEmpty(serviceTeamLogo), DCustomer::getServiceTeamLogo, serviceTeamLogo));
        }

        customerList.forEach(item -> {
            try {
                Map<String, Object> map = opportunityRadarService.enterpriseByName("山东兴华建设集团有限公司");
                if (!ObjectUtils.isEmpty(map.get("data"))) {
                    Map<String, Object> data = BeanUtil.beanToMap(map.get("data"));
                    Integer companyId = MapUtil.getInt(data, "jskEid");
                    cidList.add(companyId);
                }
            } catch (Exception e) {
                //
            }
        });
        return cidList;
    }

    @Override
    public R riskChange(DCustomerDynamicRiskChangeVo riskChangeVo) {
        Long userId = LoginHelper.getUserId();
        if (ObjectUtil.isNotEmpty(userId)) {
            riskChangeVo.setUserId(userId);
        }
        Map<String, Object> map = dskOpenApiUtil.requestBody("/operate/monitor/riskChange", BeanUtil.beanToMap(riskChangeVo, false, false));
        return BeanUtil.toBean(map, R.class);
    }
}

