package com.kingdee.eas.custom.dormitorysystem.application.service;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.BOSObjectFactory;
import com.kingdee.bos.Context;
import com.kingdee.bos.bsf.service.app.IHRMsfService;
import com.kingdee.bos.dao.AbstractObjectCollection;
import com.kingdee.bos.metadata.entity.*;
import com.kingdee.bos.metadata.query.util.CompareType;
import com.kingdee.bos.util.BOSUuid;
import com.kingdee.eas.basedata.person.PersonInfo;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.custom.dormitorysystem.application.*;
import com.kingdee.eas.custom.dormitorysystem.occupants.IOccupants;
import com.kingdee.eas.custom.dormitorysystem.occupants.OccupantsCollection;
import com.kingdee.eas.custom.dormitorysystem.occupants.OccupantsFactory;
import com.kingdee.eas.framework.CoreBillBaseCollection;
import com.kingdee.eas.framework.ICoreBillBase;
import com.kingdee.eas.hr.ats.AtsUtil;
import com.kingdee.eas.hr.base.HRBillBaseEntryInfo;
import com.kingdee.eas.hr.base.HRBillBaseInfo;
import com.kingdee.util.StringUtils;
import org.apache.log4j.Logger;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description 检查入住申请单是否重复、入住信息是否重复
 * @Date 2025/4/29 17:03
 * @Created by Heyuan
 */
public class CheckDuplicateCheckInByBillIdService implements IHRMsfService {
    private static Logger logger = Logger.getLogger(CheckDuplicateCheckInByBillIdService.class);

    @Override
    public Object process(
            Context ctx,
            Map<String, Object> params
    ) throws EASBizException, BOSException {
        String billIds = (String) params.get("billIds");
        if (StringUtils.isEmpty(billIds)) {
            logger.error("单据id不能为空!");
            throw new BOSException("单据id不能为空!");
        }
        Map<String, List<Map<String, Date>>> roomListMap = new HashMap<>();
        List<String> errorMsgList = new ArrayList<>();
        ICoreBillBase iCoreBillBase = (ICoreBillBase) BOSObjectFactory.createBOSObject(ctx,
                BOSUuid.read(billIds.split(",")[0]).getType());
        SelectorItemCollection sic = new SelectorItemCollection();
        sic.add("*");
        sic.add("entrys.*");
        sic.add("entrys.person.*");
        sic.add("entrys.person.personType.*");
        sic.add("entrys.checkInRoom.*");
        sic.add("entrys.checkInRoom.DormitoryType.*");
        FilterInfo filterInfo = new FilterInfo();
        FilterItemCollection filterItems = filterInfo.getFilterItems();
        //房间
        filterItems.add(new FilterItemInfo("id", AtsUtil.toSet(billIds), CompareType.INCLUDE));
        EntityViewInfo viewInfo = EntityViewInfo.getInstance(filterInfo, sic, null);
        CoreBillBaseCollection hrBillBaseCollection = iCoreBillBase.getCoreBillBaseCollection(viewInfo);
        for (int i = 0; i < hrBillBaseCollection.size(); i++) {
            HRBillBaseInfo hrBillBaseInfo = (HRBillBaseInfo) hrBillBaseCollection.get(i);
            String baseInfoNumber = hrBillBaseInfo.getNumber();
            //分录
            AbstractObjectCollection entrys = (AbstractObjectCollection) hrBillBaseInfo.get("entrys");
            for (int j = 0; j < entrys.size(); j++) {
                try {
                    HRBillBaseEntryInfo entryInfo = (HRBillBaseEntryInfo) entrys.getObject(j);
                    //入住日期
                    Date checkInDate = entryInfo.getDate("checkInDate");
                    if (checkInDate == null) {
                        throw new BOSException("入住日期不能为空!");
                    }
                    //退宿日期
                    Date checkoutDate = entryInfo.getDate("checkoutDate");
                    if (checkoutDate == null) {
                        throw new BOSException("退宿日期不能为空!");
                    }
                    //人员
                    PersonInfo personInfo = (PersonInfo) entryInfo.getObjectValue("person");
                    if (personInfo == null) {
                        throw new BOSException("人员不能为空!");
                    }
                    //1.根据人员、入住日期、退宿日期检查入住申请单是否重复
                    checkDuplicateCheckIn(ctx, personInfo, checkInDate, checkoutDate, entryInfo);
                    //2.根据人员、入住日期、退宿日期检查入住人员信息是否重复
                    checkDuplicateOccupants(ctx, personInfo, checkInDate, checkoutDate);
                    //3.根据人员、入住日期、退宿日期检查换宿单是否重复
                    checkDuplicateRoomChange(ctx, personInfo, checkInDate, checkoutDate);
                } catch (Exception e) {
                    logger.error("单据编号为" + baseInfoNumber + "校验未通过: " + e.getMessage());
                    errorMsgList.add("单据编号为" + baseInfoNumber + "校验未通过: " + e.getMessage());
                }
            }
        }
        Map result = new HashMap();
        if (errorMsgList.size() > 0) {
            result.put("code", 500);
            result.put("errorMsg", errorMsgList);
        } else {
            result.put("code", 200);
        }
        return result;
    }

