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

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
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.bos.util.BOSUuid;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.custom.performancenew.*;
import com.kingdee.eas.framework.CoreBaseCollection;
import com.kingdee.eas.hr.ats.AtsUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.Map;

public class ExamineGradePersonControllerBean extends AbstractExamineGradePersonControllerBean {
    private static Logger logger = Logger.getLogger(ExamineGradePersonControllerBean.class);

    /**
     * 保存
     *
     * @param ctx
     * @param model
     * @return
     * @throws BOSException
     * @throws EASBizException
     */
    @Override
    protected IObjectPK _save(Context ctx, IObjectValue model) throws BOSException, EASBizException {
        ExamineGradePersonInfo info = (ExamineGradePersonInfo) model;
        //校验
        verify(ctx, info);
        ExamineGradePersonEntryCollection entrys = info.getEntrys();
        //历史数据
        Map<String, PersonRelationOrgInfo> oldScoreOrgMap = new HashMap<String, PersonRelationOrgInfo>();
        if (info.getId() != null) {
            String id = info.getId().toString();
            ExamineGradePersonInfo oldInfo = getExamineGradePersonInfo(ctx, new ObjectUuidPK(BOSUuid.read(id)));
            ExamineGradePersonEntryCollection oldEntrys = oldInfo.getEntrys();
            for (int i = 0; i < oldEntrys.size(); i++) {
                ExamineGradePersonEntryInfo oldEntryInfo = oldEntrys.get(i);
                String adminId = oldEntryInfo.getAdminOrg().getId().toString();
                if (!oldScoreOrgMap.containsKey(adminId)) {
                    PersonRelationOrgInfo performanceScoreOrg = oldEntryInfo.getPerformanceScoreOrg();
                    oldScoreOrgMap.put(adminId, performanceScoreOrg);
                }
            }
        }
        for (int i = 0; !oldScoreOrgMap.isEmpty() && entrys != null && i < entrys.size(); i++) {
            ExamineGradePersonEntryInfo entryInfo = entrys.get(i);
            String adminId = entryInfo.getAdminOrg().getId().toString();
            PersonRelationOrgInfo personRelationOrgInfo = oldScoreOrgMap.get(adminId);
            entryInfo.setPerformanceScoreOrg(personRelationOrgInfo);
        }
        return super._save(ctx, model);
    }

    /**
     * 校验
     *
     * @param ctx
     * @param model
     * @throws BOSException
     * @throws EASBizException
     */
    protected void verify(Context ctx, ExamineGradePersonInfo model) throws BOSException, EASBizException {
        ExamineGradePersonInfo info = model;
        int year = info.getYear();//年份
        periodTypeEnum periodType = info.getPeriodType();
        String periodTypeValue = periodType.getValue();//周期类型
        int quarter = info.getQuarter();//季度
        String id = null;
        if (info.getId() != null) {
            id = info.getId().toString();
        }
        FilterInfo filterInfo = new FilterInfo();
        FilterItemCollection filterItems = filterInfo.getFilterItems();
        filterItems.add(new FilterItemInfo("year", year));
        filterItems.add(new FilterItemInfo("periodType", periodTypeValue));
        filterItems.add(new FilterItemInfo("quarter", quarter));
        filterItems.add(new FilterItemInfo("id", id, CompareType.NOTEQUALS));
        if (_exists(ctx, filterInfo)) {
            String errorMsg = null;
            if (periodTypeValue.equals("1")) {
                errorMsg = year + "年 年度绩效数据已经存在,请勿重复创建";
            } else {
                errorMsg = year + "年 " + quarter + "季度绩效数据已经存在,请勿重复创建";
            }
            logger.error(errorMsg);
            throw new BOSException(errorMsg);
        }
    }


