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

import com.alibaba.fastjson.JSONObject;
import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.eas.basedata.person.PersonInfo;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.custom.log.ISyncLog;
import com.kingdee.eas.custom.log.SyncLogFactory;
import com.kingdee.eas.custom.log.SyncLogInfo;
import com.kingdee.eas.custom.log.app.DataDirectionEnum;
import com.kingdee.eas.custom.log.app.SyncEntityNameEnum;
import com.kingdee.eas.custom.log.app.SyncStatusEnum;
import com.kingdee.eas.hr.affair.IResignBizBillEntry;
import com.kingdee.eas.hr.affair.ResignBizBillEntryCollection;
import com.kingdee.eas.hr.affair.ResignBizBillEntryFactory;
import com.kingdee.eas.hr.affair.ResignBizBillEntryInfo;
import okhttp3.*;
import org.apache.log4j.Logger;

import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

/**
 * @author qingwu
 * @date 2025/2/26
 * @apiNote
 */
public class GeneralUtils {
    private Properties propt = new Properties();
    Logger logger = Logger.getLogger("com.kingdee.eas.custom.synctask.utils.GeneralUtils");
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    public GeneralUtils() 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);
        }
    }

    public void disableUserAccount(Context ctx, PersonInfo personInfo) throws IOException, BOSException, EASBizException {
        logger.error("disableUserAccount----new");
        //日志
        ISyncLog iSyncLog = SyncLogFactory.getLocalInstance(ctx);
        SyncLogInfo syncLogInfo = new SyncLogInfo();
        syncLogInfo.setEntityName(SyncEntityNameEnum.person);
        syncLogInfo.setDataDirection(DataDirectionEnum.outflow);
        JSONObject param = new JSONObject();//请求参数
        //员工ID
        String personId = personInfo.getId().toString();
        //通过员工id获取离职当分录  预计离职日期  最后工作日  禁用用户日期 用户账号
        IResignBizBillEntry iResignBizBillEntry = ResignBizBillEntryFactory.getLocalInstance(ctx);
        ResignBizBillEntryCollection resignBizBillEntryCollection = iResignBizBillEntry.getResignBizBillEntryCollection("where person = '" + personId + "'");
        //判断该人员是否存在离职单
        if (resignBizBillEntryCollection.size() > 0) {
            ResignBizBillEntryInfo resignBizBillEntryInfo = resignBizBillEntryCollection.get(0);
            Date expectedDate = (Date) resignBizBillEntryInfo.get("expectedDate");//预计离职日期
            Date leftCompanyDate = resignBizBillEntryInfo.getLeftCompanyDate();//最后工作日
            Date forbidUserDate = resignBizBillEntryInfo.getForbidUserDate();//禁用用户日期
            if (expectedDate != null) {
                String estimatedLeaveDate = sdf.format(expectedDate);
                logger.error("estimatedLeaveDate--" + estimatedLeaveDate);
                param.put("estimatedLeaveDate", estimatedLeaveDate);
            }
            if (leftCompanyDate != null) {
                String lastWorkingDay = sdf.format(leftCompanyDate);
                logger.error("lastWorkingDay--" + lastWorkingDay);
                param.put("lastWorkingDay", lastWorkingDay);
            }
            if (forbidUserDate != null) {
                String disableUserDate = sdf.format(forbidUserDate);
                logger.error("disableUserDate--" + disableUserDate);
                param.put("disableUserDate", disableUserDate);
            }
            param.put("userAccount", personInfo.getNumber());
            logger.error("param" + param);
            syncLogInfo.setRequestParams(param.toString());//请求参数
            //请求接口  禁用用户
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(30, TimeUnit.SECONDS)
                    .writeTimeout(30, TimeUnit.SECONDS)
                    .readTimeout(30, TimeUnit.SECONDS)
                    .build();
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, param.toString());
            Request request = new Request.Builder()
                    .url(propt.getProperty("disableUserAccountUrl"))
                    .post(body)
                    .addHeader("Accept", "*/*")
                    .addHeader("Accept-Encoding", "gzip, deflate, br")
                    .addHeader("User-Agent", "PostmanRuntime-ApipostRuntime/1.1.0")
                    .addHeader("Connection", "keep-alive")
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = client.newCall(request).execute();
            String result = response.body().string();
            if (response.isSuccessful()) {
                JSONObject jsonObject = JSONObject.parseObject(result);
                logger.error("jsonObject" + jsonObject);
                if (jsonObject.get("code").equals("200")) {
                    syncLogInfo.setSyncStatus(SyncStatusEnum.SUCCESS);
                    syncLogInfo.setSuccessNum(1);
                    syncLogInfo.setSyncResult(result);
                    iSyncLog.save(syncLogInfo);
                } else {
                    syncLogInfo.setSyncStatus(SyncStatusEnum.ERROR);
                    syncLogInfo.setFailNum(1);
                    syncLogInfo.setSyncResult(result);
                    iSyncLog.save(syncLogInfo);
                }
            } else {
                syncLogInfo.setSyncStatus(SyncStatusEnum.ERROR);
                syncLogInfo.setFailNum(1);
                syncLogInfo.setSyncResult(result);
                iSyncLog.save(syncLogInfo);
            }
        }

    }
}
