package com.kingdee.eas.custom.attendanceexception.handler;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
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.eas.basedata.org.AdminOrgUnitFactory;
import com.kingdee.eas.basedata.org.AdminOrgUnitInfo;
import com.kingdee.eas.basedata.org.IAdminOrgUnit;
import com.kingdee.eas.basedata.person.PersonInfo;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.custom.attendanceexception.CenterLeaderRelationEntryCollection;
import com.kingdee.eas.custom.attendanceexception.CenterLeaderRelationEntryInfo;
import com.kingdee.eas.custom.attendanceexception.CenterLeaderRelationInfo;
import com.kingdee.eas.framework.CoreBaseInfo;
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.shr.base.syssetting.web.handler.EditHandler;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashSet;
import java.util.Set;

/**
 * @Description 中心负责人关系表表单Handler
 * @Date 2025/4/16 11:18
 * @Created by Heyuan
 */
public class CenterLeaderRelationEditHandler extends EditHandler {
    private static Logger logger = Logger.getLogger(CenterLeaderRelationEditHandler.class);
    private Context ctx = SHRContext.getInstance().getContext();
    //一级组织类型id
    private final String FIRSTLEVELORGID = "00000000-0000-0000-0000-00000000000362824988";

    @Override
    protected void verifyModel(
            HttpServletRequest request,
            HttpServletResponse response,
            CoreBaseInfo model
    ) throws SHRWebException {
        try {
            CenterLeaderRelationInfo info = (CenterLeaderRelationInfo) model;
            AdminOrgUnitInfo department = info.getDepartment();
            if (department == null) {
                throw new ShrWebBizException("组织不能为空!");
            }
            String orgId = department.getId().toString();
            //1.校验组织是否为一级部门
            IAdminOrgUnit iAdminOrgUnit = AdminOrgUnitFactory.getLocalInstance(ctx);
            department = iAdminOrgUnit.getAdminOrgUnitInfo(new ObjectUuidPK(orgId));
            String unitLayerTypeId = department.getUnitLayerType().getId().toString();
            if (!FIRSTLEVELORGID.equals(unitLayerTypeId)) {
                String orgName = department.getName();
                throw new ShrWebBizException(orgName + "不是一级组织，不能维护负责人！");
            }
            //2.校验是否存在重复组织数据
            FilterInfo filterInfo = new FilterInfo();
            FilterItemCollection filterItems = filterInfo.getFilterItems();
            filterItems.add(new FilterItemInfo("department", department.getId()));
            if (info.getId() != null) {
                filterItems.add(new FilterItemInfo("id", info.getId(), CompareType.NOTEQUALS));
            }
            boolean exists = this.getBizInterface(request).exists(filterInfo);
            if (exists) {
                String orgName = department.getName();
                throw new ShrWebBizException("组织[" + orgName + "]数据已经存在，请勿重复添加！");
            }
            //3.校验分录人员数据
            CenterLeaderRelationEntryCollection entrys = info.getEntry();
            if (entrys.size() <= 0) {
                throw new ShrWebBizException("分录不能为空!");
            } else {
                StringBuilder numbers = new StringBuilder();
                StringBuilder names = new StringBuilder();
                Set<String> personIds = new HashSet<>();
                for (int i = entrys.size() - 1; i >= 0; i--) {
                    CenterLeaderRelationEntryInfo entryInfo = entrys.get(i);
                    PersonInfo person = entryInfo.getPerson();
                    String personId = person.getId().toString();
                    if (personIds.contains(personId)) {
                        //去除重复人员
                        entrys.remove(entryInfo);
                        continue;
                    }
                    personIds.add(personId);
                    String number = person.getNumber();
                    numbers.append(number).append(",");
                    String name = person.getName();
                    names.append(name).append(",");
                }
                if (numbers.length() > 0) {
                    numbers.deleteCharAt(numbers.lastIndexOf(","));
                }
                info.setPersonNumbers(numbers.toString());
                if (names.length() > 0) {
                    names.deleteCharAt(names.lastIndexOf(","));
                }
                info.setPersonNames(names.toString());
            }
        } catch (BOSException e) {
            logger.error(e);
            throw new ShrWebBizException(e);
        } catch (EASBizException e) {
            logger.error(e);
            throw new ShrWebBizException(e);
        }
    }
}
