package com.yem.wm.bd.basemodelib.task;

import com.yem.wm.utils.YEM;
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.exception.KDException;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.schedule.executor.AbstractTask;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;

import java.util.Date;
import java.util.Map;

/**
 * @Classname ResourceFilterTask
 * @Description TODO
 * @Date 2023/12/6 17:34
 * @Created by ZZSLL
 */

public class ResourceFilterTask extends AbstractTask
{
    @Override
    public void execute(RequestContext requestContext, Map<String, Object> map) throws KDException
    {
        System.out.println("ResourceFilterTask");
        // 产品经理下单确认
        DynamicObject[] basemodelib = BusinessDataServiceHelper.load("yem_tracktaskconsole_prod",
                "id", null);
        for (DynamicObject object : basemodelib) {
            long id = object.getLong("id");
            DynamicObject entity = BusinessDataServiceHelper.loadSingle(id, "yem_tracktaskconsole_prod");
            // 分录
            DynamicObjectCollection collection = entity.getDynamicObjectCollection("yem_es_materialinfo");
            for (DynamicObject dynamicObject : collection) {
                // 产品经理下单确认状态
                String orderStatus = dynamicObject.getString("yem_productstat");
                // 产品经理已确认
                if ("B".equals(orderStatus)) {
                    // 下单确认时间
                    Date confirmDate = dynamicObject.getDate("yem_confirmationdate");
                    // 时间超过30天
                    if (isOver30Days(confirmDate)) {
                        DynamicObject resource = BusinessDataServiceHelper.loadSingle(dynamicObject.getLong("yem_resourcenog.id"),"yem_bd_basemodelib");
                        if (resource != null) {
                            // 是否特殊资源
                            String isspecialres = resource.getString("yem_isspecialres");
                            if ("Y".equals(isspecialres)) {
                                // 禁用
                                OperationServiceHelper.executeOperate("disable", resource.getDynamicObjectType().getName(), new DynamicObject[]{resource}, YEM.getOption());
                            }
                        }
                    }
                }
            }
        }
    }

    public boolean isOver30Days(Date date) {
        Date currentDate = new Date();
        long millisecondsDifference = currentDate.getTime() - date.getTime();
        long daysDifference = millisecondsDifference / (24 * 60 * 60 * 1000);
        return daysDifference > 30;
    }
}