    /**
     * 锁定周期
     *
     * @param ctx
     * @param billId 单据id
     * @throws BOSException
     */
    @Override
    protected void _periodLock(Context ctx, String billId) throws BOSException, EASBizException {
        if (StringUtils.isEmpty(billId)) {
            throw new BOSException("单据id不能为空！");
        }
        ExamineGradePersonInfo info = getExamineGradePersonInfo(ctx, new ObjectUuidPK(BOSUuid.read(billId)));
        if (periodStatusEnum.periodLock.equals(info.getPeriodStatus())) {
            throw new BOSException("周期已锁定，请勿重复操作！");
        }
        SelectorItemCollection sic = new SelectorItemCollection();
        sic.add("periodStatus");
        info.setPeriodStatus(periodStatusEnum.periodLock);
        updatePartial(ctx, info, sic);
    }

    /**
     * 解除周期
     *
     * @param ctx
     * @param billId 单据id
     * @throws BOSException
     */
    @Override
    protected void _periodUnlock(Context ctx, String billId) throws BOSException, EASBizException {
        if (StringUtils.isEmpty(billId)) {
            throw new BOSException("单据id不能为空！");
        }
        ExamineGradePersonInfo info = getExamineGradePersonInfo(ctx, new ObjectUuidPK(BOSUuid.read(billId)));
        if (periodStatusEnum.periodRelieve.equals(info.getPeriodStatus())) {
            throw new BOSException("周期已解锁，请勿重复操作！");
        }
        SelectorItemCollection sic = new SelectorItemCollection();
        sic.add("periodStatus");
        info.setPeriodStatus(periodStatusEnum.periodRelieve);
        updatePartial(ctx, info, sic);
    }

    /**
     * 开始排序
     *
     * @param ctx
     * @param billId 单据id
     * @throws BOSException
     */
    @Override
    protected void _startOrder(Context ctx, String billId) throws BOSException {
        if (StringUtils.isEmpty(billId)) {
            throw new BOSException("单据id不能为空！");
        }
        try {
            IExamineGradePersonEntry iExamineGradePersonEntry = ExamineGradePersonEntryFactory.getLocalInstance(ctx);
            ExamineGradePersonEntryCollection entrys = iExamineGradePersonEntry.getExamineGradePersonEntryCollection("where parent='" + billId + "'");
            CoreBaseCollection collection = new CoreBaseCollection();
            for (int i = 0; i < entrys.size(); i++) {
                ExamineGradePersonEntryInfo entryInfo = entrys.get(i);
                if (entryInfo.getOrderStatuc() != orderStatucEnum.closeOrder) {
                    continue;
                } else {
                    entryInfo.setOrderStatuc(orderStatucEnum.startOrder);
                    collection.add(entryInfo);
                }

            }
            if (collection.size() > 0) {
                iExamineGradePersonEntry.updateBatchData(collection);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 反启用排序
     *
     * @param ctx
     * @throws BOSException
     */
    @Override
    protected void _closeOrder(Context ctx, String entryId) throws BOSException {
        if (StringUtils.isEmpty(entryId)) {
            throw new BOSException("分录ID不能为空！");
        }
        try {
            SelectorItemCollection sic = new SelectorItemCollection();
            sic.add("orderStatuc");
            FilterInfo filterInfo = new FilterInfo();
            filterInfo.getFilterItems().add(new FilterItemInfo("id", AtsUtil.toSet(entryId), CompareType.INCLUDE));
            IExamineGradePersonEntry iExamineGradePersonEntry = ExamineGradePersonEntryFactory.getLocalInstance(ctx);
            EntityViewInfo entityViewInfo = EntityViewInfo.getInstance(filterInfo, null, null);
            ExamineGradePersonEntryCollection examineGradePersonEntryCollection = iExamineGradePersonEntry.getExamineGradePersonEntryCollection(entityViewInfo);
            if (examineGradePersonEntryCollection.size() > 0) {
                for (int i = 0; i < examineGradePersonEntryCollection.size(); i++) {
                    ExamineGradePersonEntryInfo examineGradePersonEntryInfo = examineGradePersonEntryCollection.get(i);
                    examineGradePersonEntryInfo.setOrderStatuc(orderStatucEnum.closeOrder);
                    iExamineGradePersonEntry.updatePartial(examineGradePersonEntryInfo, sic);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}