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

import com.kingdee.bos.BOSException;
import com.kingdee.bos.BOSObjectFactory;
import com.kingdee.bos.Context;
import com.kingdee.bos.dao.AbstractObjectCollection;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
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.org.HROrgUnitInfo;
import com.kingdee.eas.basedata.person.Genders;
import com.kingdee.eas.basedata.person.IPerson;
import com.kingdee.eas.basedata.person.PersonFactory;
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.application.utils.RoomChangeOrderUtil;
import com.kingdee.eas.custom.dormitorysystem.dormitory.DormitoryFactory;
import com.kingdee.eas.custom.dormitorysystem.dormitory.DormitoryInfo;
import com.kingdee.eas.custom.dormitorysystem.dormitory.IDormitory;
import com.kingdee.eas.custom.dormitorysystem.enumerationset.DormitoryClassification;
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.custom.dormitorysystem.occupants.OccupantsInfo;
import com.kingdee.eas.custom.dormitorysystem.otherbasicdata.DormitoryTypeInfo;
import com.kingdee.eas.custom.dormitorysystem.otherbasicdata.PersonDormitoryTypeInfo;
import com.kingdee.eas.framework.CoreBaseInfo;
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.shr.base.syssetting.BasicItemStateEnum;
import com.kingdee.shr.base.syssetting.context.SHRContext;
import com.kingdee.shr.base.syssetting.exception.SHRWebException;
import com.kingdee.shr.base.syssetting.exception.ShrWebBizException;
import com.kingdee.util.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.ui.ModelMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author qingwu
 * @date 2025/4/28
 * @apiNote
 */
public class HRBillBaseEditHandler extends DormitoryApplicationEditHandler {
    private Logger logger = Logger.getLogger(this.getClass());
    private Context ctx = SHRContext.getInstance().getContext();

    @Override
    protected void beforeSubmit(HttpServletRequest request, HttpServletResponse response, CoreBaseInfo model) throws SHRWebException {
        HRBillBaseInfo hrBillBaseInfo = (HRBillBaseInfo) model;
        HROrgUnitInfo hrOrgUnitInfo = new HROrgUnitInfo();
        hrOrgUnitInfo.setId(BOSUuid.read("00000000-0000-0000-0000-000000000000CCE7AED4"));
        hrBillBaseInfo.setHrOrgUnit(hrOrgUnitInfo);
        super.beforeSubmit(request, response, model);
    }

    /**
     * 保存校验
     *
     * @param request
     * @param response
     * @param modelMap
     */
    public void saveverifyAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws ShrWebBizException {
        logger.error("saveverifyAction---");
        RoomChangeApplicationInfo model = (RoomChangeApplicationInfo) request.getAttribute("dynamic_model");
        // RoomChangeApplicationInfo model = (RoomChangeApplicationInfo) request.getAttribute("dynamic_model");
        try {
            // 校验原入住人员信息 和 新入住人员信息
            verifyOccupants(model);
            // 校验原入住人员信息退宿日期是否小于当前时间
            verifyCheckOutDateBeforeCurrent(model);
            // 换宿单不能存在同员工日期交叉的数据
            verifyCheckNoDateOverlap(model);
            // 换宿单不能对有退宿单的入住信息进行换宿
            ValidateSwapWithCheckout(model);

        } catch (Exception e) {
            e.printStackTrace();
            throw new ShrWebBizException(e);
        }
    }

