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

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.dao.IObjectCollection;
import com.kingdee.bos.dao.IObjectValue;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.bos.dao.query.BizEnumValueDTO;
import com.kingdee.bos.util.BOSUuid;
import com.kingdee.eas.basedata.org.OrgUnitInfo;
import com.kingdee.eas.basedata.person.PersonFactory;
import com.kingdee.eas.basedata.person.PersonInfo;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.custom.beisen.synchronousorg.SynchronousEmpBillFactory;
import com.kingdee.eas.custom.beisen.syncperson.SyncPersonToBeisenFacadeFactory;
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.json.adapter.*;
import com.kingdee.shr.base.syssetting.web.json.adapter.BOSUuidTypeAdapter;
import com.kingdee.util.StringUtils;
import com.kingdee.util.enums.Enum;
import org.springframework.ui.ModelMap;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.util.Date;

/**
 * @author 青梧
 * @version 1.0
 * @description: EmployeeListHandlerEx
 * @date 2025/7/23 14:40
 */
public class EmployeeListHandlerEx extends EmployeeListHandler {
    /**
     * 同步人员至北森
     *
     * @param request
     * @param response
     * @param modelMap
     * @throws SHRWebException
     */
    public void syncPersonToBeisenAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws SHRWebException {
        Context ctx = SHRContext.getInstance().getContext();
        String billId = getBillId(request);
        try {
            SyncPersonToBeisenFacadeFactory.getLocalInstance(ctx).syncPerson(billId, 0);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ShrWebBizException(e);
        }
    }

