package com.kingdee.eas.custom.expandassess.hadler;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.bos.metadata.entity.EntityViewInfo;
import com.kingdee.bos.metadata.entity.FilterInfo;
import com.kingdee.bos.metadata.entity.FilterItemInfo;
import com.kingdee.bos.metadata.entity.SelectorItemCollection;
import com.kingdee.bos.util.BOSUuid;
import com.kingdee.eas.basedata.org.AdminOrgUnitInfo;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.custom.expandassess.*;
import com.kingdee.eas.custom.expandassess.app.ExpandStatusEunm;
import com.kingdee.eas.custom.expandassess.app.task.ExpandassessFacadeFactory;
import com.kingdee.eas.custom.expandassess.app.task.IExpandassessFacade;
import com.kingdee.eas.custom.expandassess.service.impl.ExpandAssessServiceImpl;
import com.kingdee.eas.custom.projectbonus.web.vo.*;
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.json.GridDataEntity;
import com.kingdee.shr.base.syssetting.web.json.JSONUtils;
import com.kingdee.util.StringUtils;
import org.springframework.ui.ModelMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author qingwu
 * @date 2024/5/16
 * @apiNote 拓展人员考核专员维护
 */
public class ExpandAssessZYDynamicListHandler extends DynamicListHandlerEx {
    ExpandAssessServiceImpl expandAssessService = new ExpandAssessServiceImpl();
    private Context ctx = SHRContext.getInstance().getContext();

    /**
     * 校验周期是否锁定
     *
     * @param request
     * @param response
     * @param modelMap
     * @throws ShrWebBizException
     * @throws BOSException
     */
    public void verifyeriodIsLockAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws SHRWebException, BOSException {
        String billId = request.getParameter("billId");
        if (StringUtils.isEmpty(billId)) {
            throw new ShrWebBizException("拓展人员考核周期ID不可为空！");
        }
        JSONUtils.SUCCESS(expandAssessService.verifyeriodLockOrNot(ctx, billId));
    }

    /**
     * 催办
     *
     * @param request
     * @param response
     * @param modelMap
     */
    public void prassAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws ShrWebBizException {
        String billID = request.getParameter("billId");
        try {
            IExpandassessFacade iExpandassessFacade = ExpandassessFacadeFactory.getLocalInstance(ctx);
            JSONUtils.SUCCESS(iExpandassessFacade.warnPrincipal(billID));
        } catch (Exception e) {
            e.printStackTrace();
            throw new ShrWebBizException(e);
        }
    }

    /**
     * 撤回至负责人
     *
     * @param request
     * @param response
     * @param modelMap
     * @throws ShrWebBizException
     */
    public void withdrawAction(HttpServletRequest request,
                               HttpServletResponse response,
                               ModelMap modelMap) throws ShrWebBizException {
        //获取删除ID
        String idArray = request.getParameter("idArray");
        if (StringUtils.isEmpty(idArray)) {
            throw new ShrWebBizException("勾选数据无效，请联系管理员！");
        }
        try {
            expandAssessService.updateAsseStatusAll(ctx, idArray, ExpandStatusEunm.PRINCIPALSUBMIT, ExpandStatusEunm.ASSESUBMINT, "请勾选状态为负责人已提交的数据,否则无法撤回");
        } catch (BOSException e) {
            e.printStackTrace();
            throw new ShrWebBizException(e);
        } catch (EASBizException e) {
            throw new ShrWebBizException(e);
        }
    }

