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.SelectorItemCollection;
import com.kingdee.bos.util.BOSUuid;
import com.kingdee.eas.basedata.person.PersonInfo;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.custom.projectbonus.*;
import com.kingdee.eas.custom.projectbonus.bizEnum.BusDepProjectStateEnum;
import com.kingdee.eas.custom.projectbonus.web.vo.EditColumnInfo;
import com.kingdee.eas.custom.projectbonus.web.vo.EditOptions;
import com.kingdee.eas.custom.projectbonus.web.vo.F7Json;
import com.kingdee.eas.custom.projectbonus.web.vo.SubWidgetOptions;
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.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 PrincipalDetailDynamicListHandler extends PersonnelDetailDynamicListHandler {
    private static Logger logger = Logger.getLogger(PrincipalDetailDynamicListHandler.class);


    /**
     * 获取默认编辑列
     *
     * @param request
     * @return
     */
    @Override
    protected Map<String, Map<String, Object>> getDefultEditColumnsSetting(HttpServletRequest request) {
        try {
            //设置F7编辑列属性
            Map<String, Map<String, Object>> result = new HashMap();
            //奖金期限截止日期
            EditColumnInfo dateEditColumnInfo = new EditColumnInfo();
            dateEditColumnInfo.setName("bDPAPD.bonusDueDate");
            dateEditColumnInfo.setFormatter("shrDateTimePicker");
            dateEditColumnInfo.setEdittype("shrDateTimePicker");
            dateEditColumnInfo.setType("shrDateTimePicker");
            EditOptions dateEditoptions = dateEditColumnInfo.getEditoptions();
            dateEditoptions.getDatepickerjson();
            result.put("bDPAPD.bonusDueDate", dateEditColumnInfo.convertToMap());
            //奖金期限起算日期
            EditColumnInfo dateEditColumnInfo2 = new EditColumnInfo();
            dateEditColumnInfo2.setName("bDPAPD.bonusStartingDate");
            dateEditColumnInfo2.setFormatter("shrDateTimePicker");
            dateEditColumnInfo2.setEdittype("shrDateTimePicker");
            dateEditColumnInfo2.setType("shrDateTimePicker");
            EditOptions dateEditoptions2 = dateEditColumnInfo2.getEditoptions();
            dateEditoptions2.getDatepickerjson();
            result.put("bDPAPD.bonusStartingDate", dateEditColumnInfo2.convertToMap());
            //分配人员
            EditColumnInfo editColumnInfo = new EditColumnInfo();
            editColumnInfo.setName("person.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("person.name", editColumnInfo.convertToMap());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * @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> person = new HashMap<String, Object>();
            Object obj = map.get("person.id");
            if (obj != null && !StringUtils.isEmpty(obj.toString())) {
                person.put("id", obj.toString());
                person.put("name", map.get("person.name"));
            }
            //分配人员
            map.put("person.name", person);
        }
    }

    /**
     * 动态表单保存
     *
     * @param request
     * @param response
     * @param modelMap
     * @return
     * @throws SHRWebException
     */
    @Override
    public void saveDynGridAction(HttpServletRequest request,
                                  HttpServletResponse response,
                                  ModelMap modelMap) throws SHRWebException {
        List<Map<String, Object>> dataList = (List) JSONUtils.convertJsonToObject(request.getParameter("modi"), List.class);
        try {
            //非启用状态的事业部数据不能保存
            IBonusCycleBusDepProjectAssPersonnelDetail iPersonnelDetail = (IBonusCycleBusDepProjectAssPersonnelDetail) getBizInterface(request);
            //待更新数据集合
            Map<String, BonusCycleBusDepProjectAssPersonnelDetailInfo> updateCols = new HashMap<String, BonusCycleBusDepProjectAssPersonnelDetailInfo>();
            //待更新字段
            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");
                BonusCycleBusDepProjectAssPersonnelDetailInfo info;
                SelectorItemCollection updateSic;
                if (updateCols.containsKey(idxValue)) {
                    info = updateCols.get(idxValue);
                } else {
                    info = new BonusCycleBusDepProjectAssPersonnelDetailInfo();
                    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");
                //数据类型
                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);
            }
            //成功更新数据条数
            int successNum = 0;
            SelectorItemCollection sic = new SelectorItemCollection();
            sic.add("parent.state");
            for (String id : updateCols.keySet()) {
                BonusCycleBusDepProjectAssPersonnelDetailInfo oldInfo =
                        iPersonnelDetail.getBonusCycleBusDepProjectAssPersonnelDetailInfo(new ObjectUuidPK(id), sic);
                //事业部项目
                BonusCycleBusDepProjectInfo parent = oldInfo.getParent();
                BusDepProjectStateEnum state = parent.getState();
                if (!BusDepProjectStateEnum.ENABLE.equals(state) && !BusDepProjectStateEnum.SUBMITCALCULATED.equals(state)) {
                    continue;
                }
                BonusCycleBusDepProjectAssPersonnelDetailInfo info = updateCols.get(id);
                SelectorItemCollection updateSic = updateSics.get(id);
                //更新
                iPersonnelDetail.updatePartial(info, updateSic);
                successNum++;
            }
            JSONUtils.SUCCESS("成功修改" + successNum + "条数据");
        } catch (Exception var27) {
            var27.printStackTrace();
            logger.error(var27.getMessage());
            throw new ShrWebBizException(var27.getMessage(), var27);
        }
    }


    /**
     * 通过事业部id获取状态
     *
     * @param request
     * @param response
     * @param modelMap
     * @return
     * @throws SHRWebException
     */
    public void getStateByBusDepIdAction(HttpServletRequest request,
                                         HttpServletResponse response,
                                         ModelMap modelMap) throws SHRWebException {
        //事业部项目ids
        String busDepId = request.getParameter("busDepId");
        if (StringUtils.isEmpty(busDepId)) {
            throw new ShrWebBizException("事业部项目id不能为空！");
        }
        Context ctx = SHRContext.getInstance().getContext();
        try {
            BonusCycleBusDepProjectInfo info = BonusCycleBusDepProjectFactory.getLocalInstance(ctx).getBonusCycleBusDepProjectInfo(new ObjectUuidPK(busDepId));
            BusDepProjectStateEnum state = info.getState();
            JSONUtils.SUCCESS(state);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ShrWebBizException(e.getMessage());
        }
    }

    /**
     * 提交
     *
     * @param request
     * @param response
     * @param modelMap
     * @throws SHRWebException
     */
    public void customSubmitAction(HttpServletRequest request,
                                   HttpServletResponse response,
                                   ModelMap modelMap) throws SHRWebException, BOSException, EASBizException {
        Context ctx = SHRContext.getInstance().getContext();
        //事业部项目ids
        String busDepId = request.getParameter("busDepId");
        if (StringUtils.isEmpty(busDepId)) {
            throw new ShrWebBizException("事业部项目id不能为空！");
        }
        try {
            //提交
            BonusCycleBusDepProjectFactory.getLocalInstance(ctx).submit(busDepId);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ShrWebBizException("提交失败，错误原因：" + e.getMessage());
        }
    }

    /**
     * 提交复核
     *
     * @param request
     * @param response
     * @param modelMap
     * @throws SHRWebException
     */
    public void submitRecheckAction(HttpServletRequest request,
                                    HttpServletResponse response,
                                    ModelMap modelMap) throws SHRWebException {
        Context ctx = SHRContext.getInstance().getContext();
        //事业部项目ids
        String busDepId = request.getParameter("busDepId");
        if (StringUtils.isEmpty(busDepId)) {
            throw new ShrWebBizException("事业部项目id不能为空！");
        }
        try {
            BonusCycleBusDepProjectFactory.getLocalInstance(ctx).submitRecheck(busDepId);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ShrWebBizException("提交失败，错误原因：" + e.getMessage());
        }
    }

    /**
     * 获取征求意见金额跟个人奖金差异数据
     *
     * @param request
     * @param response
     * @param modelMap
     * @throws SHRWebException
     */
    public void getDifferenceAmountAction(HttpServletRequest request,
                                          HttpServletResponse response,
                                          ModelMap modelMap) throws SHRWebException {
        Context ctx = SHRContext.getInstance().getContext();
        //事业部项目ids
        String busDepId = request.getParameter("busDepId");
        if (StringUtils.isEmpty(busDepId)) {
            throw new ShrWebBizException("事业部项目id不能为空！");
        }
        try {
            IBonusCycleBusDepProjectAssPersonnelDetail iAssPersonnelDetail = BonusCycleBusDepProjectAssPersonnelDetailFactory.getLocalInstance(ctx);
            String oql = "select indivBonusAmount,opinionAmount,person.name,person.number where parent.id ='" + busDepId + "'";
            BonusCycleBusDepProjectAssPersonnelDetailCollection personnelDetailCollection =
                    iAssPersonnelDetail.getBonusCycleBusDepProjectAssPersonnelDetailCollection(oql);
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            for (int i = 0; i < personnelDetailCollection.size(); i++) {
                BonusCycleBusDepProjectAssPersonnelDetailInfo personnelDetailInfo = personnelDetailCollection.get(i);
                BigDecimal indivBonusAmount = personnelDetailInfo.getIndivBonusAmount();//个人奖金
                BigDecimal opinionAmount = personnelDetailInfo.getOpinionAmount();//征求意见金额
                if (indivBonusAmount.compareTo(opinionAmount) != 0) {
                    PersonInfo person = personnelDetailInfo.getPerson();
                    String personNumber = person.getNumber();
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("person.number", personNumber);
                    map.put("person.name", person);
                    map.put("bdpapd.indivbonusamount", indivBonusAmount);
                    map.put("bdpapd.opinionamount", opinionAmount);
                    list.add(map);
                }
            }
            JSONUtils.SUCCESS(list);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ShrWebBizException(e.getMessage());
        }
    }
}