    /**
     * 同步北森人员信息
     *
     * @param request
     * @param response
     * @param modelMap
     * @return
     * @throws SHRWebException
     */
    public String synBeiSenPersonAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws SHRWebException {
        Context ctx = SHRContext.getInstance().getContext();
        BatchMessageTipsHeader batchMessageTipsHeader = new BatchMessageTipsHeader();
        String ids = request.getParameter("ids");
        System.out.println("==========ids："+ids);
        int sucess = 0;
        int failure = 0;
        if (ids != null && ids.length() > 0) {
            String[] personArray = ids.split(",");
            for (int i = 0; i < personArray.length; i++) {
                BatchMessageTipsBody body = new BatchMessageTipsBody();
                try {
                    PersonInfo personInfo = PersonFactory.getLocalInstance(ctx).getPersonInfo(new ObjectUuidPK(personArray[i]));
                    String beisenid = personInfo.getString("beisenid");
                    System.out.println("==========beisenid："+beisenid);
                    if (beisenid!=null&&beisenid.length()>0){
                        try {
                            String string = personInfo.getString("IsSync");
                            if (string==null||string.equals("0")){
                                String s = SynchronousEmpBillFactory.getLocalInstance(ctx).empBill(beisenid, "002", "asdasdasdasdasdasd");
                                System.out.println("==========s："+s);
                                body.setId(personArray[i]);
                                body.setMuitTipsState(true);
                                body.setMuitTipsMessage("同步成功【" +personInfo.getName() + "】");
                                batchMessageTipsHeader.addResult(body);
                                sucess++;
                            }else {
                                body.setId(personArray[i]);
                                body.setMuitTipsState(true);
                                body.setMuitTipsMessage("已经同步过该数据【" + personInfo.getName() + "】");
                                batchMessageTipsHeader.addResult(body);
                                sucess++;
                            }

                        }catch (Exception e){
                            System.out.println("==========personArray[i]1："+personArray[i]);
                            body.setId(personArray[i]);
                            body.setMuitTipsState(false);
                            body.setMuitTipsMessage("后台事务执行失败【" + personArray[i] + "】");
                            batchMessageTipsHeader.addResult(body);
                            e.printStackTrace();
                            failure++;
                        }
                    }else {
                        failure++;
                        System.out.println("==========personArray[i]2："+personArray[i]);
                        body.setId(personArray[i]);
                        body.setMuitTipsState(false);
                        body.setMuitTipsMessage("未查询到北森入职单id【" +personInfo.getName() + "】");
                        batchMessageTipsHeader.addResult(body);
                    }
                } catch (BOSException e) {
                    System.out.println("==========personArray[i]3："+personArray[i]);
                    body.setId(personArray[i]);
                    body.setMuitTipsState(false);
                    body.setMuitTipsMessage("同步失败查询员工失败【" + personArray[i] + "】");
                    batchMessageTipsHeader.addResult(body);
                    e.printStackTrace();
                } catch (EASBizException e) {
                    System.out.println("==========personArray[i]4："+personArray[i]);
                    body.setId(personArray[i]);
                    body.setMuitTipsState(false);
                    body.setMuitTipsMessage("同步失败查询员工失败【" + personArray[i] + "】");
                    batchMessageTipsHeader.addResult(body);
                    e.printStackTrace();
                }
            }
        }
        batchMessageTipsHeader.setBillId(ids);
        batchMessageTipsHeader.setFailureCount(failure);
        batchMessageTipsHeader.setSuccessCount(sucess);
        System.out.println("=========batchMessageTipsHeader："+batchMessageTipsHeader.toString());
        SUCCESS(batchMessageTipsHeader,request,response,"application/json;charset=UTF-8",ctx);
        return null;
    }
    public static void SUCCESS(Object object,ServletRequest request, ServletResponse response, String contentType,Context context) throws SHRWebException {
        response.setContentType(contentType);

        PrintWriter pw;
        try {
            pw = response.getWriter();
        } catch (IOException var7) {
            throw new SHRWebException("can't open the output stream!");
        }

        StringBuilder strSuccessJson = new StringBuilder();
        strSuccessJson.append("{");
        strSuccessJson.append("\"result\":\"");
        strSuccessJson.append("success");
        strSuccessJson.append("\",\"data\":");
        strSuccessJson.append(convertObjectToJson(context, object).toString());
        String successMessage = (String)request.getAttribute("successMessage");
        if (!StringUtils.isEmpty(successMessage)) {
            strSuccessJson.append(",\"successMessage\":\"");
            strSuccessJson.append(successMessage);
            strSuccessJson.append("\"");
        }

        strSuccessJson.append("}");
        pw.flush();
        pw.write(strSuccessJson.toString());
        pw.flush();
    }
    public static String convertObjectToJson(Context ctx, Object object) {
        if (object != null && !object.equals("")) {
            Gson gson = getGson(ctx);
            String result = gson.toJson(object);
            if (result == null) {
                return "\"\"";
            } else {
                result = processJsonResult(result);
                return result;
            }
        } else {
            return "\"\"";
        }
    }
    public static Gson getGson(Context ctx) {
        GsonBuilder builder = new GsonBuilder();
        builder.serializeNulls();
        builder.disableHtmlEscaping();
        builder.serializeSpecialFloatingPointValues();
        builder.registerTypeHierarchyAdapter(Date.class, new DateTypeAdapter());
        builder.registerTypeHierarchyAdapter(Timestamp.class, new DateTypeAdapter());
        builder.registerTypeHierarchyAdapter(BOSUuid.class, new BOSUuidTypeAdapter());
        builder.registerTypeHierarchyAdapter(IObjectValue.class, new BosObjectTypeAdapter(ctx));
        builder.registerTypeHierarchyAdapter(IObjectCollection.class, new BosObjectCollectionTypeAdapter(ctx));
        builder.registerTypeHierarchyAdapter(OrgUnitInfo.class, new BosObjectTypeAdapter(ctx));
        builder.registerTypeHierarchyAdapter(BizEnumValueDTO.class, new BizEnumAdapter());
        builder.registerTypeHierarchyAdapter(Enum.class, new EnumTypeAdapter());
        return builder.create();
    }
    public static String processJsonResult(String result) {
        result = result.replace("${quote_2312415321232}", "\"");
        result = result.replace("\"${leftbracket_2312415321232}", "{");
        result = result.replace("${leftbracket_2312415321232}", "{");
        result = result.replace("${rightbracket_2312415321232}\"", "}");
        result = result.replace("${rightbracket_2312415321232}", "}");
        return result;
    }
}