    /**
     * 动态表单保存
     *
     * @param request
     * @param response
     * @param modelMap
     * @throws SHRWebException
     * @returnA
     */
    public void saveDynGridAction(HttpServletRequest request,
                                  HttpServletResponse response,
                                  ModelMap modelMap) throws SHRWebException {
        Context ctx = SHRContext.getInstance().getContext();
        try {
            List<Map<String, String>> dataList = (List) JSONUtils.convertJsonToObject(request.getParameter("modi"), List.class);
            IExpandAssessEntry iExpandAssessEntry = ExpandAssessEntryFactory.getLocalInstance(ctx);
            //待更新数据集合
            Map<String, ExpandAssessEntryInfo> updEntryCols = new HashMap<String, ExpandAssessEntryInfo>();
            //待更新字段
            Map<String, SelectorItemCollection> updSics = new HashMap<String, SelectorItemCollection>();
            int succeedNum = 0;
            int errorNum = 0;
            for (int i = 0; i < dataList.size(); i++) {
                Map<String, String> map = dataList.get(i);
                ExpandAssessEntryInfo entryInfo;
                SelectorItemCollection updSic;
                String fid = map.get("fid");
                //字段名称
                String colName = map.get("column");
                //值类型
                String type = map.get("type");
                //修改值
                Object value = map.get("value");
                ExpandAssessEntryInfo expandAssessEntryInfo = iExpandAssessEntry.getExpandAssessEntryInfo(new ObjectUuidPK(fid));
                if (!colName.equals("checkrate") && !colName.equals("remark")) {
                    if (expandAssessEntryInfo.getAsseStatus() != ExpandStatusEunm.UNSTART) {
                        errorNum++;
                        continue;
                    }
                }
                //保存修改数据
                if (updEntryCols.containsKey(fid)) {
                    entryInfo = updEntryCols.get(fid);
                } else {
                    entryInfo = new ExpandAssessEntryInfo();
                    entryInfo.setId(BOSUuid.read(fid));
                    updEntryCols.put(fid, entryInfo);
                }
                //保存修改字段
                if (updSics.containsKey(fid)) {
                    updSic = updSics.get(fid);
                } else {
                    updSic = new SelectorItemCollection();
                    updSics.put(fid, updSic);
                }

                if (type.equals("Enum")) {
                    value = Integer.parseInt(value.toString());
                    colName = "checkRate";
                }
                updSic.add(colName);
                entryInfo.put(colName, value);
            }
            List list = new ArrayList();
            SelectorItemCollection sic = new SelectorItemCollection();
            sic.add("*");
            sic.add("assessor.name");
            for (String id : updEntryCols.keySet()) {
                //修改的实体
                ExpandAssessEntryInfo entryInfo = updEntryCols.get(id);

                //修改的字段
                SelectorItemCollection updSic = updSics.get(id);

                String msg = updSic.toString();
                String[] split = msg.split(",");
                Map map = new HashMap();
                for (int i = 0; i < split.length; i++) {
                    String s = split[i];
                    if (s.equals("assessor") || s.equals("adminorg")) {
                        map.put(s, s);
                    }
                }
                Boolean is = true;
                if (map.get("assessor") != null && map.get("adminorg") != null) {
                    is = existsByAssessorAndAdminOrg(iExpandAssessEntry, entryInfo, list);
                }
                if (map.get("assessor") != null && map.get("adminorg") == null) {
                    ExpandAssessEntryInfo expandAssessEntryInfo = iExpandAssessEntry.getExpandAssessEntryInfo(new ObjectUuidPK(entryInfo.getId()));
                    entryInfo.put("adminOrg", expandAssessEntryInfo.getAdminOrg().getId());
                    is = existsByAssessorAndAdminOrg(iExpandAssessEntry, entryInfo, list);
                }
                if (map.get("assessor") == null && map.get("adminorg") != null) {
                    ExpandAssessEntryInfo expandAssessEntryInfo = iExpandAssessEntry.getExpandAssessEntryInfo(new ObjectUuidPK(entryInfo.getId()));
                    entryInfo.put("assessor", expandAssessEntryInfo.getAssessor().getId());
                    is = existsByAssessorAndAdminOrg(iExpandAssessEntry, entryInfo, list);
                }
                if (is) {
                    iExpandAssessEntry.updatePartial(entryInfo, updSic);
                    succeedNum++;
                } else {
                    errorNum++;
                }

            }
            StringBuilder sb = new StringBuilder();
            sb.append("成功修改" + succeedNum + "条数据\n修改失败" + errorNum + "条数据");
            if (errorNum > 0) {
                sb.append(",失败原因：数据重复！！");
            }
            JSONUtils.SUCCESS(sb);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ShrWebBizException(e);
        }

    }

