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

import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.exception.KDException;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.message.api.MessageChannels;
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.workflow.MessageCenterServiceHelper;
import kd.bos.workflow.engine.msg.info.MessageInfo;
import kd.hr.hbp.business.servicehelper.HRBaseServiceHelper;
import kd.sdk.plugin.Plugin;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Tyx 2025-04-30
 * 预警插件
 * 查找未做销假的长假单，并通知对应人员
 */
public class VaApplyAlertTask extends AbstractTask implements Plugin {

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

        log.info("-------- 开始执行未销假休假单定时提醒 --------");
        String selectFields = "personid.number,billno,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("nckd_iscancelleave", QCP.equals, false);
        filter.and("auditstatus", QCP.equals, "C");
        filter.and("enddate", QCP.large_equals, new Date());
        DynamicObject[] bills = BusinessDataServiceHelper.load(apply_entity, selectFields, new QFilter[]{filter});
        log.info("-------- 查询出符合条件的休假单条数：" + bills.length + " --------");
        for (DynamicObject bill : bills) {
            //提醒person对应的user
            String personNo = bill.getString("personid.number");
            String billNo = bill.getString("billno");
            DynamicObject user = VaApplyBillUtil.getUserByPersonNo(personNo);
            //发送消息
            sendMessage(user, billNo);
        }
    }

    /**
     * 发送消息给指定用户
     * @param user userDyn
     * @param billNo 休假单单据编号
     */
    public void sendMessage (DynamicObject user, String billNo) {
        MessageInfo msgInfo = new MessageInfo();
        List<Long> userList = new ArrayList();
        userList.add(user.getLong("id"));
        msgInfo.setUserIds(userList);
        msgInfo.setNotifyType(MessageChannels.MC.getNumber());
        msgInfo.setType(MessageInfo.TYPE_MESSAGE);
        msgInfo.setContent("您有待销假的休假申请，单据号：" + billNo);
        //msgInfo.setContentUrl(); TODO 界面链接
        msgInfo.setTitle("销假提醒");
        Long msgId = MessageCenterServiceHelper.sendMessage(msgInfo);
    }
}