package yem.wm.cm.csrm.form;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.exception.KDException;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.schedule.api.Task;
import kd.bos.schedule.executor.AbstractTask;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import yem.base.common.utils.YEM;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 计算任务耗时
 *
 * @Author yunshuaiwei
 * @Date 2024/6/5 11:57
 * @Version 1.0
 **/
public class ComputingTaskTime extends AbstractTask implements Task {
    Log log = LogFactory.getLog(ComputingTaskTime.class);

    @Override
    public void execute(RequestContext requestContext, Map<String, Object> map) throws KDException {
        log.info("计算任务平均耗时定时任务执行，执行时间：{}", DateUtil.now());
        //1.查询所有任务
        DynamicObject[] taskItems = BusinessDataServiceHelper.load("yem_base_taskitem", "id,number,name,yem_timeoutperiod",
                new QFilter[]{new QFilter("status", QCP.equals, "C")});

        if (YEM.isNotEmpty(taskItems)) {
            //7天前
            DateTime newDate = DateUtil.offsetDay(DateUtil.date(), -7);
            //2.查询任务日志
            DynamicObject[] taskLogDetails = BusinessDataServiceHelper.load("yem_cm_taskitemlog", "id,number,yem_entryentity.yem_timespend,yem_entryentity.yem_basedatafield",
                    new QFilter[]{new QFilter("createtime", QCP.large_than, newDate.toSqlDate()),
                            new QFilter("yem_entryentity.yem_taskstatus", QCP.equals, "2")});
            if (YEM.isNotEmpty(taskLogDetails)) {
                DynamicObjectCollection dynamicObjects = new DynamicObjectCollection();
                Arrays.stream(taskLogDetails).forEach(taskLogDetail -> {
                    DynamicObjectCollection dynamicObject = taskLogDetail.getDynamicObjectCollection("yem_entryentity");
                    dynamicObjects.addAll(dynamicObject);
                });
                Map<Long, DynamicObjectCollection> collectionHashMap = new HashMap<>();
                for (DynamicObject dynamicObject : dynamicObjects) {
                    long aLong = dynamicObject.getLong("yem_basedatafield.id");
                    DynamicObjectCollection objects = collectionHashMap.getOrDefault(aLong, new DynamicObjectCollection());
                    objects.add(dynamicObject);
                    collectionHashMap.put(aLong, objects);
                }
                for (DynamicObject taskItem : taskItems) {
                    long totalTime = 0L;
                    long id = taskItem.getLong("id");
                    DynamicObjectCollection objects = collectionHashMap.get(id);
                    if (YEM.isNotEmpty(objects)) {
                        int size = objects.size();
                        for (DynamicObject object : objects) {
                            long timeSpend = YEM.isEmpty(object.getString("yem_timespend")) ? 0L : Long.parseLong(object.getString("yem_timespend"));
                            totalTime += timeSpend;
                        }
                        long ms = totalTime / size;
                        long l = TimeUnit.MILLISECONDS.toSeconds(ms) % 60;
                        taskItem.set("yem_timeoutperiod", Math.max(l, 1));
                        SaveServiceHelper.update(taskItem);
                    }
                }
            }
        }
    }
}
