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

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.bos.metadata.entity.*;
import com.kingdee.bos.util.BOSUuid;
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.custom.projectbonus.task.ProjectbonusFacadeFactory;
import com.kingdee.eas.custom.projectbonus.web.vo.*;
import com.kingdee.eas.framework.ICoreBase;
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.handler.DynamicListHandler;
import com.kingdee.shr.base.syssetting.web.json.JSONUtils;
import com.kingdee.util.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.ui.ModelMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

/**
 * @Description 项奖金周期表动态列表handler
 * @Date 2024/4/22 17:56
 * @Created by Heyuan
 */
public class BusDepProjectDynamicListHandler extends ProjectBonusDynamicHandler {
    private static Logger logger = Logger.getLogger(BusDepProjectDynamicListHandler.class);

    /**
     * 获取生效日期过滤器
     * 移除父类方法过滤条件
     *
     * @param effectDate
     * @return
     */
    protected FilterInfo getEffectDateFilter(Date effectDate) {
        return null;
    }

    /**
     * @param request
     * @param response
     * @param gridDataEntity
     * @throws SHRWebException
     */
    protected void afterGetListData(HttpServletRequest request,
                                    HttpServletResponse response,
                                    GridDataEntity gridDataEntity) throws SHRWebException {
        super.afterGetListData(request, response, gridDataEntity);
        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> principal = new HashMap<String, Object>();
            Object obj = map.get("principal.id");
            if (obj != null && !StringUtils.isEmpty(obj.toString())) {
                principal.put("id", obj.toString());
                principal.put("name", map.get("principal.name"));
            }
            //事业部负责人
            map.put("principal.name", principal);
            Map<String, Object> project = new HashMap<String, Object>();
            Object proPrin = map.get("proprin.id");
            if (proPrin != null && !StringUtils.isEmpty(proPrin.toString())) {
                project.put("id", proPrin.toString());
                project.put("name", map.get("proprin.name"));
            }
            //项目负责人
            map.put("proprin.name", project);
        }
    }

    /**
     * 获取默认编辑列
     *
     * @param request
     * @return
     */
    protected Map<String, Map<String, Object>> getDefultEditColumnsSetting(HttpServletRequest request) {
        try {
            //设置F7编辑列属性
            Map<String, Map<String, Object>> result = new HashMap();
            EditColumnInfo editColumnInfo = new EditColumnInfo();
            editColumnInfo.setName("principal.name");
            EditOptions editoptions = editColumnInfo.getEditoptions();
            F7Json f7Json = editoptions.getF7Json();
            SubWidgetOptions subWidgetOptions = f7Json.getSubWidgetOptions();
            subWidgetOptions.setUipk("com.kingdee.eas.custom.projectbonus.app.BonusCycle.Person.F7");
            subWidgetOptions.setTitle("事业部负责人");
            subWidgetOptions.setQuery("com.kingdee.eas.hr.emp.app.PersonWebListQuery");
            result.put("principal.name", editColumnInfo.convertToMap());
            //项目负责人
            EditColumnInfo proPrinEditColumnInfo = new EditColumnInfo();
            proPrinEditColumnInfo.setName("proPrin.name");
            EditOptions proPrinEditoptions = proPrinEditColumnInfo.getEditoptions();
            F7Json proPrinF7Json = proPrinEditoptions.getF7Json();
            SubWidgetOptions proPrinSubWidgetOptions = proPrinF7Json.getSubWidgetOptions();
            proPrinSubWidgetOptions.setUipk("com.kingdee.eas.custom.projectbonus.app.BonusCycle.Person.F7");
            proPrinSubWidgetOptions.setTitle("项目负责人");
            proPrinSubWidgetOptions.setQuery("com.kingdee.eas.hr.emp.app.PersonWebListQuery");
            result.put("proPrin.name", proPrinEditColumnInfo.convertToMap());
            //状态枚举
//            EditColumnInfo stateEditColumn = new EditColumnInfo();
//            stateEditColumn.setName("bDP.state");
//            stateEditColumn.setFormatter("shrselect");
//            stateEditColumn.setEdittype("shrselect");
//            stateEditColumn.setType("shrselect");
//            EditOptions stateEditoptions = stateEditColumn.getEditoptions();
//            stateEditoptions.setUrlSource("com.kingdee.shr.base.syssetting.StateEnum");
//            SelectJson selectJson = stateEditoptions.getSelectJson();
//            selectJson.setId("setState");//方法名称
//            selectJson.setName("state");//属性名称
//            selectJson.setEnumSource("com.kingdee.shr.base.syssetting.StateEnum");
//            result.put("bDP.state", stateEditColumn.convertToMap());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 动态表单保存
     *
     * @param request
     * @param response
     * @param modelMap
     * @return
     * @throws SHRWebException
     */
    public void saveDynGridAction(HttpServletRequest request,
                                  HttpServletResponse response,
                                  ModelMap modelMap) throws SHRWebException {
        Context ctx = SHRContext.getInstance().getContext();
        List<Map<String, Object>> dataList = (List) JSONUtils.convertJsonToObject(request.getParameter("modi"), List.class);
        try {
            IBonusCycleBusDepProject iBonusCycleBusDepProject = BonusCycleBusDepProjectFactory.getLocalInstance(ctx);
            //待更新数据集合
            Map<String, BonusCycleBusDepProjectInfo> updateCols = new HashMap<String, BonusCycleBusDepProjectInfo>();
            //待更新字段
            Map<String, SelectorItemCollection> updateSics = new HashMap<String, SelectorItemCollection>();
            for (int i = 0; i < dataList.size(); i++) {
                Map<String, Object> map = dataList.get(i);
                String idxValue = (String) map.get("fid");
                BonusCycleBusDepProjectInfo info;
                SelectorItemCollection updateSic;
                if (updateCols.containsKey(idxValue)) {
                    info = updateCols.get(idxValue);
                } else {
                    info = new BonusCycleBusDepProjectInfo();
                    info.setId(BOSUuid.read(idxValue));
                    updateCols.put(idxValue, info);
                }
                //保存更新列
                if (updateSics.containsKey(idxValue)) {
                    updateSic = updateSics.get(idxValue);
                } else {
                    updateSic = new SelectorItemCollection();
                    updateSics.put(idxValue, updateSic);
                }
                //列名
                String colName = (String) map.get("column");
                if ("proprin".equals(colName)) {
                    colName = "projectPrincipal";
                }
                //数据类型
                String dataType = (String) map.get("type");
                //值
                Object valueObj = map.get("value");
                if ("BigDecimal".equals(dataType) && StringUtils.isEmpty(valueObj.toString())) {
                    valueObj = BigDecimal.ZERO;
                }
                updateSic.add(colName);
                info.put(colName, valueObj);
            }
            SelectorItemCollection sic = new SelectorItemCollection();
            sic.add("state");
            SelectorItemInfo bonusAmountSic = new SelectorItemInfo("bonusAmount");
            SelectorItemInfo principalSic = new SelectorItemInfo("principal");
            //成功更新数据条数
            int successNum = 0;
            for (String id : updateCols.keySet()) {
                SelectorItemCollection updateSic = updateSics.get(id);
                BonusCycleBusDepProjectInfo oldInfo =
                        iBonusCycleBusDepProject.getBonusCycleBusDepProjectInfo(new ObjectUuidPK(id), sic);
                //事业部项目
                BusDepProjectStateEnum state = oldInfo.getState();
                if (BusDepProjectStateEnum.ENABLE.equals(state) || BusDepProjectStateEnum.SUBMITED.equals(state)) {
                    //当状态为启用或提交，不允许修改负责人和奖金分包金额
                    if (updateSic.contains(bonusAmountSic) || updateSic.contains(principalSic)) {
                        continue;
                    }
                }
                BonusCycleBusDepProjectInfo info = updateCols.get(id);
                //更新
                iBonusCycleBusDepProject.updatePartial(info, updateSic);
                successNum++;
            }
            JSONUtils.SUCCESS("成功修改" + successNum + "条数据");
        } catch (Exception var27) {
            var27.printStackTrace();
            logger.error(var27.getMessage());
            throw new ShrWebBizException(var27.getMessage(), var27);
        }
    }

    /**
     * 同步事业部项目
     *
     * @param request
     * @param response
     * @param modelMap
     * @throws SHRWebException
     */
    public void syncDepProjectAction(HttpServletRequest request,
                                     HttpServletResponse response,
                                     ModelMap modelMap) throws SHRWebException {
        String parentId = request.getParameter("parentId");//周期id
        Context ctx = SHRContext.getInstance().getContext();
        try {
            IBonusCycleBusDepProject iBonusCycleBusDepProject =
                    BonusCycleBusDepProjectFactory.getLocalInstance(ctx);
            String resultMsg = iBonusCycleBusDepProject.syncDepProject(parentId);
            JSONUtils.SUCCESS(resultMsg);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ShrWebBizException(e.getMessage());
        }
    }

    /**
     * 获取接口
     *
     * @param request
     * @return
     * @throws SHRWebException
     */
    @Override
    protected ICoreBase getBizInterface(HttpServletRequest request) throws SHRWebException {
        Context ctx = SHRContext.getInstance().getContext();
        try {
            return BonusCycleBusDepProjectFactory.getLocalInstance(ctx);
        } catch (BOSException e) {
            e.printStackTrace();
            throw new ShrWebBizException(e.getMessage());
        }
    }

    /**
     * 批量撤回
     *
     * @param request
     * @param response
     * @param modelMap
     * @throws SHRWebException
     */
    public void batchWithdrawAction(HttpServletRequest request,
                                    HttpServletResponse response,
                                    ModelMap modelMap) throws SHRWebException {
        this.handleEnableWithTips(request, "withdraw");
    }

    /**
     * 锁定周期
     *
     * @param request
     * @param response
     * @param modelMap
     * @throws SHRWebException
     */
    public void lockAction(HttpServletRequest request,
                           HttpServletResponse response,
                           ModelMap modelMap) throws SHRWebException {
        Context ctx = SHRContext.getInstance().getContext();
        try {
            String parentId = request.getParameter("parentId");
            BonusCycleFactory.getLocalInstance(ctx).lock(parentId);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ShrWebBizException(e.getMessage());
        }
    }

    /**
     * 解锁周期
     *
     * @param request
     * @param response
     * @param modelMap
     * @throws SHRWebException
     */
    public void unlockAction(HttpServletRequest request,
                             HttpServletResponse response,
                             ModelMap modelMap) throws SHRWebException {
        Context ctx = SHRContext.getInstance().getContext();
        try {
            String parentId = request.getParameter("parentId");
            BonusCycleFactory.getLocalInstance(ctx).unLock(parentId);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ShrWebBizException(e.getMessage());
        }
    }


    /**
     * 催办
     *
     * @param request
     * @param response
     * @param modelMap
     * @throws SHRWebException
     */
    public void noticePrincipalAction(HttpServletRequest request,
                                      HttpServletResponse response,
                                      ModelMap modelMap) throws SHRWebException {
        Context ctx = SHRContext.getInstance().getContext();
        try {
            String parentId = request.getParameter("parentId");
            String resultMsg = ProjectbonusFacadeFactory.getLocalInstance(ctx)
                    .noticePrincipal(parentId);
            JSONUtils.SUCCESS(resultMsg);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ShrWebBizException(e.getMessage());
        }
    }


    /**
     * 通过周期id获取锁定状态
     *
     * @param request
     * @param response
     * @param modelMap
     * @return
     * @throws SHRWebException
     */
    public void getStateByBonusCycleIdAction(HttpServletRequest request,
                                             HttpServletResponse response,
                                             ModelMap modelMap) throws SHRWebException {
        //周期id
        String bonusCycleId = request.getParameter("bonusCycleId");
        if (StringUtils.isEmpty(bonusCycleId)) {
            throw new ShrWebBizException("周期id不能为空！");
        }
        Context ctx = SHRContext.getInstance().getContext();
        try {
            BonusCycleInfo info = BonusCycleFactory.getLocalInstance(ctx)
                    .getBonusCycleInfo(new ObjectUuidPK(bonusCycleId));
            CycleStateEnum state = info.getState();
            JSONUtils.SUCCESS(state);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ShrWebBizException(e.getMessage());
        }
    }
}
