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

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.bos.metadata.entity.EntityViewInfo;
import com.kingdee.bos.metadata.entity.FilterInfo;
import com.kingdee.bos.metadata.entity.FilterItemCollection;
import com.kingdee.bos.metadata.entity.FilterItemInfo;
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.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.occupants.IOccupants;
import com.kingdee.eas.custom.dormitorysystem.occupants.OccupantsFactory;
import com.kingdee.eas.custom.dormitorysystem.occupants.OccupantsInfo;
import com.kingdee.eas.framework.CoreBaseInfo;
import com.kingdee.eas.hr.base.HRBillBaseInfo;
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 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);
        }
    }

    /**
     * 换宿单不能对有退宿单的入住信息进行换宿
     *
     * @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("不可对历史入住人员信息进行换宿！！");
            }
        }
    }
}