    private Boolean existsByAssessorAndAdminOrg(IExpandAssessEntry iExpandAssessEntry, ExpandAssessEntryInfo entryInfo, List list) throws BOSException, EASBizException {
        ExpandAssessEntryInfo expandAssessEntryInfo = iExpandAssessEntry.getExpandAssessEntryInfo(new ObjectUuidPK(entryInfo.getId()));
        FilterInfo filterInfo = new FilterInfo();
        filterInfo.getFilterItems().add(new FilterItemInfo("parent.id", expandAssessEntryInfo.getParent().getId()));
        filterInfo.getFilterItems().add(new FilterItemInfo("assessor.id", entryInfo.get("assessor")));
        filterInfo.getFilterItems().add(new FilterItemInfo("adminOrg.id", entryInfo.get("adminOrg")));
        EntityViewInfo entityViewInfo = EntityViewInfo.getInstance(filterInfo, null, null);
        ExpandAssessEntryCollection expandAssessEntryCollection = iExpandAssessEntry.getExpandAssessEntryCollection(entityViewInfo);
        //判断是否存在
        if (expandAssessEntryCollection.size() > 0) {
            ExpandAssessEntryInfo entryinfo = expandAssessEntryCollection.get(0);
            list.add(entryinfo.getAssessor().getName());
            return false;
        }
        return true;
    }

   @Override
    protected void afterGetListData(HttpServletRequest request, HttpServletResponse response, GridDataEntity gridDataEntity) throws SHRWebException {
        List<Map<String, Object>> rows = gridDataEntity.getRows();
        //封装F7部门对象
        for (int i = 0; i < rows.size(); i++) {
            Map<String, Object> map = rows.get(i);
            Map<String, Object> colNameMap = null;
            //部门
            Object adminOrgID = map.get("adminorg.id");
            if (adminOrgID != null && !StringUtils.isEmpty(adminOrgID.toString())) {
                colNameMap = new HashMap<String, Object>();
                colNameMap.put("id", adminOrgID.toString());
                colNameMap.put("name", map.get("adminorg.name"));
                map.put("adminorg.name", colNameMap);
            }
            //考核人
            Object auditorId = map.get("assessor.id");
            if (auditorId != null && !StringUtils.isEmpty(auditorId.toString())) {
                colNameMap = new HashMap<String, Object>();
                colNameMap.put("id", auditorId.toString());
                colNameMap.put("name", map.get("assessor.name"));
                map.put("assessor.name", colNameMap);
            }
            //负责人
            Object scorerId = map.get("principal.id");
            if (scorerId != null && !StringUtils.isEmpty(scorerId.toString())) {
                colNameMap = new HashMap<String, Object>();
                colNameMap.put("id", scorerId.toString());
                colNameMap.put("name", map.get("principal.name"));
                map.put("principal.name", colNameMap);
            }
        }
    }

