package com.kingdee.eas.custom.projectbonus.web.service;

import com.kingdee.bos.Context;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.bos.metadata.entity.*;
import com.kingdee.eas.basedata.person.PersonInfo;
import com.kingdee.eas.custom.projectbonus.*;
import com.kingdee.eas.custom.projectbonus.bizEnum.BusDepProjectStateEnum;
import com.kingdee.eas.custom.projectbonus.bizEnum.CycleStateEnum;
import com.kingdee.eas.framework.CoreBaseInfo;
import com.kingdee.eas.util.app.ContextUtil;
import com.kingdee.shr.base.syssetting.app.io.fileImport.BaseColumnInfo;
import com.kingdee.shr.base.syssetting.app.io.fileImport.BaseRowInfo;
import com.kingdee.shr.base.syssetting.app.io.fileImport.ImportException;
import com.kingdee.util.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;


/**
 * @Description 分配人员明细列表导入模板(负责人)_带数据更新导入
 * @Date 2024/5/7 21:28
 * @Created by Heyuan
 */
public class PrincipalDetailImportServiceV2 extends PrincipalDetailImportService {

    /**
     * 模板下载时携带数据
     *
     * @param columnInfoMap
     * @param wb
     * @param sheet
     */
    @Override
    public void completeGenerateExcel(Map<String, BaseColumnInfo> columnInfoMap,
                                      XSSFWorkbook wb,
                                      XSSFSheet sheet) {
        Context ctx = this.getContext();
        String busDepId = this.getCustomParam("parentId");
        if (StringUtils.isEmpty(busDepId)) {
            throw new RuntimeException("生成事业部项目带数据导入模板报错,事业部项目id不能为空!");
        }
        int beginRow = 4;//数据生成开始行数
        //隐藏第一列
        //sheet.setColumnHidden(0, true);
        try {
            IBonusCycleBusDepProject iBonusCycleBusDepProject = BonusCycleBusDepProjectFactory.getLocalInstance(ctx);
            SelectorItemCollection sic = new SelectorItemCollection();
            sic.add("AssPersonnelDetail.*");
            sic.add("AssPersonnelDetail.person.name");
            sic.add("AssPersonnelDetail.person.number");
            sic.add("*");
            sic.add("parent.*");
            sic.add("busDep.name");
            sic.add("busDep.number");
            sic.add("project.name");
            sic.add("project.number");
            sic.add("secondcenter.name");
            sic.add("secondcenter.number");
            //事业部项目
            BonusCycleBusDepProjectInfo depProjectInfo = iBonusCycleBusDepProject.getBonusCycleBusDepProjectInfo(new ObjectUuidPK(busDepId), sic);
            BusDepProjectStateEnum state = depProjectInfo.getState();
            if (!BusDepProjectStateEnum.ENABLE.equals(state) && !BusDepProjectStateEnum.SUBMITCALCULATED.equals(state)) {
                throw new RuntimeException("事业部项目非启用或待复核状态，不允许执行导入操作！");
            }
            PersonInfo principal = depProjectInfo.getPrincipal();
            if (principal == null) {
                throw new RuntimeException("当前事业部项目负责人为空！");
            }
            String principalId = principal.getId().toString();
            //当前登录人
            PersonInfo personInfo = ContextUtil.getCurrentUserInfo(ctx).getPerson();
            String personId = personInfo.getId().toString();
            if (!personId.equals(principalId)) {
                throw new RuntimeException("当前操作人不是事业部项目负责人，不允许执行导入操作！");
            }
            Map<Integer, String> columnIndexMap = this.getColumnIndexFn(columnInfoMap);
            //周期
            BonusCycleInfo bonusCycleInfo = depProjectInfo.getParent();
            //分配人员明细
            BonusCycleBusDepProjectAssPersonnelDetailCollection personnelDetailCols = depProjectInfo.getAssPersonnelDetail();
            int fillColumnCount = columnInfoMap.size();
            for (int i = 0; i < personnelDetailCols.size(); i++) {
                Row row = sheet.createRow(i + beginRow);
                BonusCycleBusDepProjectAssPersonnelDetailInfo info = personnelDetailCols.get(i);
                for (int j = 0; j < fillColumnCount; ++j) {
                    Cell createCell = row.createCell(j);
                    String columnName = columnIndexMap.get(j);
                    String value = null;
                    CoreBaseInfo coreBase = null;
                    if (columnName.startsWith("BonusCycle.")) {
                        columnName = columnName.substring(columnName.indexOf(".") + 1);
                        coreBase = bonusCycleInfo;
                    } else if (columnName.startsWith("BonusCycleBusDepProject.")) {
                        columnName = columnName.substring(columnName.indexOf(".") + 1);
                        coreBase = depProjectInfo;
                    } else {
                        coreBase = info;
                    }
                    Object obj = coreBase.get(columnName);
                    if (obj != null) {
                        if (obj instanceof CoreBaseInfo) {
                            CoreBaseInfo coreBaseInfo = (CoreBaseInfo) coreBase.get(columnName);
                            value = coreBaseInfo.get("number") + "##" + coreBaseInfo.get("name");
                        } else if (obj instanceof BigDecimal) {
                            BigDecimal bigDecimal = (BigDecimal) obj;
                            if (this.moneyFields.contains(columnName)) {
                                value = bigDecimal.setScale(6, RoundingMode.HALF_UP).toPlainString();
                            } else {
                                value = bigDecimal.setScale(2, RoundingMode.HALF_UP).toPlainString();
                            }
                        } else {
                            value = obj.toString();
                        }
                    }
                    createCell.setCellValue(value);
                }
            }
        } catch (Exception e) {
            if (e.getMessage().contains("fetched too much rows")) {
                throw new ImportException("查询的数据量超出限制！请联系系统管理员修改配置，或者减少下载的数据量。");
            } else {
                e.printStackTrace();
                throw new ImportException(e.getMessage());
            }
        }
    }

