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

import com.kingdee.bos.dao.IObjectPK;
import com.kingdee.bos.dao.IObjectValue;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.bos.metadata.entity.*;
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.synctask.utils.HRTimeWebUtils;
import com.kingdee.eas.hr.emp.IPersonPosition;
import com.kingdee.eas.hr.emp.PersonPositionCollection;
import com.kingdee.eas.hr.emp.PersonPositionFactory;
import com.kingdee.eas.hr.emp.PersonPositionInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import com.kingdee.bos.*;
import com.kingdee.eas.custom.attendanceexception.CenterLeaderRelationCollection;

import java.lang.String;
import java.util.*;

import com.kingdee.eas.custom.attendanceexception.CenterLeaderRelationInfo;

public class CenterLeaderRelationControllerBean extends AbstractCenterLeaderRelationControllerBean {
    private static Logger logger = Logger.getLogger(CenterLeaderRelationControllerBean.class);
    //一级组织类型id
    //private final String FIRSTLEVELORGID = "00000000-0000-0000-0000-00000000000362824988";

    @Override
    protected IObjectPK _save(Context ctx, IObjectValue model) throws BOSException, EASBizException {
        CenterLeaderRelationInfo info = (CenterLeaderRelationInfo) model;
        AdminOrgUnitInfo department = info.getDepartment();
        if (department == null) {
            throw new BOSException("组织不能为空!");
        }
        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 BOSException(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 = exists(ctx, filterInfo);
        if (exists) {
            String orgName = department.getName();
            throw new BOSException("组织[" + orgName + "]数据已经存在，请勿重复添加！");
        }
        //3.校验分录人员数据
        CenterLeaderRelationEntryCollection entrys = info.getEntry();
        if (entrys.size() <= 0) {
            throw new BOSException("分录不能为空!");
        } else {
            Set<String> personIds = new HashSet<String>();
            List<String> numbers = new ArrayList<String>();
            List<String> names = new ArrayList<String>();
            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);
                numbers.add(person.getNumber());
                names.add(person.getName());
            }
            Collections.reverse(numbers);
            Collections.reverse(names);
            info.setPersonNumbers(listToString(numbers));
            info.setPersonNames(listToString(names));
        }
        return super._save(ctx, model);
    }

    /**
     * 获取中心负责人
     *
     * @param ctx
     * @return
     * @throws BOSException
     */
    @Override
    protected Map _getLeaders(Context ctx) throws BOSException {
        super._getLeaders(ctx);
        Map<String, String> orgLeadersMap = new HashMap();
        //中心负责人关系表
        CenterLeaderRelationCollection relationCol = getCenterLeaderRelationCollection(ctx, "select id,department.longNumber,personNumbers");
        for (int i = 0; i < relationCol.size(); i++) {
            CenterLeaderRelationInfo info = relationCol.get(i);
            //中心
            AdminOrgUnitInfo department = info.getDepartment();
            //员工工号s
            String personNumbers = info.getPersonNumbers();
            if (department != null && StringUtils.isNotBlank(personNumbers)) {
                orgLeadersMap.put(department.getLongNumber(), personNumbers);
            } else {
                String id = info.getId().toString();
                logger.error("CenterLeaderRelationInfo exist department is null or personNumbers is null, id=" + id);
            }
        }
        if (logger.isInfoEnabled()) {
            logger.info("CenterLeaderRelationControllerBean getLeaders: " + orgLeadersMap);
        }
        return orgLeadersMap;
    }

    /**
     * 获取组织负责人
     *
     * @param ctx
     * @return
     * @throws BOSException
     */
    protected Map<String, Set<String>> getOrgLeaders(Context ctx) throws BOSException {
        Map<String, Set<String>> orgLeadersMap = new HashMap<String, Set<String>>();
        //今天
        String curentShortStringDate = HRTimeWebUtils.getCurentShortStringDate();
        IPersonPosition iPersonPosition = PersonPositionFactory.getLocalInstance(ctx);
        FilterInfo filterInfo = new FilterInfo();
        FilterItemCollection filterItems = filterInfo.getFilterItems();
        //组织层级为一级组织
        filterItems.add(new FilterItemInfo("personDep.unitLayerType", "00000000-0000-0000-0000-00000000000362824988"));
        //组织状态为启用
        filterItems.add(new FilterItemInfo("personDep.isSealUp", "0"));
        //职位为负责人职位
        filterItems.add(new FilterItemInfo("primaryPosition.isRespPosition", "1"));
        //职位状态为启用
        filterItems.add(new FilterItemInfo("primaryPosition.deletedStatus", "1"));
        //结束日期大于等于今天
        filterItems.add(new FilterItemInfo("LEFFDT", curentShortStringDate, CompareType.GREATER_EQUALS));
        //结束日期大于等于今天
        filterItems.add(new FilterItemInfo("endDateTime", curentShortStringDate, CompareType.GREATER_EQUALS));
        SelectorItemCollection sic = new SelectorItemCollection();
        sic.add("person.number");
        sic.add("personDep.number");
        EntityViewInfo viewInfo = EntityViewInfo.getInstance(filterInfo, sic, null);
        PersonPositionCollection personPositionCollection = iPersonPosition.getPersonPositionCollection(viewInfo);
        for (int i = 0; i < personPositionCollection.size(); i++) {
            PersonPositionInfo personPositionInfo = personPositionCollection.get(i);
            AdminOrgUnitInfo personDep = personPositionInfo.getPersonDep();
            String orgNumber = personDep.getNumber();
            PersonInfo person = personPositionInfo.getPerson();
            String personNumber = person.getNumber();
            if (orgLeadersMap.containsKey(orgNumber)) {
                orgLeadersMap.get(orgNumber).add(personNumber);
            } else {
                Set<String> set = new HashSet<String>();
                set.add(personNumber);
                orgLeadersMap.put(orgNumber, set);
            }
        }
        if (logger.isInfoEnabled()) {
            logger.info("orgLeadersMap = " + orgLeadersMap);
        }
        return orgLeadersMap;
    }

    protected String listToString(List<String> list) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; list != null && i < list.size(); i++) {
            sb.append(list.get(i)).append(",");
        }
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.lastIndexOf(","));
        }
        return sb.toString();
    }
}