package com.kingdee.eas.custom.handover.task;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.metadata.data.SortType;
import com.kingdee.bos.metadata.entity.*;
import com.kingdee.bos.metadata.function.WfEventListenerStateManager;
import com.kingdee.bos.metadata.query.util.CompareType;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.custom.handover.*;
import com.kingdee.eas.custom.handover.utils.WorkHandoverUtil;
import com.kingdee.eas.hr.affair.*;
import com.kingdee.eas.hr.ats.WorkCalendarItemCollection;
import com.kingdee.eas.hr.ats.WorkCalendarItemInfo;
import com.kingdee.util.DateTimeUtils;
import org.apache.log4j.Logger;

import java.util.Date;

public class WorkHandoverFacadeControllerBean extends AbstractWorkHandoverFacadeControllerBean {
    private static Logger logger = Logger.getLogger(WorkHandoverFacadeControllerBean.class);

    /**
     * 创建并提交工作交接单
     *
     * @param ctx
     * @param preDays 提前工作日天数
     * @throws BOSException
     * @throws EASBizException
     */
    @Override
    protected void _createAndSubmitHandover(
            Context ctx,
            int preDays
    ) throws BOSException, EASBizException {
        super._createAndSubmitHandover(ctx, preDays);
        //今天
        Date toDay = DateTimeUtils.truncateDate(new Date());
        boolean isWorkDay = WorkHandoverUtil.isWorkDay(ctx, toDay);
        if (!isWorkDay) {
            logger.error(DateTimeUtils.format(toDay) + "非工作日，不执行创建工作交接单任务！");
            return;
        }
        if (preDays <= 0) {
            preDays = 1;
        }
        IResignBizBillEntry iResignBizBillEntry = ResignBizBillEntryFactory.getLocalInstance(ctx);
        IWorkHandover iWorkHandover = WorkHandoverFactory.getLocalInstance(ctx);
        IWorkHandoverEntry iWorkHandoverEntry = WorkHandoverEntryFactory.getLocalInstance(ctx);
        //1.查询审批通过的离职单并且当前日期等于离职日期前两个工作日
        WorkCalendarItemCollection workCalendarItemCollection =
                WorkHandoverUtil.getWorkCalendarItemCollection(ctx, SortType.ASCEND, toDay, 30);
        if (workCalendarItemCollection.size() < preDays) {
            throw new BOSException("_createAndSubmitHandover 没有获取到指定工作日");
        }
        WorkCalendarItemInfo workCalendarItemInfo = workCalendarItemCollection.get(preDays - 1);
        Date date = workCalendarItemInfo.getDate();
        FilterInfo filterInfo = new FilterInfo();
        FilterItemCollection filterItems = filterInfo.getFilterItems();
        //单据状态为审批通过
        filterItems.add(new FilterItemInfo("bill.billState", "3"));
        //离职日期大于等于今天
        filterItems.add(new FilterItemInfo("bizDate", toDay, CompareType.GREATER_EQUALS));
        //离职日期小于等于后n个工作日期
        filterItems.add(new FilterItemInfo("bizDate", date, CompareType.LESS_EQUALS));
        //非自离
        filterItems.add(new FilterItemInfo("variationReason.number", "CTYY00302", CompareType.NOTEQUALS));
        SelectorItemCollection sic = new SelectorItemCollection();
        sic.add("*");
        sic.add("person.*");
        sic.add("bill.*");
        EntityViewInfo viewInfo = EntityViewInfo.getInstance(filterInfo, sic, null);
        //获取离职单分录
        ResignBizBillEntryCollection resignBizBillEntryCol = iResignBizBillEntry.getResignBizBillEntryCollection(viewInfo);
        for (int i = 0; i < resignBizBillEntryCol.size(); i++) {
            ResignBizBillEntryInfo resignBizBillEntryInfo = resignBizBillEntryCol.get(i);
            ResignBizBillInfo resignBizBillInfo = resignBizBillEntryInfo.getBill();
            try {
                //检查是否存在该离职单对应的交接单
                FilterInfo existsFilterInfo = new FilterInfo();
                existsFilterInfo.getFilterItems().add(new FilterItemInfo("resignBizBill", resignBizBillInfo.getId()));
                if (iWorkHandoverEntry.exists(existsFilterInfo)) {
                    //存在对同一离职单的交接单,跳过
                    continue;
                }
                //2.创建离职交接单
                WorkHandoverInfo workHandoverInfo = WorkHandoverUtil.generateWorkHandoverInfo(ctx, resignBizBillEntryInfo);
                //3.提交
                //再次检查工作交接单是否存在
                if (!iWorkHandoverEntry.exists(existsFilterInfo)) {
                    //提交工作流
                    WfEventListenerStateManager listenerStateManager = WfEventListenerStateManager.getInstance();
                    boolean isOpen = listenerStateManager.isEnable();
                    //开启工作流事务
                    if (!isOpen) {
                        listenerStateManager.enableEventListener();
                    }
                    iWorkHandover.submit(workHandoverInfo);
                    //如果本来工作流服务状态不是关的，将它关掉
                    if (!isOpen) {
                        listenerStateManager.disableEventListener();
                    }
                }
            } catch (Exception e) {
                logger.error("自动创建工作交接单任务报错: " + e.getMessage(), e);
                logger.error("自动创建工作交接单任务报错, resignBizBillInfoId : " + resignBizBillInfo.getId());
            }
        }
    }
}