    /**
     * 获取默认编辑列
     *
     * @param request
     * @return
     */
    protected Map<String, Map<String, Object>> getDefultEditColumnsSetting(HttpServletRequest request) {
        try {
            Map<String, Map<String, Object>> result = new HashMap();
            //部门
            EditColumnInfo editColumnAuditorInfo4 = new EditColumnInfo();
            editColumnAuditorInfo4.setName("adminorg.name");
            //必填
            editColumnAuditorInfo4.setRequired(true);
            EditOptions editoptions4 = editColumnAuditorInfo4.getEditoptions();
            F7Json f7Json4 = editoptions4.getF7Json();
            SubWidgetOptions subWidgetOptions4 = f7Json4.getSubWidgetOptions();
            subWidgetOptions4.setUipk("shr.AllAdminOrgUnit.F7");
            subWidgetOptions4.setTitle("请选择部门");
            subWidgetOptions4.setQuery("");
            result.put("adminorg.name", editColumnAuditorInfo4.convertToMap());
            //考核人
            EditColumnInfo editColumnAuditorInfo2 = new EditColumnInfo();
            //必填
            editColumnAuditorInfo2.setRequired(true);
            editColumnAuditorInfo2.setName("assessor.name");
            EditOptions editoptions2 = editColumnAuditorInfo2.getEditoptions();
            F7Json f7Json2 = editoptions2.getF7Json();
            SubWidgetOptions subWidgetOptions2 = f7Json2.getSubWidgetOptions();
            subWidgetOptions2.setUipk("com.kingdee.eas.basedata.person.app.PersonQwEx.F7");
            subWidgetOptions2.setTitle("请选择考核人");
            //subWidgetOptions2.setQuery("com.kingdee.eas.hr.emp.emp_page.QwCostomPersonQuery");
            subWidgetOptions2.setQuery("com.kingdee.eas.hr.emp.app.PersonWebListQuery");
            result.put("assessor.name", editColumnAuditorInfo2.convertToMap());
            //负责人
            EditColumnInfo editColumnAuditorInfo3 = new EditColumnInfo();
            //必填
            editColumnAuditorInfo3.setRequired(true);
            editColumnAuditorInfo3.setName("principal.name");
            EditOptions editoptions3 = editColumnAuditorInfo3.getEditoptions();
            F7Json f7Json3 = editoptions3.getF7Json();
            SubWidgetOptions subWidgetOptions3 = f7Json3.getSubWidgetOptions();
            subWidgetOptions3.setUipk("com.kingdee.eas.basedata.person.app.PersonQwEx.F7");
            subWidgetOptions3.setTitle("请选择负责人");
            //subWidgetOptions3.setQuery("com.kingdee.eas.hr.emp.emp_page.QwCostomPersonQuery");
            subWidgetOptions3.setQuery("com.kingdee.eas.hr.emp.app.PersonWebListQuery");
            result.put("principal.name", editColumnAuditorInfo3.convertToMap());
            //复核评级
            EditColumnInfo stateEditColumn = new EditColumnInfo();
            stateEditColumn.setName("entrys.checkRate");
            stateEditColumn.setFormatter("shrselect");
            stateEditColumn.setEdittype("shrselect");
            stateEditColumn.setType("shrselect");
            EditOptions stateEditoptions = stateEditColumn.getEditoptions();
            stateEditoptions.setUrlSource("com.kingdee.eas.custom.expandassess.app.AssessRatingEnum");
            SelectJson selectJson = stateEditoptions.getSelectJson();
            selectJson.setId("setCheckRate");//方法名称
            selectJson.setName("checkRate");//属性名称
            selectJson.setEnumSource("com.kingdee.eas.custom.expandassess.app.AssessRatingEnum");
            result.put("entrys.checkRate", stateEditColumn.convertToMap());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }


    /**
     * customDelete  删除
     *
     * @param request
     * @param response
     * @param modelMap
     * @return
     * @throws SHRWebException
     */
    public void customDeleteAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws SHRWebException, BOSException, EASBizException {
        //获取删除ID
        String idArray = request.getParameter("idArray");
        //调用删除方法
        expandAssessService.deleteExpandAssessEntry(ctx, idArray);
    }

    /**
     * 解锁周期
     *
     * @param request
     * @param response
     * @param modelMap
     * @throws ShrWebBizException
     * @throws BOSException
     */
    public void unlockAction(HttpServletRequest request,
                             HttpServletResponse response,
                             ModelMap modelMap) throws EASBizException, ShrWebBizException, BOSException {
        String billId = request.getParameter("billId");
        if (StringUtils.isEmpty(billId)) {
            throw new ShrWebBizException("拓展人员考核周期ID不可为空！");
        }
        IExpandAssess iExpandAssess = ExpandAssessFactory.getLocalInstance(ctx);
        //锁定周期
        iExpandAssess.unlock(billId);
    }

    /**
     * 锁定周期
     *
     * @param request
     * @param response
     * @param modelMap
     * @throws ShrWebBizException
     * @throws BOSException
     */
    public void lockAction(HttpServletRequest request,
                           HttpServletResponse response,
                           ModelMap modelMap) throws EASBizException, ShrWebBizException, BOSException {
        String billId = request.getParameter("billId");
        if (StringUtils.isEmpty(billId)) {
            throw new ShrWebBizException("拓展人员考核周期ID不可为空！");
        }
        IExpandAssess iExpandAssess = ExpandAssessFactory.getLocalInstance(ctx);
        IExpandAssessEntry iExpandAssessEntry = ExpandAssessEntryFactory.getLocalInstance(ctx);
        FilterInfo filterInfo = new FilterInfo();
        filterInfo.getFilterItems().add(new FilterItemInfo("parent.id", billId));
        SelectorItemCollection sic = new SelectorItemCollection();
        sic.add("principal.name");
        sic.add("*");
        EntityViewInfo entityViewInfo = EntityViewInfo.getInstance(filterInfo, sic, null);
        ExpandAssessEntryCollection expandAssessEntryCollection = iExpandAssessEntry.getExpandAssessEntryCollection(entityViewInfo);
        for (int i = 0; i < expandAssessEntryCollection.size(); i++) {
            ExpandAssessEntryInfo expandAssessEntryInfo = expandAssessEntryCollection.get(i);
            if (expandAssessEntryInfo.getAsseStatus() != ExpandStatusEunm.PRINCIPALSUBMIT) {
                throw new ShrWebBizException("还有数据未提交，不可锁定周期");
            }

        }
        //锁定周期
        iExpandAssess.lock(billId);
    }

    /***
     * 关闭考核
     * @param request
     * @param response
     * @param modelMap
     * @throws ShrWebBizException
     * @throws BOSException
     */
    public void closeCheckAction(HttpServletRequest request,
                                 HttpServletResponse response,
                                 ModelMap modelMap) throws ShrWebBizException, BOSException {
        String billId = request.getParameter("billId");
        String entryIds = request.getParameter("entryIds");
        if (StringUtils.isEmpty(entryIds)) {
            throw new ShrWebBizException("请勾选需要关闭考核的数据！");
        }
        IExpandAssess iExpandAssess = ExpandAssessFactory.getLocalInstance(ctx);
        //关闭
        iExpandAssess.closeCheck(entryIds);
    }

    /***
     * 启动考核
     * @param request
     * @param response
     * @param modelMap
     * @throws ShrWebBizException
     * @throws BOSException
     */
    public void startCheckAction(HttpServletRequest request,
                                 HttpServletResponse response,
                                 ModelMap modelMap) throws ShrWebBizException, BOSException, EASBizException {
        String billId = request.getParameter("billId");
        if (StringUtils.isEmpty(billId)) {
            throw new ShrWebBizException("拓展人员考核周期ID不可为空！");
        }
        IExpandAssess iExpandAssess = ExpandAssessFactory.getLocalInstance(ctx);
        ExpandAssessInfo expandAssessInfo = iExpandAssess.getExpandAssessInfo(new ObjectUuidPK(billId));
        int year = expandAssessInfo.getYear();
        QuarterlyRatioCollection quarterlyRatioByYear = expandAssessService.getQuarterlyRatioByYear(ctx, year);
        if (quarterlyRatioByYear == null) {
            throw new ShrWebBizException("未维护" + year + "年，季度比例表。请维护后再启动！！");
        } else {
            //启动考核
            iExpandAssess.startCheck(billId);
        }
    }
}
