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

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.org.*;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.cp.taskmng.util.StringUtil;
import com.kingdee.eas.custom.synctask.ISyncTranForIOTFacade;
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.org.web.handler.OrgUnitListHandler;
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 org.apache.log4j.Logger;
import org.springframework.ui.ModelMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

import org.apache.commons.lang3.StringUtils;

/**
 * @author qingwu
 * @date 2024/10/21
 * @apiNote
 */
public class OrgUnitListHandlerEx extends OrgUnitListHandler {
    Logger logger = Logger.getLogger(OrgUnitListHandlerEx.class);
    private Context ctx = SHRContext.getInstance().getContext();
    private Properties propt = new Properties();
    private static Map<String, Integer> personStatusMap = new HashMap<String, Integer>();

    static {
        personStatusMap.put("集团", 1);//集团
        personStatusMap.put("公司", 2);//公司
        personStatusMap.put("一级组织", 3);//一级组织  区域
        personStatusMap.put("二级组织", 4);//二级组织  分公司
        personStatusMap.put("三级组织", 5);//三级组织  子公司
        personStatusMap.put("四级组织", 6);//四级组织  管理
    }

    public OrgUnitListHandlerEx() throws BOSException {
        String syncOAConfigPath = System.getProperty("EAS_HOME") + "/server/properties/scy/syncIOTConfig.properties";
        try {
            propt.load(new FileInputStream(syncOAConfigPath));
        } catch (IOException e) {
            e.printStackTrace();
            String errorMsg = "获取配置文件报错，请检查配置：" + syncOAConfigPath + "   " + e.getMessage();
            throw new BOSException(errorMsg);
        }
    }