    public Map validateRoomAvailableByBillIds(String billIds) throws BOSException {
        logger.error("validateRoomAvailableByBillIds--");
        if (StringUtils.isEmpty(billIds)) {
            logger.error("单据id不能为空!");
            throw new BOSException("单据id不能为空!");
        }
        Map<String, List<Map<String, Date>>> roomListMap = new HashMap<String, List<Map<String, Date>>>();
        // StringBuilder errorMsg = new StringBuilder();
        List<String> errorMsgList = new ArrayList<String>();
        // HRBillBaseFactory.getLocalInstance()
        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.adjustRoom.*");
        sic.add("entrys.adjustRoom.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);
        logger.error("hrBillBaseCollection--" + hrBillBaseCollection.size());
        for (int i = 0; i < hrBillBaseCollection.size(); i++) {
            HRBillBaseInfo hrBillBaseInfo = (HRBillBaseInfo) hrBillBaseCollection.get(i);
            // String billId = hrBillBaseInfo.getId().toString();
            String baseInfoNumber = hrBillBaseInfo.getNumber();
            String bosType = hrBillBaseInfo.getId().getType().toString();
            AbstractObjectCollection entrys = (AbstractObjectCollection) hrBillBaseInfo.get("entrys");
            logger.error("entrys--" + entrys.size());
            for (int j = 0; j < entrys.size(); j++) {
                try {
                    HRBillBaseEntryInfo entryInfo = (HRBillBaseEntryInfo) entrys.getObject(j);
                    Date checkInDate = null;
                    // B371AC0A 换宿单分录  0CDEF948
                    if ("0CDEF948".equals(bosType)) {
                        // 换宿单
                        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("人员不能为空!");
                    }
                    // 房间
                    DormitoryInfo dormitory = (DormitoryInfo) entryInfo.getObjectValue("adjustRoom");
                    if (dormitory == null) {
                        throw new BOSException("房间不能为空!");
                    }
                    String roomId = dormitory.getId().toString();
                    // 根据入住日期,性别,员工类别查询可选房间
                    // 人员类型
                    PersonDormitoryTypeInfo personType = (PersonDormitoryTypeInfo) personInfo.get("personType");
                    if (personType == null) {
                        throw new BOSException("员工[" + personInfo.getName() + "]的人员类别为空，请及时维护！");
                    }
                    // String personTypeId = personType.getId().toString();
                    // 已住人数
                    int dormCheckInCount = 0;
                    // 1.校验房间信息
                    validateDormitoryInfo(ctx, personInfo, dormitory);
                    // 可住人数
                    int occupancyCapacity = dormitory.getOccupancyCapacity();
                    // 2.根据换宿日期和退宿日期算出入住信息房间已住人数
                    dormCheckInCount += getCheckInInfoByOccupants(ctx, checkInDate, checkoutDate, roomId, personType);
                    // 3.根据换宿日期和退宿日期算出入住申请单状态为申请中的已住人数
                    dormCheckInCount += getCheckInInfoByCheckInApplication(ctx, checkInDate, checkoutDate, roomId, personType);
                    // 4.根据换宿日期和退宿日期算出换宿申请单状态为申请中的已住人数
                    dormCheckInCount += getRoomChangeInfoByRoomChangeApplication(ctx, checkInDate, checkoutDate, roomId, personType);
                    // 5.根据当前参数缓存算出已住人数
                    if (roomListMap.containsKey(roomId)) {
                        List<Map<String, Date>> roomMapList = roomListMap.get(roomId);
                        for (int k = 0; k < roomMapList.size(); k++) {
                            Map<String, Date> roomMap = roomMapList.get(k);
                            Date checkInDateOld = roomMap.get("checkInDate");
                            Date checkoutDateOld = roomMap.get("checkoutDate");
                            // 申请入住日期在入住日期和退宿日期之间
                            // 入住日期在申请入住日期和申请退宿日期之间
                            if ((checkInDateOld.compareTo(checkInDate) <= 0 && checkoutDateOld.compareTo(checkInDate) >= 0)
                                    || (checkInDateOld.compareTo(checkInDate) >= 0 && checkInDateOld.compareTo(checkoutDate) <= 0)) {
                                dormCheckInCount++;
                            }
                        }
                    }
                    logger.error("occupancyCapacity--" + occupancyCapacity);
                    logger.error("dormCheckInCount--" + dormCheckInCount);
                    // 6.算出房间剩余可住人数: 可住人数 - 已住人数
                    if (occupancyCapacity - dormCheckInCount < 0) {
                        String dormitoryName = dormitory.getName();
                        throw new BOSException("当前入住人数" + dormCheckInCount + "，已超过房间[" + dormitoryName + "]可住人数" + occupancyCapacity + "，不能入住!");
                    }
                    Map roomMap = new HashMap();
                    roomMap.put("checkInDate", checkInDate);
                    roomMap.put("checkoutDate", checkoutDate);
                    if (roomListMap.containsKey(roomId)) {
                        roomListMap.get(roomId).add(roomMap);
                    } else {
                        List list = new ArrayList();
                        roomListMap.put(roomId, list);
                        list.add(roomMap);
                    }
                } catch (Exception e) {
                    logger.error("单据编号为" + baseInfoNumber + "校验未通过: " + e.getMessage(), e);
                    errorMsgList.add("单据编号为" + baseInfoNumber + "校验未通过: " + e.getMessage());
                    // errorMsg.append("单据编号为").append(baseInfoNumber).append("校验未通过: ").append(e.getMessage()).append(System.lineSeparator());
                }
            }
        }
        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 checkInDate  入住日期
     * @param checkoutDate 退宿日期
     * @param roomId       房间id
     * @param personType   人员类型
     * @return
     * @throws BOSException
     */
    private int getRoomChangeInfoByRoomChangeApplication(
            Context ctx,
            Date checkInDate,
            Date checkoutDate,
            String roomId,
            PersonDormitoryTypeInfo personType
    ) throws BOSException {
        IRoomChangeApplicationEntry iRoomChangeApplicationEntry = RoomChangeApplicationEntryFactory.getLocalInstance(ctx);
        FilterInfo filterInfo = new FilterInfo();
        FilterItemCollection filterItems = filterInfo.getFilterItems();
        // 房间
        filterItems.add(new FilterItemInfo("adjustRoom", roomId));
        // 申请入住日期在入住日期和退宿日期之间
        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("parent.billState", "1,2,3", CompareType.INCLUDE));
        filterInfo.setMaskString("#0 and ((#1 and #2) or (#3 and #4)) and #5");
        SelectorItemCollection sic = new SelectorItemCollection();
        sic.add("adjustRoom.id");
        sic.add("person.personType.id");
        sic.add("person.personType.name");
        EntityViewInfo viewInfo = EntityViewInfo.getInstance(filterInfo, sic, null);
        RoomChangeApplicationEntryCollection roomChangeApplicationEntryCol = iRoomChangeApplicationEntry.getRoomChangeApplicationEntryCollection(viewInfo);
        String personTypeId = personType.getId().toString();
        String personTypeName = personType.getName();
        // 已住人数
        int dormCheckInCount = 0;
        for (int i = 0; i < roomChangeApplicationEntryCol.size(); i++) {
            RoomChangeApplicationEntryInfo roomChangeApplicationEntryInfo = roomChangeApplicationEntryCol.get(i);
            // 房间
            PersonInfo person = roomChangeApplicationEntryInfo.getPerson();
            String personName = person.getName();
            // 人员类型
            PersonDormitoryTypeInfo personDormitoryType = (PersonDormitoryTypeInfo) person.get("personType");
            if (personDormitoryType == null) {
                throw new BOSException("员工[" + personName + "]的人员类别为空，请及时维护！");
            }
            String personDormitoryTypeId = personDormitoryType.getId().toString();
            String personDormitoryTypeName = personDormitoryType.getName();
            if (!personTypeId.equals(personDormitoryTypeId)) {
                throw new BOSException("人员类别[" + personTypeName + "]与宿舍类型[" + personDormitoryTypeName + "]不符，不能入住！");
            }
            // 累计已住人数
            dormCheckInCount++;
        }
        return dormCheckInCount;
    }

    /**
     * 根据入住日期和退宿日期算出入住申请单状态为申请中的已住人数
     *
     * @param ctx
     * @param checkInDate  入住日期
     * @param checkoutDate 退宿日期
     * @param roomId       房间id
     * @param personType   人员类型
     * @return
     * @throws BOSException
     */
    private int getCheckInInfoByCheckInApplication(
            Context ctx,
            Date checkInDate,
            Date checkoutDate,
            String roomId,
            PersonDormitoryTypeInfo personType
    ) throws BOSException {
        ICheckInApplicationEntry iCheckInApplicationEntry = CheckInApplicationEntryFactory.getLocalInstance(ctx);
        FilterInfo filterInfo = new FilterInfo();
        FilterItemCollection filterItems = filterInfo.getFilterItems();
        // 房间
        filterItems.add(new FilterItemInfo("checkInRoom", roomId));
        // 申请入住日期在入住日期和退宿日期之间
        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("parent.billState", "1,2,3", CompareType.INCLUDE));
        filterInfo.setMaskString("#0 and ((#1 and #2) or (#3 and #4)) and #5");
        SelectorItemCollection sic = new SelectorItemCollection();
        sic.add("checkInRoom.id");
        sic.add("person.personType.id");
        sic.add("person.personType.name");
        EntityViewInfo viewInfo = EntityViewInfo.getInstance(filterInfo, sic, null);
        CheckInApplicationEntryCollection checkInApplicationEntryCol = iCheckInApplicationEntry.getCheckInApplicationEntryCollection(viewInfo);
        String personTypeId = personType.getId().toString();
        String personTypeName = personType.getName();
        // 已住人数
        int dormCheckInCount = 0;
        for (int i = 0; i < checkInApplicationEntryCol.size(); i++) {
            CheckInApplicationEntryInfo checkInApplicationEntryInfo = checkInApplicationEntryCol.get(i);
            // 房间
            PersonInfo person = checkInApplicationEntryInfo.getPerson();
            String personName = person.getName();
            // 人员类型
            PersonDormitoryTypeInfo personDormitoryType = (PersonDormitoryTypeInfo) person.get("personType");
            if (personDormitoryType == null) {
                throw new BOSException("员工[" + personName + "]的人员类别为空，请及时维护！");
            }
            String personDormitoryTypeId = personDormitoryType.getId().toString();
            String personDormitoryTypeName = personDormitoryType.getName();
            if (!personTypeId.equals(personDormitoryTypeId)) {
                throw new BOSException("人员类别[" + personTypeName + "]与宿舍类型[" + personDormitoryTypeName + "]不符，不能入住！");
            }
            // 累计已住人数
            dormCheckInCount++;
        }
        return dormCheckInCount;
    }

