package yem.wm.cm.csrm.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.exception.KDBizException;
import kd.bos.orm.ORM;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import yem.wm.cm.csrm.enums.PageIdEnum;
import yem.wm.cm.csrm.enums.TaskItemTypeEnum;
import yem.wm.cm.csrm.enums.TaskLogStatusEnum;
import yem.wm.cm.csrm.qcc.QccFakeData;
import yem.wm.cm.csrm.qcc.QccScorePlan;

import java.util.*;

/**
 * @program: yem-cosmic
 * @description:
 * @author: zsf
 * @create: 2024-06-05 12:50
 **/
public class QccUtils {

    /**
     * 对接企查查数据
     * @param paramMap
     * @return
     */
    public static Map<String,Object> StartQccTask(Map<String,Object> paramMap) {
        Map returnMap = new HashMap();
        DynamicObject load = (DynamicObject) paramMap.getOrDefault("load","");
        updateStatus(load, TaskLogStatusEnum.TASK_ING.getStatus(), 0L,"");
        try {
            String companyInfo = "{\n" +
        "    \"yem_keyno\": \"9151010078813015XE\",\n" +
        "    \"name\": \"西安云易贸信息科技有限公司\",\n" +
        "    \"yem_registration\": \"9151010078813015XE\"\n" +
        "}";
            JSONObject jsonObject = JSON.parseObject(companyInfo);
//            if (YEM.isNotEmpty(taskLog)) {
//                taskLog.set("yem_societycreditcode", jsonObject.getString("yem_keyno"));
//                SaveServiceHelper.update(taskLog);
//            }
            returnMap.put("taskType", TaskItemTypeEnum.QCC);
            returnMap.put("data", jsonObject);
            returnMap.put("flag",true);
            returnMap.put("load",load);
        } catch (Exception e) {
            updateStatus(load,TaskLogStatusEnum.STOP.getStatus(), System.currentTimeMillis(),e.getMessage());
            throw new KDBizException("企查查对接数据出现错误:" + e.getMessage());
        }
        return returnMap;
    }

    /**
     *  生成客商评分进行对应评分
     * @param paramMap
     * @return
     */
    public static Map<String,Object> startScoreTask(Map<String,Object> paramMap) {
        Map returnMap = new HashMap();
        DynamicObject load = (DynamicObject) paramMap.getOrDefault("load","");
        DynamicObject merchantApply = (DynamicObject) paramMap.getOrDefault("merchantApply","");
        String scorPlanId = String.valueOf(paramMap.getOrDefault("scorPlanId", ""));
        updateStatus(load, TaskLogStatusEnum.TASK_ING.getStatus(), 0L,"");
        try {
            //下推生成评分单评分
            if (QccScorePlan.UpdataScorePlan(merchantApply,scorPlanId)){
                QccScorePlan.push(merchantApply, scorPlanId);
            }
            returnMap.put("flag",true);
            returnMap.put("load",load);
            returnMap.put("taskType",TaskItemTypeEnum.SCORE);
        } catch (Exception e) {
            updateStatus(load,TaskLogStatusEnum.STOP.getStatus(), System.currentTimeMillis(), e.getMessage());
            throw new KDBizException("评分方案流程出现错误:" + e.getMessage());
        }
        return returnMap;
    }

    /**
     * 数据集成
     * @param paramMap
     * @return
     */
    public static Map<String,Object> startDataTask(Map<String,Object> paramMap) {
        Map returnMap = new HashMap();
        //对接qcc数据
        DynamicObject load = (DynamicObject) paramMap.getOrDefault("load","");
        DynamicObject merchantApply = (DynamicObject) paramMap.getOrDefault("merchantApply","");
        updateStatus(load, TaskLogStatusEnum.TASK_ING.getStatus(), 0L, "");
        Map<String, Object> objectMap = null;
        try {
            objectMap = QccFakeData.setCompanyBaseInfor(merchantApply);
            DynamicObject dynamicObject = (DynamicObject) objectMap.get("data");
            OperateOption operateOption = OperateOption.create();
            if (dynamicObject.getBoolean("yem_isadmit")){
                SaveServiceHelper.saveOperate(PageIdEnum.MERCHANT_APPLY.getPageId(), new DynamicObject[]{dynamicObject},operateOption);
            }else {
                SaveServiceHelper.update( new DynamicObject[]{dynamicObject});
            }
            returnMap.put("flag",true);
            returnMap.put("load",load);
            returnMap.put("merchantApply",dynamicObject);
        } catch (Exception e) {
            updateStatus(load, TaskLogStatusEnum.STOP.getStatus(), System.currentTimeMillis(), e.getMessage());
            throw new KDBizException("数据集成出现错误:" + e.getMessage());
        }
        return returnMap;
    }

    /**
     * 天眼查
     * @param paramMap
     * @return
     */
    public static Map<String,Object> startEysSelTask(Map<String,Object> paramMap) {
        Map returnMap = new HashMap();
        DynamicObject load = (DynamicObject) paramMap.getOrDefault("load","");
        updateStatus(load, TaskLogStatusEnum.TASK_ING.getStatus(), 0L, "");
        try {
            returnMap.put("flag",true);
            returnMap.put("load",load);
        } catch (Exception e) {
            updateStatus(load,TaskLogStatusEnum.STOP.getStatus(), System.currentTimeMillis(), e.getMessage());
            throw new KDBizException("天眼查流程执行错误:" + e.getMessage());
        }
        return returnMap;
    }

    /**
     * 修改日期表分录行信息
     *
     * @param load
     * @param status
     * @param ms
     * @param message
     */
    public static void updateStatus(DynamicObject load, String status, Long ms, String message) {
        //反写日志表状态
        if (status.equals("1")) {
            load.set("yem_taskstatus", status);
            SaveServiceHelper.update(load);
        } else if(status.equals("2")){
            load.set("yem_taskstatus", status);
            load.set("yem_consuming", timeFormat(ms));
            load.set("yem_timespend",ms);
            SaveServiceHelper.update(load);
        } else if(status.equals("3")){
            load.set("yem_taskstatus", status);
            load.set("yem_consuming", timeFormat(ms));
            load.set("yem_timespend",ms);
            load.set("yem_errormessage",message);
            SaveServiceHelper.update(load);
        }
    }

    /**
     * 修改申请单页面数据对接状态
     * @param billno
     * @param yem_finish_status
     */
    public static void updateApplyMessage(String billno,String yem_finish_status) {
        DynamicObject loadSingle = BusinessDataServiceHelper.loadSingle("yem_cm_merchantapply",
                new QFilter[]{new QFilter("billno", QCP.equals, billno)});
        loadSingle.set("yem_finish_status",yem_finish_status);
        SaveServiceHelper.save(new DynamicObject[]{loadSingle});
    }
    private static String timeFormat ( long ms){
        long diffInSeconds = ms / 1000;
        long hours = diffInSeconds / 3600;
        long minutes = (diffInSeconds % 3600) / 60;
        long seconds = diffInSeconds % 60;
        long millis = ms % 1000;
        // 使用String.format来格式化输出，确保每部分都是两位数（不足的话前面补0）
        return String.format("%02d:%02d:%02d.%03d", hours, minutes, seconds, millis);
    }
}
