package com.kingdee.eas.custom.synctask.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.metadata.entity.*;
import com.kingdee.bos.metadata.query.util.CompareType;
import com.kingdee.eas.basedata.person.IPerson;
import com.kingdee.eas.basedata.person.PersonCollection;
import com.kingdee.eas.basedata.person.PersonFactory;
import com.kingdee.eas.basedata.person.PersonInfo;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.cp.taskmng.util.StringUtil;
import com.kingdee.eas.custom.synctask.SyncTranForIOTFacadeFactory;
import com.kingdee.eas.custom.synctask.SyncTranForOAFacadeFactory;
import com.kingdee.eas.hr.ats.AtsUtil;
import com.kingdee.eas.hr.emp.web.handler.EmployeeListHandler;
import com.kingdee.shr.base.syssetting.api.bean.BatchMessageTipsBody;
import com.kingdee.shr.base.syssetting.api.bean.BatchMessageTipsHeader;
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.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.util.*;


/**
 * @author qingwu
 * @date 2024/10/24
 * @apiNote 员工信息维护扩展
 */
public class EmployeeListHandlerEx extends EmployeeListHandler {
    public Logger logger = Logger.getLogger(EmployeeListHandlerEx.class);
    public Context ctx = SHRContext.getInstance().getContext();
    public static Map<String, String> personStatusMap = new HashMap<String, String>();

    static {
        personStatusMap.put("001", "1");//试用员工
        personStatusMap.put("011", "1");//待岗
        personStatusMap.put("006", "1");//长期病假
        personStatusMap.put("007", "1");//停薪留职
        personStatusMap.put("005", "1");//出国
        personStatusMap.put("012", "1");//返聘员工
        personStatusMap.put("031", "1");//长学
        personStatusMap.put("S01", "1");//实习生
        personStatusMap.put("S02", "1");//劳务派遣
        personStatusMap.put("S05", "1");//待分配
        personStatusMap.put("S03", "1");//顾问
        personStatusMap.put("S20", "1");//临时工
        personStatusMap.put("002", "3");//辞退
        personStatusMap.put("010", "3");//辞职
        personStatusMap.put("009", "3");//退休
        personStatusMap.put("003", "3");//下岗
        personStatusMap.put("004", "3");//离休
        personStatusMap.put("013", "3");//开除
        personStatusMap.put("020", "3");//解聘
        personStatusMap.put("021", "3");//失踪
        personStatusMap.put("030", "3");//死亡
        personStatusMap.put("S04", "3");//返聘终止
        personStatusMap.put("S08", "3");//离职
        personStatusMap.put("S09", "3");//派遣终止
        personStatusMap.put("035", "3");//临时工终止
        personStatusMap.put("S07", "3");//实习终止
    }

    /**
     * 获取人员批处理信息
     *
     * @param request
     * @param response
     * @param modelMap
     * @return
     */
    public void getPersonBatchInfoAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws BOSException, ShrWebBizException {
        try {
            IPerson iPerson = PersonFactory.getLocalInstance(ctx);
            PersonCollection personCollection = null;
            String ids = request.getParameter("ids");
            if (StringUtil.isEmpty(ids)) {
                personCollection = iPerson.getPersonCollection();
            } else {
                Set<String> adminOrgIds = AtsUtil.toSet(ids);
                FilterInfo filterInfo = new FilterInfo();
                FilterItemCollection filterItems = filterInfo.getFilterItems();
                filterItems.add(new FilterItemInfo("id", adminOrgIds, CompareType.INCLUDE));
                EntityViewInfo entityViewInfo = EntityViewInfo.getInstance(filterInfo, null, null);
                personCollection = iPerson.getPersonCollection(entityViewInfo);
            }
            List list = new ArrayList();
            for (int i = 0; i < personCollection.size(); i++) {
                PersonInfo personInfo = personCollection.get(i);
                Map personMap = new HashMap();
                personMap.put("person.name", personInfo.getName());
                personMap.put("person.number", personInfo.getNumber());
                personMap.put("person.id", personInfo.getId().toString());
                personMap.put("id", personInfo.getId().toString());
                list.add(personMap);
            }
            JSONUtils.SUCCESS(list);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ShrWebBizException(e);
        }
    }