    /**
     * 校验房间信息
     *
     * @param ctx
     * @param personInfo
     * @param dormitory  房间
     * @return
     * @throws BOSException
     * @throws EASBizException
     */
    protected void validateDormitoryInfo(
            Context ctx,
            PersonInfo personInfo,
            DormitoryInfo dormitory
    ) throws BOSException, EASBizException {
        Genders gender = personInfo.getGender();
        if (gender == null) {
            throw new BOSException("员工性别为空!");
        }
        String personInfoName = personInfo.getName();
        IDormitory iDormitory = DormitoryFactory.getLocalInstance(ctx);
        // 查询房间信息
        String dormitoryName = dormitory.getName();
        DormitoryClassification roomClassification = dormitory.getRoomClassification();
        if (!DormitoryClassification.ROOM.equals(roomClassification)) {
            String classificationAlias = roomClassification.getAlias();
            throw new BOSException("房间[" + dormitoryName + "]房间归类为" + classificationAlias + "，不能入住!");
        }
        BasicItemStateEnum dormitoryInfoState = dormitory.getState();
        if (BasicItemStateEnum.DISABLE.equals(dormitoryInfoState)) {
            throw new BOSException("房间[" + dormitoryName + "]未启用，不能入住!");
        }
        // 宿舍类型
        DormitoryTypeInfo dormitoryType = dormitory.getDormitoryType();
        Genders roomGender = dormitoryType.getGender();
        if (roomGender != null && gender.getValue() != roomGender.getValue()) {
            String dormitoryTypeName = dormitoryType.getName();
            throw new BOSException("房间[" + dormitoryName + "]宿舍类型为" + dormitoryTypeName + "，与人员[" + personInfoName + "]的性别不符!");
        }
    }

