package yem.wm.cm.csrm.qcc;

import kd.bos.data.BusinessDataReader;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.metadata.IDataEntityType;
import kd.bos.dataentity.serialization.SerializationUtils;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.botp.runtime.ConvertOperationResult;
import kd.bos.entity.botp.runtime.PushArgs;
import kd.bos.entity.datamodel.IRefrencedataProvider;
import kd.bos.entity.datamodel.ListSelectedRow;
import kd.bos.entity.filter.FilterCondition;
import kd.bos.exception.KDBizException;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.permission.cache.util.PermCommonUtil;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.botp.ConvertServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import yem.base.common.module.version.helper.NewVersionHelper;
import yem.base.common.utils.StringUtils;
import yem.base.common.utils.YEM;
import yem.wm.cm.csrm.enums.PageIdEnum;
import yem.wm.cm.sys.utils.DynamicObjectUtil;
import yem.wm.cm.sys.utils.RatingUtil;

import java.math.BigDecimal;
import java.util.*;

/**
 * @program: yem-cosmic
 * @description: 企查查评分方案
 * @author: zsf
 * @create: 2024-06-17 09:57
 **/
public class QccScorePlan {

    private final static String APPLY_NAME = "yem_cm_merchantapply";

    private final static String APPLY_SCORE = "yem_cm_merchantrating";
    private final static String SCORE_PLAN = "yem_bd_score_plan";
    public static DynamicObject getScorePlan(DynamicObject merchan,String id){
        //获取企业风险评估默认方案
        if (!StringUtils.isBlank(id) && !StringUtils.isEmpty(id)){
            DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle(Long.parseLong(id), SCORE_PLAN);
            return dynamicObject;
        }
        String billno = merchan.getString("billno");
        //查询评分方案
        String properties = "yem_elaborate_tag,yem_entryentity.yem_scoreindexgroup,yem_entryentity.yem_scoringrubrics,yem_entryentity.yem_weight,yem_entryentity.yem_descindicator,";
        QFilter yemElaborateTag = new QFilter("yem_elaborate_tag", QCP.not_equals, "");
        QFilter qFilter1 = new QFilter("status", QCP.equals, "C");
        QFilter qFilter2 = new QFilter("yem_default", QCP.equals, false);
        QFilter[] qilters =  new QFilter[]{yemElaborateTag,qFilter1,qFilter2};
        DynamicObject[] load = BusinessDataServiceHelper.load(SCORE_PLAN, properties, qilters);
        if (load.length > 0){
            for (DynamicObject dynamicObject : load) {
                String value = dynamicObject.getString("yem_elaborate_tag");
                //启用规则大文本
                FilterCondition filterCondition = SerializationUtils.fromJsonString(value, FilterCondition.class);
                QFilter qFilter = PermCommonUtil.getQFilterFromEntNumFilterCondition(APPLY_NAME, filterCondition);
                DynamicObject object = BusinessDataServiceHelper.loadSingle(APPLY_NAME, new QFilter[]{new QFilter("billno", QCP.equals, billno), qFilter});
                if (YEM.isNotEmpty(object)) {
                    return dynamicObject;
                }
            }
        }
        //默认取第一个无启用规则的评分条件
        DynamicObject[] loads = BusinessDataServiceHelper.load(SCORE_PLAN, properties, new QFilter[]{new QFilter("yem_default", QCP.equals, true),qFilter1}, "createtime");
        return loads[0];
    }
    public static Boolean UpdataScorePlan(DynamicObject merchantApply,String scorPlanId) {
        //根据社会信用代码以及以及对应的评分方案查询是否有对饮的评分单生成
        //获取社会信用代码
        String yemSocietycreditcode = merchantApply.getString("yem_societycreditcode");
        //获取评分方案
        DynamicObject scoringScheme = getScorePlan(merchantApply, scorPlanId);
        QFilter qFilter = new QFilter("yem_societycreditcode",QCP.equals,yemSocietycreditcode);
        QFilter qFilter1 = new QFilter("yem_scoringscheme.id",QCP.equals,scoringScheme.getPkValue());
        QFilter qFilter2 = new QFilter("billstatus",QCP.equals,"A");
        QFilter[] qFilters = new QFilter[]{qFilter,qFilter1,qFilter2};
        String proper = new String("billno,yem_gradingscale,yem_totalscore1,yem_initialscore,yem_societycreditcode,yem_scoringbreakdo.yem_scoreindexgroup,yem_scoringbreakdo.yem_scoringrubrics,yem_scoringbreakdo.yem_weight,yem_scoringbreakdo.yem_descindicator,yem_scoringbreakdo.yem_specificvalues");
        DynamicObject merchantRating = BusinessDataServiceHelper.loadSingle(APPLY_SCORE,proper, qFilters);
        if (!YEM.isEmpty(merchantRating)){
            Map<String, Object> score = score(merchantApply, merchantRating, scoringScheme, true);
            BigDecimal totalscore = (BigDecimal) score.get("totalscore");
            //获取评分等级
            String yemLevel = RatingUtil.setLevel(merchantApply, totalscore, "yem_level");
            merchantApply.set("yem_totalscore",totalscore);
            merchantApply.set("yem_level",yemLevel);
            SaveServiceHelper.update(new DynamicObject[]{merchantApply});
            return false;
        }
        return true;
    }

