package nckd.jimin.jyyy.hr.hrmp.hbpm.opplugin.web.position;

import kd.bos.algo.DataSet;
import kd.bos.algo.Row;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.db.DB;
import kd.bos.db.DBRoute;
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.hr.hdm.business.domain.parttime.ParttimeServiceHelper;
import kd.hr.hdm.business.domain.transfer.service.external.PersonExternalService;
import kd.sdk.plugin.Plugin;
import nckd.jimin.jyyy.hr.wtc.wtabm.opplugin.web.vaapply.VaApplyBillUtil;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 自动取消兼岗调度插件
 * Tyx 2025-05-06
 * 查询 同时存在主职和兼职的岗位，取消该岗位的所有兼职，需排除长假场景（长假员工的基本信息中的员工状态为长假，但实际主职岗位不发生变化，这种场景视作该岗位上没有主职
 */
public class AutoEndPartTimeTask extends AbstractTask implements Plugin {
    private static final Log log = LogFactory.getLog(AutoEndPartTimeTask.class);
    private static String ermanFile_entity = "hspm_ermanfile";

    @Override
    public void execute(RequestContext requestContext, Map<String, Object> map) throws KDException {
        log.info(" -------- 自动取消兼岗开始 -------- ");
        StringBuilder sb = new StringBuilder();

        sb.append(" /*dialect*/ select * from (\n");
        sb.append(" select a.fpositionid,max(a.fisprimary) maxp,min(a.fisprimary) minp \n");
        sb.append(" from t_hrpi_empposorgrel a \n");
        sb.append(" left join t_hrpi_pernontsprop b on a.fpersonid = b.fpersonid and b.fiscurrentversion = '1' \n");
        sb.append(" left join t_hbss_laborrelstatus c on c.fid = b.fk_nckd_ygzt \n");
        sb.append(" where a.fiscurrentversion = '1' \n");
        sb.append("   and a.fbusinessstatus = '1' \n");
        sb.append("   and (c.fnumber <> '9010_S' or c.fnumber is null) \n");
        sb.append(" group by a.fpositionid \n");
        sb.append(" ) a where a.maxp = '1' and a.minp = '0' ");
        log.info(" -------- sql : " +sb.toString()+ " -------- ");
        DataSet dataSet = DB.queryDataSet(this.getClass().getName(), DBRoute.of("hr"), sb.toString());

        List<Long> positionIds = new ArrayList<Long>();
        while(dataSet.hasNext()) {
            Row rowData = dataSet.next();
            positionIds.add(rowData.getLong("fpositionid"));
        }

        //取出岗位下所有兼职
        if(positionIds.size() > 0) {
            //获取档案
            DynamicObject[] ermanFiles = VaApplyBillUtil.getErmanFilesByPosition(positionIds);
            //转成List<Long>
            List<Long> ermanFileIds = Arrays.stream(ermanFiles).map(dyx -> dyx.getLong("id")).collect(Collectors.toList());
            //调用标准方法获取ermanFile
            List<Map<String, Object>> erManFiles = PersonExternalService.getInstance().invokeGetCardFields(ermanFileIds);
            //actionId 默认201100_S
            QFilter filter = new QFilter("number", "=", "201100_S");
            DynamicObject action = BusinessDataServiceHelper.loadSingle("hpfs_chgaction",new QFilter[]{filter});
            Date partEndDate = new Date();
            //调用标准终止兼职方法
            log.info(" -------- begin 调用标品终止兼职方法 --------");
            ParttimeServiceHelper.batchEndParttime(action.getLong("id"), partEndDate, erManFiles);
            log.info(" -------- after 调用标品终止兼职方法 --------");
        }

    }

    /**
     * 组装查询兼职档案的过滤条件
     * @param positionIds
     * @return
     */
    public QFilter getQFilter(List<Long> positionIds) {
        QFilter filter = new QFilter("depemp.iscurrentversion", QCP.equals, "1");
        filter.and("depemp.businessstatus", QCP.equals, "1");
        filter.and("depemp.postype.number",QCP.equals, "1020_S");
        filter.and("depemp.position", QCP.in, positionIds);
        filter.and("iscurrentversion", QCP.equals, "1");
        filter.and("businessstatus", QCP.equals, "1");
        return filter;
    }
}