    /**
     * 根据入住日期和退宿日期算出入住信息中每个房间已住人数
     *
     * @param ctx
     * @param checkInDate  入住日期
     * @param checkoutDate 退宿日期
     * @param roomId       房间id
     * @param personType   人员类型
     * @return
     * @throws BOSException
     */
    protected int getCheckInInfoByOccupants(
            Context ctx,
            Date checkInDate,
            Date checkoutDate,
            String roomId,
            PersonDormitoryTypeInfo personType
    ) throws BOSException {
        IOccupants iOccupants = OccupantsFactory.getLocalInstance(ctx);
        FilterInfo filterInfo = new FilterInfo();
        FilterItemCollection filterItems = filterInfo.getFilterItems();
        // 房间
        filterItems.add(new FilterItemInfo("Dormitory", roomId));
        // 申请入住日期在入住日期和退宿日期之间
        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("PersonDormitoryType.id");
        sic.add("PersonDormitoryType.name");
        EntityViewInfo viewInfo = EntityViewInfo.getInstance(filterInfo, sic, null);
        OccupantsCollection occupantsCollection = iOccupants.getOccupantsCollection(viewInfo);
        String personTypeId = personType.getId().toString();
        String personTypeName = personType.getName();
        // 已住人数
        int dormCheckInCount = 0;
        String personDormitoryTypeId = null;
        for (int i = 0; i < occupantsCollection.size(); i++) {
            OccupantsInfo occupantsInfo = occupantsCollection.get(i);
            // 人员宿舍分类
            PersonDormitoryTypeInfo personDormitoryType = occupantsInfo.getPersonDormitoryType();
            personDormitoryTypeId = personDormitoryType.getId().toString();
            String personDormitoryTypeName = personDormitoryType.getName();
            if (!personTypeId.equals(personDormitoryTypeId)) {
                throw new BOSException("人员类别[" + personTypeName + "]与宿舍类型[" + personDormitoryTypeName + "]不符，不能入住！");
            }
            dormCheckInCount++;
        }
        return dormCheckInCount;
    }

