package nckd.jimin.jyyy.hr.wtc.wtabm.opplugin.web.vaapply;

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.executor.AbstractTask;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.hr.hbp.business.servicehelper.HRBaseServiceHelper;
import kd.sdk.plugin.Plugin;

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

/**
 * Tyx 2025-04-27
 * 休假更新员工状态定时任务插件
 * 查询休假单数据，更新这些请假人员的基本信息-员工状态字段为长期休假
 * 具体数据过滤条件：
 * nckd_isupdateperson = false and nckd_islongleave = true
 * ischange = false and ishavechange = false
 * auditstatus = 'C' and startdate < now();
 */
public class VaApplyBillTask extends AbstractTask implements Plugin {

    private static String apply_entity = "wtabm_vaapply";
    private static final Log log = LogFactory.getLog(VaApplyBillTask.class);
    @Override
    public void execute(RequestContext requestContext, Map<String, Object> map) throws KDException {

        log.info("-------- 开始执行请假单定时更新长假员工状态 --------");
        String selectFields = "personid,startdate,enddate,nckd_isupdateperson,nckd_islongleave,entryentity.entryvacationtype";
        HRBaseServiceHelper helper = HRBaseServiceHelper.create(apply_entity);
        QFilter filter = new QFilter("nckd_islongleave", QCP.equals, true);
        filter.and("ischange", QCP.equals, false);
        filter.and("ishavechange", QCP.equals, false);
        filter.and("auditstatus", QCP.equals, "C");
        filter.and("startdate", QCP.less_equals, new Date());
        filter.and("nckd_isupdateperson", QCP.equals, false);
        DynamicObject[] bills = BusinessDataServiceHelper.load(apply_entity, selectFields, new QFilter[]{filter});
        log.info("-------- 查询出符合条件的休假单条数：" + bills.length + " --------");
        for(DynamicObject bill : bills) {
            //获取到人员
            Long personId = bill.getLong("personid_id");
            //获取到假期类型 根据假期类型判断员工状态编码
            String typeNumber = "";

            DynamicObjectCollection entryCols = bill.getDynamicObjectCollection("entryentity");
            if(entryCols.size() > 0) {
                DynamicObject entry = entryCols.get(0);
                String vacationNumber = entry.getString("entryvacationtype.number");
                if (vacationNumber.equals("1060_S")) {
                    typeNumber = "9020_S";  //产假
                } else {
                    typeNumber = "9010_S";  //长假
                }
                //更新员工档案
                VaApplyBillUtil.updatePersonType(typeNumber, personId);
                //更新单据上nckd_isupdateperson字段
                bill.set("nckd_isupdateperson", true);
            }
        }
        SaveServiceHelper.save(bills);
    }
}