    /**
     * 客商申请单下推生成评分单
     * @param dataEntitie
     */
    public static void push(DynamicObject dataEntitie,String scorPlanId) {
        PushArgs pushArgs = new PushArgs();
        String name = dataEntitie.getDataEntityType().getName();
        Long id = (Long) dataEntitie.getPkValue();
        NewVersionHelper newVersionHelper = new NewVersionHelper(name);
        if (newVersionHelper.isChanged()) {
            name = newVersionHelper.getRequireKey();
            //客商评审内码id
            id = dataEntitie.getLong("yem_masterid");
        }
        pushArgs.setSourceEntityNumber(name);
        pushArgs.setTargetEntityNumber(APPLY_SCORE);
        pushArgs.setHasRight(true);
        pushArgs.setBuildConvReport(true);
        //客商申请单下推客商准入单
//        pushArgs.setRuleId(RULE_ID);
        List<ListSelectedRow> selectedRows = new ArrayList<>();
        ListSelectedRow srcBill1 = new ListSelectedRow(id);
        selectedRows.add(srcBill1);
        pushArgs.setSelectedRows(selectedRows);
        ConvertOperationResult pushResult = ConvertServiceHelper.push(pushArgs);
        if (pushResult.isSuccess()) {
            MainEntityType targetMainType = EntityMetadataCache.getDataEntityType(APPLY_SCORE);
            List<DynamicObject> targetBillObjs = pushResult.loadTargetDataObjects(new IRefrencedataProvider() {
                @Override
                public void fillReferenceData(Object[] objs, IDataEntityType dType) {
                    BusinessDataReader.loadRefence(objs, dType);
                }
            }, targetMainType);
            //评分单进行评分
            for(DynamicObject targetBillObj : targetBillObjs) {
//			SaveServiceHelper.save(new DynamicObject[] {targetBillObj});
                //dataEntitie:客商申请表实体，targetBillObj:评分单实体
                createMerchantRating(dataEntitie,targetBillObj, true,scorPlanId);
            }
        }

    }
    public static void createMerchantRating(DynamicObject merchantApply,DynamicObject merchantRating, Boolean type,String scorPlanId) {
        //获取对应的评分方案:是否风险评估方案默认方案
        DynamicObject scoringScheme = getScorePlan(merchantApply,scorPlanId) ;
        if (scoringScheme == null) {
            throw new KDBizException("该客商分类没有评分方案,请前往设置！");
        }
        merchantRating.set("yem_scoringscheme", scoringScheme);
        //merchantRating.set("billno", merchantApply.getString("billno"));
        Map<String, Object> score = score(merchantApply, merchantRating, scoringScheme, false);
        BigDecimal totalscore = (BigDecimal) score.get("totalscore");
        //获取评分等级
        String yemLevel = RatingUtil.setLevel(merchantApply, totalscore, "yem_level");
        merchantApply.set("yem_totalscore",totalscore);
        merchantApply.set("yem_level",yemLevel);
        merchantApply.set("yem_scoringscheme", scoringScheme);
        SaveServiceHelper.update(new DynamicObject[]{merchantApply});
    }
    public static Map<String,Object> score(DynamicObject merchantApply, DynamicObject merchantRating, DynamicObject scoringScheme, Boolean flag) {
        Map<String,Object> map = new HashMap<>();
        BigDecimal totalscore = BigDecimal.ZERO;
        //评分单分录评分明细
        DynamicObjectCollection scoringbreakdos = merchantRating.getDynamicObjectCollection("yem_scoringbreakdo");
        //评分方案中评分指标分录
        DynamicObjectCollection scoringmetrics = scoringScheme.getDynamicObjectCollection("yem_entryentity");
        scoringbreakdos.clear();
        //评分单中添加对应的评分指标项目
        for (DynamicObject scoringmetric : scoringmetrics) {
            //评分指标
            DynamicObject scoringrubrics = scoringmetric.getDynamicObject("yem_scoringrubrics");
            DynamicObject addNew = scoringbreakdos.addNew();
            addNew.set("yem_scoreindexgroup", scoringmetric.getDynamicObject("yem_scoreindexgroup"));
            addNew.set("yem_scoringrubrics", scoringmetric.getDynamicObject("yem_scoringrubrics"));
            addNew.set("yem_weight", scoringmetric.getBigDecimal("yem_weight"));
            addNew.set("yem_descindicator", scoringrubrics.getString("yem_indicator"));
            Map<Boolean, BigDecimal> contents = new HashMap<Boolean, BigDecimal>();
            String yemPointertype = scoringrubrics.getString("yem_pointertype");
            switch(yemPointertype){
                case "D":
                    //执行配置
                    //评分指标指标配置
                    BigDecimal score = getScore(merchantApply, scoringrubrics);
                    addNew.set("yem_specificvalues",score);
                    totalscore = totalscore.add(score);
                    break;
                case "E":
                    //插件执行特殊流程
                    break;
                default:
                    break;
            }

        }
        BigDecimal newScore = totalscore.add(new BigDecimal(100));

        map.put("totalscore",newScore);
        // 获取评分等级
        Map<Object, DynamicObject> gradingScaleMaps = DynamicObjectUtil.getFiledDynamicObject(PageIdEnum.BD_GRADINGSCALE.getPageId(), null, "id");
        //设置对应的评分等级
        Collection<DynamicObject> gradingScales = gradingScaleMaps.values();
        for (DynamicObject gradingScale : gradingScales) {
            BigDecimal upperLimit = gradingScale.getBigDecimal("yem_upperlimit");
            BigDecimal lowerLimit = gradingScale.getBigDecimal("yem_lowerlimit");
            if (newScore.compareTo(lowerLimit) >= 0 && newScore.compareTo(upperLimit) <= 0) {
                merchantRating.set("yem_gradingscale", gradingScale);
                break;
            }
        }
        merchantRating.set("yem_totalscore1",newScore);
        merchantRating.set("yem_initialscore",newScore);
        merchantRating.set("yem_societycreditcode",merchantApply.getString("yem_societycreditcode"));
        if (flag){
            SaveServiceHelper.update(new DynamicObject[]{merchantRating});
        }else {
            SaveServiceHelper.saveOperate("save", APPLY_SCORE, new DynamicObject[]{merchantRating}, OperateOption.create());
        }
        return map;
    }
    private static BigDecimal getScore(DynamicObject merchantApply,DynamicObject scoringrubrics){
        Long pkValue = (Long) scoringrubrics.getPkValue();
        DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle(pkValue, "yem_bd_scoringrubrics");
        DynamicObjectCollection objects = dynamicObject.getDynamicObjectCollection("yem_numerical1");
//        DynamicObject merchantApply = (DynamicObject)TaskUtils.globalData.get("merchantApply");
        if (YEM.isNotEmpty(merchantApply)){
            BigDecimal value = merchantApply.getBigDecimal(dynamicObject.getString("yem_filedtag"));
            for (DynamicObject numerical : objects) {
                BigDecimal upperLimit = numerical.getBigDecimal("yem_upperlimit1");
                BigDecimal lowerLimit = numerical.getBigDecimal("yem_lowerlimit1");
                if (value.compareTo(lowerLimit) > 0 && value.compareTo(upperLimit) <= 0) {
                    BigDecimal yemScore = numerical.getBigDecimal("yem_score1");
                    return yemScore;
                }
            }
        }
        return BigDecimal.ZERO;
    }
}