    /**
     * 换宿单不能对有退宿单的入住信息进行换宿
     *
     * @param info
     */
    public void ValidateSwapWithCheckout(RoomChangeApplicationInfo info) throws ShrWebBizException, BOSException, EASBizException {
        logger.error("ValidateSwapWithCheckout---");
        RoomChangeApplicationEntryCollection entrys = info.getEntrys();
        ICheckoutApplicationEntry iCheckoutApplicationEntry = CheckoutApplicationEntryFactory.getLocalInstance(ctx);
        IPerson iPerson = PersonFactory.getLocalInstance(ctx);
        for (int i = 0; i < entrys.size(); i++) {
            RoomChangeApplicationEntryInfo entryInfo = entrys.get(i);
            OccupantsInfo oldOccupants = entryInfo.getOldOccupants();
            String personId = entryInfo.getPerson().getId().toString();
            FilterInfo filterInfo = new FilterInfo();
            FilterItemCollection filterItems = filterInfo.getFilterItems();
            filterItems.add(new FilterItemInfo("occupants.id", oldOccupants.getId()));
            filterItems.add(new FilterItemInfo("person.id", personId));
            filterItems.add(new FilterItemInfo("parent.billState", "0", CompareType.NOTEQUALS));
            EntityViewInfo entityViewInfo = EntityViewInfo.getInstance(filterInfo, null, null);
            CheckoutApplicationEntryCollection checkoutApplicationEntryCollection =
                    iCheckoutApplicationEntry.getCheckoutApplicationEntryCollection(entityViewInfo);
            if (checkoutApplicationEntryCollection.size() > 0) {
                PersonInfo personInfo = iPerson.getPersonInfo(new ObjectUuidPK(personId));
                throw new ShrWebBizException(personInfo.getName() + "存在退宿单，不能进行换宿！！");
            }
        }
    }

    /**
     * 校验原入住人员信息 和 新入住人员信息
     *
     * @param info
     */
    public void verifyOccupants(RoomChangeApplicationInfo info) throws ShrWebBizException {
        logger.error("verifyOccupants---");
        RoomChangeApplicationEntryCollection entrys = info.getEntrys();
        for (int i = 0; i < entrys.size(); i++) {
            RoomChangeApplicationEntryInfo entryInfo = entrys.get(i);
            if (entryInfo.getCurrentRoom().getId().equals(entryInfo.getAdjustRoom().getId())) {
                throw new ShrWebBizException("同一个房间不允许换宿！！");
            }
        }
    }