    /**
     * 获取主键条件字符串
     *
     * @param row
     * @return
     */
    @Override
    protected String getPKSelectString(BaseRowInfo row) {
        List<BaseColumnInfo> keyColumnList = row.getKeyColumnInfo();
        for (int i = 0; i < keyColumnList.size(); ++i) {
            BaseColumnInfo keyColumn = keyColumnList.get(i);
            keyColumn.setCustomField(false);
        }
        return super.getPKSelectString(row);
    }

    /**
     * 校验对象
     *
     * @param coreBaseInfo
     * @throws ImportException
     */
    protected void verifyRowBiz(CoreBaseInfo coreBaseInfo) throws ImportException {
        BonusCycleBusDepProjectAssPersonnelDetailInfo info = (BonusCycleBusDepProjectAssPersonnelDetailInfo) coreBaseInfo;
        String id = info.getId().toString();
        SelectorItemCollection sic = new SelectorItemCollection();
        sic.add("parent.parent.state");//周期锁定状态
        sic.add("parent.state");//
        try {
            IBonusCycleBusDepProjectAssPersonnelDetail iBonusCycleBusDepProjectAssPersonnelDetail =
                    BonusCycleBusDepProjectAssPersonnelDetailFactory.getLocalInstance(this.getContext());
            BonusCycleBusDepProjectAssPersonnelDetailInfo oldInfo = iBonusCycleBusDepProjectAssPersonnelDetail.getBonusCycleBusDepProjectAssPersonnelDetailInfo(new ObjectUuidPK(id), sic);
            CycleStateEnum state = oldInfo.getParent().getParent().getState();
            if (CycleStateEnum.LOCK.equals(state)) {
                throw new RuntimeException("周期已锁定，不允许执行导入操作！");
            }
            BusDepProjectStateEnum busDepProjectState = oldInfo.getParent().getState();
            String alias = busDepProjectState.getAlias();
            if (!BusDepProjectStateEnum.ENABLE.equals(busDepProjectState)
                    && !BusDepProjectStateEnum.SUBMITCALCULATED.equals(busDepProjectState)) {
                throw new RuntimeException("事业部项目" + alias + "状态，不允许执行导入操作！");
            }
            info.setParent(oldInfo.getParent());
        } catch (Exception e) {
            e.printStackTrace();
            throw new ImportException(e.getMessage());
        }
    }


    /**
     * 提交数据
     *
     * @param coreBaseInfo
     * @throws ImportException
     */
    @Override
    protected void submitData(CoreBaseInfo coreBaseInfo) throws ImportException {
        try {
            IBonusCycleBusDepProjectAssPersonnelDetail iBonusCycleBusDepProjectAssPersonnelDetail =
                    BonusCycleBusDepProjectAssPersonnelDetailFactory.getLocalInstance(this.getContext());
            BonusCycleBusDepProjectAssPersonnelDetailInfo info = (BonusCycleBusDepProjectAssPersonnelDetailInfo) coreBaseInfo;
            String id = info.getId().toString();
            SelectorItemCollection sic = new SelectorItemCollection();
            sic.add("parent.state");
            BonusCycleBusDepProjectAssPersonnelDetailInfo oldInfo = iBonusCycleBusDepProjectAssPersonnelDetail.getBonusCycleBusDepProjectAssPersonnelDetailInfo(new ObjectUuidPK(id), sic);
            BusDepProjectStateEnum state = oldInfo.getParent().getState();
            //根据事业部状态获取更新列
            SelectorItemCollection updateSic = getUpdateSic(state);
            iBonusCycleBusDepProjectAssPersonnelDetail.updatePartial(coreBaseInfo, updateSic);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ImportException(e.getMessage());
        }
    }

    /**
     * 根据事业部状态获取更新列
     *
     * @param state
     * @return
     */
    protected SelectorItemCollection getUpdateSic(BusDepProjectStateEnum state) {
        SelectorItemCollection updateSic = new SelectorItemCollection();
        if (BusDepProjectStateEnum.ENABLE.equals(state)) {
            updateSic.add("functionCoefficient");//职能系数
            updateSic.add("energyInputCoeff");//精力投入系数
            updateSic.add("bonusStartingDate");//奖金期限起算日期
            updateSic.add("bonusDueDate");//奖金期限截止日期
        } else if (BusDepProjectStateEnum.SUBMITCALCULATED.equals(state)) {
            updateSic.add("opinionAmount");//征求意见金额
            updateSic.add("adjustmentdesc");//调整说明
        }
        return updateSic;
    }
}
