package com.kingdee.eas.custom.beisen.synchronouspos.handler;

import com.google.common.collect.Maps;
import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.eas.framework.util.ExceptionMessageUtility;
import com.kingdee.eas.hr.base.util.IntegratedPatternCheckUtil;
import com.kingdee.eas.hr.org.IPositionOptFacade;
import com.kingdee.eas.hr.org.OrgnizationBizException;
import com.kingdee.eas.hr.org.PositionOptFacadeFactory;
import com.kingdee.eas.hr.org.util.OrgAdjLockManager;
import com.kingdee.eas.hr.org.util.OrgUtils;
import com.kingdee.shr.base.syssetting.MSFServiceFacadeFactory;
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.ml.SHRWebResource;
import com.kingdee.util.StringUtils;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * description: PositionListHandlerEx <br>
 * date: 2025/7/18 10:07 <br>
 * author: lhbj <br>
 * version: 1.0 <br>
 */
public class PositionListHandlerEx extends com.kingdee.eas.hr.org.web.handler.PositionListHandler {
    private String multilingual(String key) {
        return SHRWebResource.getString("com.kingdee.eas.hr.org.OrganisationBizResource", key);
    }

    private void batchOperationV0(String opType, String billIds) throws SHRWebException {
        Context ctx = SHRContext.getInstance().getContext();
        IPositionOptFacade iPositionOpt = null;

        try {
            iPositionOpt = PositionOptFacadeFactory.getRemoteInstance();
        } catch (BOSException var14) {
            var14.printStackTrace();
            throw new ShrWebBizException(new OrgnizationBizException(OrgnizationBizException.PLEASE_CONTACT_ADMIN));
        }

        int successCount = 0;
        int errorCount = 0;
        BatchMessageTipsHeader batchMessageTipsHeader = new BatchMessageTipsHeader();
        if (billIds.length() > 0) {
            String sortType = "asc";
            if ("disable".equals(opType) || "delete".equals(opType)) {
                sortType = "desc";
            }

            String[] ids = OrgUtils.sortIdByLongnumber(billIds, sortType, ctx);
            int i = 0;

            for(int size = ids.length; i < size; ++i) {
                BatchMessageTipsBody body = new BatchMessageTipsBody();
                body.setId(ids[i]);

                try {
                    OrgAdjLockManager.checkIfOrgLocked(ctx, (String)null, ids[i]);
                    if ("disable".equals(opType)) {
                        iPositionOpt.disable(ids[i]);
                    } else if ("enable".equals(opType)) {
                        iPositionOpt.enable(ids[i]);
                    } else if ("delete".equals(opType)) {
                        iPositionOpt.delete(ids[i]);
                    } else if ("showInOrgChart".equals(opType)) {
                        iPositionOpt.showInOrgChart(ids[i]);
                    } else {
                        if (!"notShowInOrgChart".equals(opType)) {
                            throw new ShrWebBizException(new OrgnizationBizException(OrgnizationBizException.NOT_SUPPORT_OPT));
                        }

                        iPositionOpt.notShowInOrgChart(ids[i]);
                    }

                    body.setMuitTipsState(Boolean.TRUE);
                    body.setMuitTipsMessage(this.multilingual("OperationSuccess"));
                    ++successCount;
                } catch (Exception var15) {
                    var15.printStackTrace();
                    body.setMuitTipsState(Boolean.FALSE);
                    body.setMuitTipsMessage("" + SHRWebResource.getString("com.kingdee.eas.hr.base.BaseBizResourse", "Operation_failed") + ":" + this.translateErrorMsg(var15.getMessage()));
                    ++errorCount;
                    batchMessageTipsHeader.addResult(body);
                    continue;
                }

                batchMessageTipsHeader.addResult(body);
            }
        }

        batchMessageTipsHeader.setBillId(billIds);
        batchMessageTipsHeader.setFailureCount(errorCount);
        batchMessageTipsHeader.setSuccessCount(successCount);
       // this.writeSuccessData(batchMessageTipsHeader);
    }
    public void deletePositionAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws SHRWebException {
        String billIds = this.getPosBillId(request);
        Context ctx = SHRContext.getInstance().getContext();
        try {
            this.batchOperationV0("disable", billIds);
            IntegratedPatternCheckUtil.checkIsShr2Cloud(ctx, SHRWebResource.getString("com.kingdee.eas.hr.org.OrganisationBizResource", "Position"));
        } catch (Exception var8) {
            var8.printStackTrace();
            String errorMessage = ExceptionMessageUtility.getMessage(var8);
            throw new ShrWebBizException(errorMessage, var8);
        }
        try {
            BatchMessageTipsHeader batchMessageTipsHeader = new BatchMessageTipsHeader();
            this.syncEnable(billIds, ctx, batchMessageTipsHeader);
        } catch (Exception var8) {
            var8.printStackTrace();
            String errorMessage = ExceptionMessageUtility.getMessage(var8);
            throw new ShrWebBizException(errorMessage, var8);
        }
        super.deletePositionAction(request, response, modelMap);
    }