    /**
     * 换宿单不能存在同员工日期交叉的数据
     *
     * @param info
     * @throws BOSException
     * @throws ShrWebBizException
     * @throws EASBizException
     */
    public void verifyCheckNoDateOverlap(RoomChangeApplicationInfo info) throws BOSException, ShrWebBizException, EASBizException {
        logger.error("verifyCheckNoDateOverlap---");
        IRoomChangeApplicationEntry ientry = RoomChangeApplicationEntryFactory.getLocalInstance(ctx);
        RoomChangeApplicationEntryCollection entrys = info.getEntrys();
        List<RoomChangeOrderUtil> roomChangeOrders = new ArrayList<>();
        IPerson iPerson = PersonFactory.getLocalInstance(ctx);
        IOccupants iOccupants = OccupantsFactory.getLocalInstance(ctx);
        for (int i = 0; i < entrys.size(); i++) {
            // 保存单据的数据
            RoomChangeApplicationEntryInfo entryInfo = entrys.get(i);
            // OccupantsInfo oldOccupants = entryInfo.getOldOccupants();
            OccupantsInfo oldOccupants = iOccupants.getOccupantsInfo(new ObjectUuidPK(entryInfo.getOldOccupants().getId()));
            PersonInfo person = oldOccupants.getPerson();
            // 查询历史的数据
            RoomChangeApplicationEntryCollection roomChangeApplicationEntryCollection =
                    ientry.getRoomChangeApplicationEntryCollection("select * ,person.name where person.id='" + person.getId() + "'");
            roomChangeOrders.add(new RoomChangeOrderUtil(entryInfo.getPerson().getId().toString(), entryInfo.getCheckInDate(), entryInfo.getCheckoutDate()));
            logger.error("verifyCheckNoDateOverlap-" + entryInfo.getPerson().getId().toString() + "---" + entryInfo.getCheckInDate().getTime() + "----" + entryInfo.getCheckoutDate().getTime());
            for (int j = 0; j < roomChangeApplicationEntryCollection.size(); j++) {
                RoomChangeApplicationEntryInfo entry = roomChangeApplicationEntryCollection.get(j);
                roomChangeOrders.add(new RoomChangeOrderUtil(entry.getPerson().getId().toString(), entry.getCheckInDate(), entry.getCheckoutDate()));
                // logger.error("verifyCheckNoDateOverlap-" + entry.getPerson().getId().toString() + "---" + entry.getCheckInDate().getTime() + "----" + entry.getCheckoutDate().getTime());
            }
        }
        logger.error("verifyCheckNoDateOverlap--roomChangeOrders.size()--" + roomChangeOrders.size());
        logger.error("verifyCheckNoDateOverlap--roomChangeOrders---" + roomChangeOrders);
        RoomChangeOrderUtil result = checkNoDateOverlap(roomChangeOrders);
        logger.error("verifyCheckNoDateOverlap--result-" + result);
        if (result != null) {
            PersonInfo personInfo = iPerson.getPersonInfo(new ObjectUuidPK(result.getEmployeeId()));
            throw new ShrWebBizException(personInfo.getName() + "换宿单存在日期交叉的数据。");
        }
    }

    /**
     * 检查换宿单列表中是否存在同员工日期交叉的数据
     *
     * @param roomChangeOrders 换宿单列表
     * @return true 如果不存在日期交叉数据，false 如果存在
     */
    public static RoomChangeOrderUtil checkNoDateOverlap(List<RoomChangeOrderUtil> roomChangeOrders) {
        for (int i = 0; i < roomChangeOrders.size(); i++) {
            RoomChangeOrderUtil order1 = roomChangeOrders.get(i);
            for (int j = i + 1; j < roomChangeOrders.size(); j++) {
                RoomChangeOrderUtil order2 = roomChangeOrders.get(j);
                if (order1.getEmployeeId() == order2.getEmployeeId()) {
                    Calendar cal1Start = Calendar.getInstance();
                    cal1Start.setTime(order1.getStartDate());
                    Calendar cal1End = Calendar.getInstance();
                    cal1End.setTime(order1.getEndDate());
                    Calendar cal2Start = Calendar.getInstance();
                    cal2Start.setTime(order2.getStartDate());
                    Calendar cal2End = Calendar.getInstance();
                    cal2End.setTime(order2.getEndDate());
                    if (cal1Start.before(cal2End) && cal1End.after(cal2Start)) {
                        return order1;
                    }
                }
            }
        }
        return null;
    }

    /**
     * 校验原入住人员信息退宿日期是否小于当前时间
     */
    public void verifyCheckOutDateBeforeCurrent(RoomChangeApplicationInfo info) throws Exception {
        logger.error("verifyCheckOutDateBeforeCurrent---");
        RoomChangeApplicationEntryCollection entrys = info.getEntrys();
        IOccupants iOccupants = OccupantsFactory.getLocalInstance(ctx);
        for (int i = 0; i < entrys.size(); i++) {
            RoomChangeApplicationEntryInfo roomChangeApplicationEntryInfo = entrys.get(i);
            OccupantsInfo oldOccupants = iOccupants.getOccupantsInfo(new ObjectUuidPK(roomChangeApplicationEntryInfo.getOldOccupants().getId()));
            Date checkOutDate = oldOccupants.getCheckOutDate();
            logger.error("checkOutDate---" + checkOutDate);
            long checkOutTime = checkOutDate.getTime();
            long dateTime = new Date().getTime();
            // 校验原入住人员信息退宿日期是否小于当前时间
            if (checkOutTime < dateTime) {
                throw new ShrWebBizException("不可对历史入住人员信息进行换宿！！");
            }
        }
    }
}