    /**
     * 同步IOT人员
     *   后续如需部署生产去掉Ex
     * @param request
     * @param response
     * @param modelMap
     * @throws BOSException
     * @throws EASBizException
     * @throws SHRWebException
     */
    public void syncPersonToIotAction(HttpServletRequest request,
                                      HttpServletResponse response,
                                      ModelMap modelMap) throws BOSException, ShrWebBizException {
        String billId = request.getParameter("billId");
        IPerson iPerson = PersonFactory.getLocalInstance(ctx);
        PersonCollection personCollection = null;
        Set personIds = null;
        Map<String, String> personNameAndNumberMap = new HashMap<String, String>();
        if (StringUtils.isEmpty(billId)) {
            personCollection = iPerson.getPersonCollection("select id,number");
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < personCollection.size(); i++) {
                PersonInfo personInfo = personCollection.get(i);
                String personId = personInfo.getId().toString();
                String personNumber = personInfo.getNumber().toString();
                sb.append(personId).append(",");
                personNameAndNumberMap.put(personNumber, personId);
            }
            sb.deleteCharAt(sb.lastIndexOf(","));
            billId = sb.toString();
        } else {
            personCollection = iPerson.getPersonCollection("select id,number where id in (" + AtsUtil.getStrFromString(billId) + ")");
        }
        personIds = AtsUtil.toSet(billId);
        //调用同步IOT人员
        try {
            //部署测试环境需要注释此行
            Map<String, String> resultMap = SyncTranForIOTFacadeFactory.getLocalInstance(ctx).syncPersonToIot(billId);
            int failure = 0;
            int success = personIds.size();
            BatchMessageTipsHeader batchMessageTipsHeader = new BatchMessageTipsHeader();
            for (int i = 0; i < personCollection.size(); i++) {
                BatchMessageTipsBody body = new BatchMessageTipsBody();
                PersonInfo personInfo = personCollection.get(i);
                body.setId(personInfo.getId().toString());
                String personNumber = personInfo.getNumber();
                if (resultMap.containsKey(personNumber)) {
                    //失败
                    body.setMuitTipsState(false);
                    body.setMuitTipsMessage(resultMap.get(personNumber));
                    failure++;
                } else {
                    body.setMuitTipsState(true);
                }
                batchMessageTipsHeader.addResult(body);
            }
            success -= failure;
            logger.error("handleEnableWithTips----- >> ");
            batchMessageTipsHeader.setBillId(billId);
            batchMessageTipsHeader.setFailureCount(failure);
            batchMessageTipsHeader.setSuccessCount(success);
            ObjectMapper mapper = new ObjectMapper();
            logger.error("handleEnableWithTips----- >> " + mapper.writeValueAsString(batchMessageTipsHeader));
            logger.error("handleEnableWithTips--size--- >> " + batchMessageTipsHeader.getResult().size());
            //logger.error("batchMessageTipsHeader  " + batchMessageTipsHeader.getSuccessCount());
            request.setAttribute("res_method_data", batchMessageTipsHeader);
            this.writeSuccessData(batchMessageTipsHeader);
            logger.error("handleEnableWithTips----- end ");
        } catch (Exception e) {
            e.printStackTrace();
            throw new ShrWebBizException(e);
        }
    }


    /**
     * 同步OA人员
     *
     * @param request
     * @param response
     * @param modelMap
     * @throws BOSException
     * @throws EASBizException
     * @throws SHRWebException
     */
    public void syncPersonToOAAction(HttpServletRequest request,
                                     HttpServletResponse response,
                                     ModelMap modelMap) throws BOSException, EASBizException, SHRWebException {
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            String headerValue = request.getHeader(headerName);
            logger.error("----headerNames------key【" + headerName + "】-value【 " + headerValue + "】");
        }
        Enumeration enu = request.getParameterNames();
        while (enu.hasMoreElements()) {
            String paraName = (String) enu.nextElement();
            logger.error("----ParameterNames------key【" + paraName + "】-value【 " + request.getParameter(paraName) + "】");
        }
        //String billId = request.getParameter("billId[]");
        ////}
        //if (StringUtils.isEmpty(billId)) {
        //    billId = (String) request.getAttribute("billId[]");
        //}
        //if (StringUtils.isEmpty(billId)) {
        //    billId = request.getParameter("billIds[]");
        //}
        //if (StringUtils.isEmpty(billId)) {
        //    billId = (String) request.getAttribute("billIds[]");
        //}
        //logger.error("----headerNames------billId----" + billId);

        this.handleEnableWithTips(request, "");
    }


    protected void handleEnableWithTips(HttpServletRequest request, String methodName) throws SHRWebException {
        //String billId = this.getBillId(request);
        String billId = request.getParameter("billId");
        //}
        if (StringUtils.isEmpty(billId)) {
            billId = (String) request.getAttribute("billId");
        }
        if (StringUtils.isEmpty(billId)) {
            billId = request.getParameter("billIds[]");
        }
        if (StringUtils.isEmpty(billId)) {
            billId = (String) request.getAttribute("billId[]");
        }
        try {
            IPerson iPerson = PersonFactory.getLocalInstance(ctx);
            if (StringUtils.isEmpty(billId)) {
                PersonCollection personCollection = iPerson.getPersonCollection("select id");
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < personCollection.size(); i++) {
                    String personId = personCollection.get(i).getId().toString();
                    sb.append(personId).append(",");
                }
                sb.deleteCharAt(sb.lastIndexOf(","));
                billId = sb.toString();
            }
            Map<String, Object> resultMap = SyncTranForOAFacadeFactory.getLocalInstance(ctx).syncPersonToOA(billId, null);
            logger.error("handleEnableWithTips----- resultMap----" + resultMap);
            if (resultMap != null && !resultMap.isEmpty()) {
                logger.error("handleEnableWithTips----- start ");
                logger.error("handleEnableWithTips----- billId-- " + billId);
                PersonCollection personCollection = iPerson.getPersonCollection("select id,number where id in (" + AtsUtil.getStrFromString(billId) + ")");
                int sucess = 0;
                int failure = 0;
                BatchMessageTipsHeader batchMessageTipsHeader = new BatchMessageTipsHeader();
                for (int i = 0; i < personCollection.size(); i++) {
                    BatchMessageTipsBody body = new BatchMessageTipsBody();
                    PersonInfo personInfo = personCollection.get(i);
                    body.setId(personInfo.getId().toString());
                    String personNumber = personInfo.getNumber();
                    Map<String, String> map = (Map<String, String>) resultMap.get(personNumber);
                    logger.error("map----" + map);
                    if (map == null) {
                        ++failure;
                        body.setMuitTipsState(Boolean.FALSE);
                        body.setMuitTipsMessage("同步数据不能为空或检查是否同步OA字段是否等于否!");
                    } else {
                        if ("success".equals(map.get("state"))) {
                            ++sucess;
                            body.setMuitTipsState(Boolean.TRUE);
                            body.setMuitTipsMessage(map.get("msg"));
                        } else {
                            ++failure;
                            body.setMuitTipsState(Boolean.FALSE);
                            body.setMuitTipsMessage(map.get("msg"));
                        }
                    }
                    batchMessageTipsHeader.addResult(body);
                }
                //if (StringUtils.isEmpty(billId)) {
                //    Set setPersonIds = (Set) resultMap.get("setPersonIds");
                //    FilterInfo filterInfo = new FilterInfo();
                //    filterInfo.getFilterItems().add(new FilterItemInfo("id", setPersonIds, CompareType.NOTINCLUDE));
                //    EntityViewInfo entityViewInfo = EntityViewInfo.getInstance(filterInfo, null, null);
                //    PersonCollection personCollection2 = iPerson.getPersonCollection(entityViewInfo);
                //    StringBuilder sb = new StringBuilder();
                //    for (int i = 0; i < personCollection2.size(); i++) {
                //        PersonInfo personInfo = personCollection2.get(i);
                //        sb.append(personInfo.getId().toString()).append(",");
                //    }
                //    sb.deleteCharAt(sb.lastIndexOf(","));
                //    billId = sb.toString();
                //}

                logger.error("handleEnableWithTips----- >> ");
                batchMessageTipsHeader.setBillId(billId);
                batchMessageTipsHeader.setFailureCount(failure);
                batchMessageTipsHeader.setSuccessCount(sucess);
                logger.error("batchMessageTipsHeader  " + batchMessageTipsHeader.getSuccessCount());
                request.setAttribute("res_method_data", batchMessageTipsHeader);
                this.writeSuccessData(batchMessageTipsHeader);
                logger.error("handleEnableWithTips----- end ");

            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ShrWebBizException(e);
        }
    }
}