    /**
     * 获取组织批处理信息
     *
     * @param request
     * @param response
     * @param modelMap
     * @return
     */
    public void getAdminOrgBatchInfoAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws BOSException, ShrWebBizException {
        try {
            IAdminOrgUnit iAdminOrgUnit = AdminOrgUnitFactory.getLocalInstance(ctx);
            AdminOrgUnitCollection adminOrgUnitCollection = null;
            String ids = request.getParameter("ids");
            if (StringUtil.isEmpty(ids)) {
                adminOrgUnitCollection = iAdminOrgUnit.getAdminOrgUnitCollection();
            } 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);
                adminOrgUnitCollection = iAdminOrgUnit.getAdminOrgUnitCollection(entityViewInfo);
            }
            List list = new ArrayList();
            for (int i = 0; i < adminOrgUnitCollection.size(); i++) {
                AdminOrgUnitInfo adminOrgUnitInfo = adminOrgUnitCollection.get(i);
                list.add(adminOrgUnitInfo);
            }
            JSONUtils.SUCCESS(list);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ShrWebBizException(e);
        }
    }

    /**
     * 同步IOT平台
     *
     * @param request
     * @param response
     * @param modelMap
     * @return  后续如需部署生产去掉Ex
     */
    public Map syncOrgUnitToIotAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws BOSException, ShrWebBizException {
        try {
            String billds = request.getParameter("billIds");
            logger.error("_syncOrgUnitToOA---billds: " + billds);
            Set<String> adminOrgIds = null;
            if (StringUtils.isEmpty(billds)) {
                IAdminOrgUnit iAdminOrgUnit = AdminOrgUnitFactory.getLocalInstance(ctx);
                AdminOrgUnitCollection adminOrgUnitCollection = iAdminOrgUnit.getAdminOrgUnitCollection("select id ,name,number");
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < adminOrgUnitCollection.size(); i++) {
                    String adminOrgId = adminOrgUnitCollection.get(i).getId().toString();
                    sb.append(adminOrgId).append(",");
                }
                sb.deleteCharAt(sb.lastIndexOf(","));
                billds = sb.toString();
            }
            adminOrgIds = AtsUtil.toSet(billds);
            //部署测试环境需要注释此行
            ISyncTranForIOTFacade iSyncTranForIOTFacade = SyncTranForIOTFacadeFactory.getLocalInstance(ctx);
            Map<String, List<Map<String, String>>> result = iSyncTranForIOTFacade.syncOrgUnitToIot(billds);
            logger.error("result---" + result);
            List<Map<String, String>> list = result.get("data");
            int success = adminOrgIds.size();
            int failure = 0;
            BatchMessageTipsHeader batchMessageTipsHeader = new BatchMessageTipsHeader();
            if (list.size() > 0) {
                failure = list.size();
                for (int i = 0; i < list.size(); i++) {
                    BatchMessageTipsBody body = new BatchMessageTipsBody();
                    Map<String, String> map = list.get(i);
                    body.setId(map.get("id"));
                    body.setMuitTipsState(Boolean.FALSE);
                    body.setMuitTipsMessage(map.get("msg"));
                    batchMessageTipsHeader.addResult(body);
                }
                success -= list.size();
            }
            logger.error("handleEnableWithTips----- >> ");
            batchMessageTipsHeader.setBillId(billds);
            batchMessageTipsHeader.setFailureCount(failure);
            batchMessageTipsHeader.setSuccessCount(success);
            logger.error("batchMessageTipsHeader  " + batchMessageTipsHeader.getSuccessCount());
            request.setAttribute("res_method_data", batchMessageTipsHeader);
            this.writeSuccessData(batchMessageTipsHeader);
            logger.error("handleEnableWithTips----- end ");
        } catch (SHRWebException e) {
            e.printStackTrace();
            throw new ShrWebBizException(e);
        } catch (EASBizException e) {
            throw new ShrWebBizException(e);
        }
        return null;
    }




    /**
     * 同步OA部门
     *
     * @param request
     * @param response
     * @param modelMap
     * @throws BOSException
     * @throws EASBizException
     */
    public void syncOrgUnitToOAAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws BOSException, EASBizException, ShrWebBizException {
        String billIds = request.getParameter("billIds");
        //同步组织到OA
        //Map map = SyncTranForOAFacadeFactory.getLocalInstance(ctx).syncOrgUnitToOA(billIds, null);
        try {
            IAdminOrgUnit iAdminOrgUnit = AdminOrgUnitFactory.getLocalInstance(ctx);

            String billds = request.getParameter("billIds");
            logger.error("_syncOrgUnitToOA---billds: " + billds);
            Set<String> adminOrgIds = null;
            if (StringUtils.isEmpty(billds)) {
                AdminOrgUnitCollection adminOrgUnitCollection = iAdminOrgUnit.getAdminOrgUnitCollection("select id ,name,number");
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < adminOrgUnitCollection.size(); i++) {
                    String adminOrgId = adminOrgUnitCollection.get(i).getId().toString();
                    sb.append(adminOrgId).append(",");
                }
                sb.deleteCharAt(sb.lastIndexOf(","));
                billds = sb.toString();
            }
            adminOrgIds = AtsUtil.toSet(billds);
            Map<String, List<Map<String, String>>> result = SyncTranForOAFacadeFactory.getLocalInstance(ctx).syncOrgUnitToOA(billIds, null);
            if (result != null && !result.isEmpty()) {
                logger.error("handleEnableWithTips----- start ");
                logger.error("handleEnableWithTips----- billId-- " + billIds);
                AdminOrgUnitCollection adminOrgUnitCollection = iAdminOrgUnit.getAdminOrgUnitCollection("select id,number where id in (" + AtsUtil.getStrFromString(billds) + ")");
                int sucess = 0;
                int failure = 0;
                BatchMessageTipsHeader batchMessageTipsHeader = new BatchMessageTipsHeader();
                for (int i = 0; i < adminOrgUnitCollection.size(); i++) {
                    BatchMessageTipsBody body = new BatchMessageTipsBody();
                    AdminOrgUnitInfo adminOrgUnitInfo = adminOrgUnitCollection.get(i);
                    body.setId(adminOrgUnitInfo.getId().toString());
                    String adminOrgNumber = adminOrgUnitInfo.getNumber();
                    Map<String, String> map = (Map<String, String>) result.get(adminOrgNumber);
                    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);
                }

                logger.error("handleEnableWithTips----- >> ");
                batchMessageTipsHeader.setBillId(billds);
                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 (SHRWebException e) {
            e.printStackTrace();
            throw new ShrWebBizException(e);
        }

    }
}