    public BatchMessageTipsHeader syncEnable(String billIds, Context ctx,
                                             BatchMessageTipsHeader batchMessageTipsHeader) throws SHRWebException {
        int successCount = 0;
        int errorCount = 0;
        if (billIds.length() > 0) {
            String[] ids = billIds.split(",");
            int i = 0;

            for (int size = ids.length; i < size; ++i) {
                BatchMessageTipsBody body = new BatchMessageTipsBody();
                body.setId(ids[i]);
                try {
                    Map<String, Object> map = Maps.newHashMap();
                    map.put("posId", ids[i]);
                    if (org.apache.commons.lang3.StringUtils.isNotBlank(billIds)) {
                        Object obj = MSFServiceFacadeFactory.getLocalInstance(ctx).processService("synchronousPosOSF", map);
                        body.setMuitTipsState(Boolean.TRUE);
                        body.setMuitTipsMessage(obj.toString());
                        ++successCount;
                    }
                } catch (Exception var15) {
                    var15.printStackTrace();
                    body.setMuitTipsState(Boolean.FALSE);
                    body.setMuitTipsMessage("" + SHRWebResource.getString("com.kingdee.eas.hr.base.BaseBizResourse", "Operation_failed") + ":" + this.translateErrorMsg(var15.getMessage()));
                    ++errorCount;
                    batchMessageTipsHeader.addResult(body);
                    continue;
                }
                batchMessageTipsHeader.addResult(body);
            }
        }
        batchMessageTipsHeader.setBillId(billIds);
        batchMessageTipsHeader.setFailureCount(errorCount);
        batchMessageTipsHeader.setSuccessCount(successCount);
        return batchMessageTipsHeader;
    }

    @RequestMapping(
            params = {"method=syncEnable"}
    )
    public String syncEnableAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws SHRWebException {
        String billIds = this.getPosBillId(request);

        Object obj = null;
        try {
            Context ctx = SHRContext.getInstance().getContext();
            BatchMessageTipsHeader batchMessageTipsHeader = new BatchMessageTipsHeader();
            batchMessageTipsHeader = this.syncEnable(billIds,ctx,batchMessageTipsHeader);
            this.writeSuccessData(batchMessageTipsHeader);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private String translateErrorMsg(String msg) {
        if ("POS_NAME_DUPLICATE".equals(msg)) {
            msg = this.multilingual("ExistEnabledSameNamePositonUnderOneAdminOrg");
        } else if ("EXIST_PRE_POSITION".equals(msg)) {
            msg = this.multilingual("CannotEnableLowerPositionBecauseSuperiorPositionForbiddenStatus");
        } else if (msg != null && msg.indexOf(this.multilingual("DataAlreadyQuotedOperationFailed")) > 0) {
            msg = this.multilingual("DataAlreadyQuotedOperationFailed");
        }

        return msg;
    }

    private String getPosBillId(HttpServletRequest request) throws ShrWebBizException {
        String billId = "";

        try {
            billId = super.getBillId(request);
        } catch (SHRWebException var4) {
            var4.printStackTrace();
        }

        if (StringUtils.isEmpty(billId)) {
            throw new ShrWebBizException(new OrgnizationBizException(OrgnizationBizException.NO_FIND_BILLID));
        } else {
            return billId;
        }
    }

}
