package yem.wm.cm.csrm.utils;

import cn.hutool.core.util.CreditCodeUtil;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.operate.result.OperationResult;
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 java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.Callable;

/**
 * @program: yem-cosmic
 * @description:
 * @author: zsf
 * @create: 2024-06-12 14:45
 **/
public class TaskUtils {
    /**
     * 创建对应任务项
     * @param paramType
     * @return
     */
    public static List<Callable<Map<String, Object>>> creatTaskList(Map<String,Object> paramType) {
        // 定义任务列表
        DynamicObjectCollection loads = (DynamicObjectCollection) paramType.getOrDefault("loads", "");
        RequestContext rc = (RequestContext) paramType.getOrDefault("rc", "");
        List<Callable<Map<String, Object>>> tasks = new ArrayList<>();
        for (DynamicObject load : loads) {
            String method = load.getString("yem_plugin");
            tasks.add(() -> {
                RequestContext.set(rc);
                paramType.put("methodRoute",method);
                paramType.put("load",load);
                Map<String, Object> objectMap = getMethod(paramType);
                //更新对应客商申请单据
                if (objectMap.containsKey("merchantApply")){
                    DynamicObject merchant = (DynamicObject) objectMap.get("merchantApply");
                    paramType.put("merchantApply",merchant);
                }
                return objectMap;
            });
        }
        return tasks;
    }

    /**
     * 创建任务日志底表
     * @param next
     * @param flag
     * @return
     */

    public static Map<String, String> creatTaskTable(DynamicObject next,String flag) {
        QFilter qFilter11 = new QFilter("status", QCP.equals, "C");
        //过滤入口
        QFilter qFilter12 = new QFilter(flag, QCP.equals, true);
        QFilter[] filters = {qFilter11,qFilter12};
        Map<String, String> hashMap = new HashMap<>();
        //查询任务表
        DynamicObject[] loads = BusinessDataServiceHelper.load(PageIdEnum.TASK_ITEM.getPageId(), "number,name,yem_timeoutperiod,yem_plugin,enable,yem_tag", filters, "yem_sequence");
            //获取社会信用代码

        String societyCreditCode = String.valueOf(next.get("yem_societycreditcode"));
        //创建日志底表
        DynamicObject newBill = BusinessDataServiceHelper.newDynamicObject(PageIdEnum.TASK_ITEM_LOG.getPageId());
        //统一社会信用代码
        newBill.set("yem_societycreditcode", societyCreditCode);
        //创建人
        newBill.set("creator", BusinessDataServiceHelper.loadSingleFromCache(RequestContext.get().getCurrUserId(), "bos_user"));
        //创建时间
        newBill.set("createtime", new Date());
        newBill.set("billstatus", "A");
        int Index = 0;
        DynamicObjectCollection logdetails = newBill.getDynamicObjectCollection("yem_entryentity");
        for (DynamicObject load : loads) {
            DynamicObject entry = logdetails.addNew();
            entry.set("yem_ordernum", ++Index);
            entry.set("yem_basedatafield", load);
            entry.set("yem_plugin",load.getString("yem_plugin"));
            entry.set("yem_taskstatus", 0);
        }
        OperationResult yemTaskItemLog = SaveServiceHelper.saveOperate("save", PageIdEnum.TASK_ITEM_LOG.getPageId(), new DynamicObject[]{newBill}, OperateOption.create());
        SaveServiceHelper.update(next);
        if (yemTaskItemLog.isSuccess()) {
            hashMap.put(societyCreditCode, newBill.getPkValue().toString());
        }
        return hashMap;
    }

    /**
     * 通过反射获取对应插件，以及对应方法对应对应参数
     * @param paramType
     * @return
     */
    public static Map<String,Object> getMethod(Map<String,Object> paramType){
        String methodRoute = String.valueOf(paramType.get("methodRoute"));
        String className = methodRoute.substring(0, methodRoute.indexOf('#'));
        String methodName = methodRoute.substring(methodRoute.indexOf('#') + 1);
        try {
            Class<?> aClass = Class.forName(className);
            //设置传入的参数类型
            Class<?>[] parameterTypes = new Class<?>[]{Map.class};
            Method method = aClass.getMethod(methodName, parameterTypes);
            Map<String,Object> invoke = (Map<String, Object>) method.invoke(null,paramType);
            return invoke;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
