package com.kingdee.eas.custom.compensation.basedata.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.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.IPosition;
import com.kingdee.eas.basedata.org.PositionFactory;
import com.kingdee.eas.basedata.org.PositionInfo;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.custom.compensation.basedata.PositionSalaryStandardInfo;
import org.apache.log4j.Logger;

/**
 * 岗位薪酬标准 ControllerBean，保存前校验同岗位不可重复创建。
 */
public class PositionSalaryStandardControllerBean extends AbstractPositionSalaryStandardControllerBean {
    private static Logger logger = Logger.getLogger(PositionSalaryStandardControllerBean.class);

    /**
     * 保存前校验：同一岗位只能有一条薪酬标准记录。
     * 校验通过后将 Name 赋值为岗位编号+岗位名称。
     */
    protected IObjectPK _save(Context ctx, IObjectValue model) throws BOSException, EASBizException {
        PositionSalaryStandardInfo info = (PositionSalaryStandardInfo) model;

        // 岗位不能为空
        PositionInfo positionInfo = info.getPosition();
        if (positionInfo == null) {
            throw new BOSException("职位数据不能为空!");
        }

        // 重新查询岗位完整信息
        String positionId = positionInfo.getId().toString();
        IPosition iPosition = PositionFactory.getLocalInstance(ctx);
        positionInfo = iPosition.getPositionInfo(new ObjectUuidPK(positionId));

        // 查询是否已存在该岗位的薪酬标准记录
        FilterInfo filterInfo = new FilterInfo();
        FilterItemCollection filterItems = filterInfo.getFilterItems();
        filterItems.add(new FilterItemInfo("position.id", positionInfo.getId()));
        // 编辑模式排除自身
        if (info.getId() != null) {
            filterItems.add(new FilterItemInfo("id", info.getId(), CompareType.NOTEQUALS));
        }
        if (exists(ctx, filterInfo)) {
            throw new BOSException("职位[" + positionInfo.getName() + "] 职位编码[" + positionInfo.getNumber() + "]的岗位薪酬标准数据已经存在,不可重复创建!");
        }

        // 将名称赋值为岗位编码+名称，便于列表识别
        info.setName(positionInfo.getNumber() + "##" + positionInfo.getName());
        return super._save(ctx, info);
    }
}