    /**
     * 根据人员、入住日期、退宿日期检查换宿单是否重复
     *
     * @param ctx
     * @param personInfo
     * @param checkInDate
     * @param checkoutDate
     */
    protected void checkDuplicateRoomChange(
            Context ctx,
            PersonInfo personInfo,
            Date checkInDate,
            Date checkoutDate
    ) throws BOSException {
        String personInfoName = personInfo.getName();
        IRoomChangeApplicationEntry iRoomChangeApplicationEntry = RoomChangeApplicationEntryFactory.getLocalInstance(ctx);
        FilterInfo filterInfo = new FilterInfo();
        FilterItemCollection filterItems = filterInfo.getFilterItems();
        //人员
        filterItems.add(new FilterItemInfo("person", personInfo.getId()));
        //申请入住日期在入住日期和退宿日期之间
        filterItems.add(new FilterItemInfo("checkInDate", checkInDate, CompareType.LESS_EQUALS));
        filterItems.add(new FilterItemInfo("checkoutDate", checkInDate, CompareType.GREATER_EQUALS));
        //入住日期在申请入住日期和申请退宿日期之间
        filterItems.add(new FilterItemInfo("checkInDate", checkInDate, CompareType.GREATER_EQUALS));
        filterItems.add(new FilterItemInfo("checkInDate", checkoutDate, CompareType.LESS_EQUALS));
        filterInfo.setMaskString("#0 and ((#1 and #2) or (#3 and #4))");
        SelectorItemCollection sic = new SelectorItemCollection();
        sic.add("parent.number");
        EntityViewInfo viewInfo = EntityViewInfo.getInstance(filterInfo, sic, null);
        RoomChangeApplicationEntryCollection entryCollection = iRoomChangeApplicationEntry.getRoomChangeApplicationEntryCollection(viewInfo);
        StringBuilder errorMsg = new StringBuilder();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < entryCollection.size(); i++) {
            RoomChangeApplicationEntryInfo roomChangeApplicationEntryInfo = entryCollection.get(i);
            RoomChangeApplicationInfo parent = roomChangeApplicationEntryInfo.getParent();
            String number = parent.getNumber();
            errorMsg.append("员工[" + personInfoName + "]在[" + sdf.format(checkInDate) + "] ~ [" + sdf.format(checkoutDate) + "]期间与换宿申请单[" + number + "]日期存在交叉\n");
        }
        if (errorMsg.length() > 0) {
            throw new BOSException(errorMsg.toString());
        }
    }


    /**
     * 根据人员、入住日期、退宿日期检查入住人员信息是否重复
     *
     * @param ctx
     * @param personInfo   人员
     * @param checkInDate  入住日期
     * @param checkoutDate 退宿日期
     * @throws BOSException
     */
    protected void checkDuplicateOccupants(
            Context ctx,
            PersonInfo personInfo,
            Date checkInDate,
            Date checkoutDate
    ) throws BOSException {
        String personInfoName = personInfo.getName();
        IOccupants iOccupants = OccupantsFactory.getLocalInstance(ctx);
        FilterInfo filterInfo = new FilterInfo();
        FilterItemCollection filterItems = filterInfo.getFilterItems();
        //人员
        filterItems.add(new FilterItemInfo("person", personInfo.getId()));
        //申请入住日期在入住日期和退宿日期之间
        filterItems.add(new FilterItemInfo("CheckInDate", checkInDate, CompareType.LESS_EQUALS));
        filterItems.add(new FilterItemInfo("CheckOutDate", checkInDate, CompareType.GREATER_EQUALS));
        //入住日期在申请入住日期和申请退宿日期之间
        filterItems.add(new FilterItemInfo("CheckInDate", checkInDate, CompareType.GREATER_EQUALS));
        filterItems.add(new FilterItemInfo("CheckInDate", checkoutDate, CompareType.LESS_EQUALS));
        filterInfo.setMaskString("#0 and ((#1 and #2) or (#3 and #4))");
        SelectorItemCollection sic = new SelectorItemCollection();
        sic.add("parent.number");
        EntityViewInfo viewInfo = EntityViewInfo.getInstance(filterInfo, sic, null);
        OccupantsCollection occupantsCollection = iOccupants.getOccupantsCollection(viewInfo);
        StringBuilder errorMsg = new StringBuilder();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if (occupantsCollection.size() > 0) {
            errorMsg.append("员工[" + personInfoName + "]在[" + sdf.format(checkInDate) + "] ~ [" + sdf.format(checkoutDate) + "]期间与入住信息数据存在日期交叉\n");
            throw new BOSException(errorMsg.toString());
        }
    }

    /**
     * 根据人员、入住日期、退宿日期检查单据状态为已提交、审批中或审批通过的入住申请单是否重复
     *
     * @param ctx
     * @param personInfo   人员
     * @param checkInDate  入住日期
     * @param checkoutDate 退宿日期
     * @throws BOSException
     * @throws EASBizException
     */
    protected void checkDuplicateCheckIn(
            Context ctx,
            PersonInfo personInfo,
            Date checkInDate,
            Date checkoutDate,
            HRBillBaseEntryInfo entryInfo
    ) throws BOSException {
        String personInfoName = personInfo.getName();
        String entryId = entryInfo.getId().toString();
        ICheckInApplicationEntry iCheckInApplicationEntry = CheckInApplicationEntryFactory.getLocalInstance(ctx);
        FilterInfo filterInfo = new FilterInfo();
        FilterItemCollection filterItems = filterInfo.getFilterItems();
        //单据状态等于已提交、审批中或审批通过
        filterItems.add(new FilterItemInfo("parent.billState", "1,2,3", CompareType.INCLUDE));
        //申请入住日期在入住日期和退宿日期之间
        filterItems.add(new FilterItemInfo("checkInDate", checkInDate, CompareType.LESS_EQUALS));
        filterItems.add(new FilterItemInfo("checkoutDate", checkInDate, CompareType.GREATER_EQUALS));
        //入住日期在申请入住日期和申请退宿日期之间
        filterItems.add(new FilterItemInfo("checkInDate", checkInDate, CompareType.GREATER_EQUALS));
        filterItems.add(new FilterItemInfo("checkInDate", checkoutDate, CompareType.LESS_EQUALS));
        //人员
        filterItems.add(new FilterItemInfo("person", personInfo.getId()));
        //不等于当前分录数据
        filterItems.add(new FilterItemInfo("id", entryId, CompareType.NOTEQUALS));
        filterInfo.setMaskString("#0 and ((#1 and #2) or (#3 and #4)) and #5 and #6");
        SelectorItemCollection sic = new SelectorItemCollection();
        sic.add("parent.number");
        EntityViewInfo viewInfo = EntityViewInfo.getInstance(filterInfo, sic, null);
        CheckInApplicationEntryCollection entryCollection = iCheckInApplicationEntry.getCheckInApplicationEntryCollection(viewInfo);
        StringBuilder errorMsg = new StringBuilder();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < entryCollection.size(); i++) {
            CheckInApplicationEntryInfo checkInApplicationEntryInfo = entryCollection.get(i);
            CheckInApplicationInfo parent = checkInApplicationEntryInfo.getParent();
            String number = parent.getNumber();
            errorMsg.append("员工[" + personInfoName + "]在[" + sdf.format(checkInDate) + "] ~ [" + sdf.format(checkoutDate) + "]期间与入住申请单[" + number + "]日期存在交叉\n");
        }
        if (errorMsg.length() > 0) {
            throw new BOSException(errorMsg.toString());
        }
    }
}