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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kingdee.bos.metadata.data.SortType;
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.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 com.kingdee.eas.hr.ats.AtsUtil;
import com.kingdee.eas.hr.base.*;
import com.kingdee.eas.hr.emp.IPersonPosition;
import com.kingdee.eas.hr.emp.PersonPositionCollection;
import com.kingdee.eas.hr.emp.PersonPositionFactory;
import com.kingdee.eas.hr.emp.PersonPositionInfo;
import com.kingdee.eas.scm.util.datetime.DateTimeUtil;
import com.kingdee.ws.ca.utils.StringUtils;
import oadd.org.apache.commons.codec.digest.DigestUtils;
import okhttp3.*;
import org.apache.log4j.Logger;

import javax.ejb.*;
import java.io.FileInputStream;
import java.io.IOException;
import java.rmi.RemoteException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.TimeUnit;

import com.kingdee.bos.*;
import com.kingdee.bos.util.BOSObjectType;
import com.kingdee.bos.metadata.IMetaDataPK;
import com.kingdee.bos.metadata.rule.RuleExecutor;
import com.kingdee.bos.metadata.MetaDataPK;
//import com.kingdee.bos.metadata.entity.EntityViewInfo;
import com.kingdee.bos.framework.ejb.AbstractEntityControllerBean;
import com.kingdee.bos.framework.ejb.AbstractBizControllerBean;
//import com.kingdee.bos.dao.IObjectPK;
import com.kingdee.bos.dao.IObjectValue;
import com.kingdee.bos.dao.IObjectCollection;
import com.kingdee.bos.service.ServiceContext;
import com.kingdee.bos.service.IServiceContext;


public class SynPersonToPunchCardFacadeControllerBean extends AbstractSynPersonToPunchCardFacadeControllerBean {
    private static Logger logger =
            Logger.getLogger("com.kingdee.eas.custom.synctask.task.SynPersonToPunchCardFacadeControllerBean");
    private volatile Properties propt;  // 使用 volatile 保证可见性
    private final Object configLock = new Object();
    private static final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(30, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .build();

    private void loadProperties() throws BOSException {
        if (propt == null) {  // 第一次检查
            synchronized (configLock) {
                if (propt == null) {  // 第二次检查（双重检查锁）
                    Properties temp = new Properties();
                    String path = System.getProperty("EAS_HOME") + "/server/properties/abk/syncAtsConfig.properties";
                    try (FileInputStream fis = new FileInputStream(path)) {  // try-with-resources 自动关闭流
                        temp.load(fis);
                        propt = temp;  // 原子性赋值
                    } catch (IOException e) {
                        String errorMsg = "加载配置文件失败: " + path + " | " + e.getMessage();
                        logger.error(errorMsg, e);  // 使用日志记录代替 e.printStackTrace()
                        throw new BOSException(errorMsg);
                    }
                }
            }
        }
    }


    /**
     * 人员离职
     *
     * @param ctx
     * @throws BOSException
     * @throws EASBizException
     */
    @Override
    protected void _dimissionPerson(Context ctx, String personNumbers) throws BOSException, EASBizException {
        logger.error("_dimissionPerson--");
        loadProperties();
        IPersonPosition iPersonPosition = PersonPositionFactory.getLocalInstance(ctx);
        //离职单
        SelectorItemCollection sic = getSic();
        FilterInfo filterInfo = new FilterInfo();
        if (personNumbers.equals(null) || personNumbers.equals("")) {
            throw new BOSException("同步人员编码不能为空！！");
        }
        filterInfo.getFilterItems().add(new FilterItemInfo("person.number", AtsUtil.toSet(personNumbers), CompareType.INCLUDE));
        EntityViewInfo entityViewInfo = EntityViewInfo.getInstance(filterInfo, sic, null);
        PersonPositionCollection personPositionCollection = iPersonPosition.getPersonPositionCollection(entityViewInfo);
        if (personPositionCollection.size() <= 1) {
            logger.error("personPositionCollection--" + personPositionCollection.size());
            List<PersonPositionInfo> PersonPositionList = new ArrayList();
            for (int i = 0; i < personPositionCollection.size(); i++) {
                PersonPositionList.add(personPositionCollection.get(i));
            }
            logger.error("PersonPositionList--" + PersonPositionList.size());
            JSONArray msgArray = new JSONArray();
            Map messageMap = null;
            if (PersonPositionList.size() > 180) {
                List<PersonPositionCollection> objects = splitList(PersonPositionList, 180);
                for (int i = 0; i < objects.size(); i++) {
                    PersonPositionCollection coll = objects.get(i);
                    personDelete(ctx, coll);
                }
            } else {
                personDelete(ctx, personPositionCollection);
                msgArray.add(messageMap);
            }
        }
    }

    /**
     * 人员删除
     *
     * @param ctx
     * @param personPositionCollection
     * @throws BOSException
     */
    public void personDelete(Context ctx, PersonPositionCollection personPositionCollection) throws BOSException {
        logger.error("personDelete--");
        //离职单
        IResignBizBillEntry iResignBizBillEntry = ResignBizBillEntryFactory.getLocalInstance(ctx);
        for (int i = 0; i < personPositionCollection.size(); i++) {
            PersonPositionInfo personPositionInfo = personPositionCollection.get(i);
            PersonInfo person = personPositionInfo.getPerson();
            EmployeeTypeInfo employeeType = person.getEmployeeType();
            //判断是否是离职人员
            String number = employeeType.getNumber();
            logger.error("person--" + person.getName() + "--employeeType--" + number);
            if (number.equals("010") || number.equals("009") || number.equals("S09")) {
                //人员离职
                JSONObject result = synLeavePerson(iResignBizBillEntry, person);
                logger.error("personDelete--" + result);
            }
        }
    }

    /**
     * 人员恢复 再入职
     *
     * @param ctx
     * @throws BOSException
     * @throws EASBizException
     */
    @Override
    protected void _recoverPerson(Context ctx, int offSet) throws BOSException, EASBizException {
        logger.error("_recoverPerson--");
        loadProperties();
        String dayBefore = getDayBefore(new Date(), offSet);
        logger.error("_recoverPerson--dayBefore--" + dayBefore);
        //员工变动记录
        IEmpPosOrgRelation iEmpPosOrgRelation = EmpPosOrgRelationFactory.getLocalInstance(ctx);
        Set personSet = getPersonDateByDate(ctx, dayBefore);
        logger.error("_recoverPerson--personSet--" + dayBefore);
        //查询字段
        SelectorItemCollection sic = new SelectorItemCollection();
        sic.add("id");
        sic.add("number");
        sic.add("person.id");
        sic.add("person.number");
        sic.add("action.id");
        sic.add("action.number");

        //过滤条件
        FilterInfo filterInfo = new FilterInfo();
        FilterItemCollection filterItems = filterInfo.getFilterItems();
        filterItems.add(new FilterItemInfo("person", personSet, CompareType.INCLUDE));

        //排序条件
        SorterItemCollection sorter = new SorterItemCollection();
        SorterItemInfo sorterItem = new SorterItemInfo("createTime");
        sorterItem.setSortType(SortType.DESCEND);
        sorter.add(sorterItem);

        EntityViewInfo entityViewInfo = EntityViewInfo.getInstance(filterInfo, sic, sorter);
        //查询变动记录是否存在在入职
        JSONArray personNumber = new JSONArray();
        EmpPosOrgRelationCollection empPosOrgRelationCollection = iEmpPosOrgRelation.getEmpPosOrgRelationCollection(entityViewInfo);
        for (int i = 0; i < empPosOrgRelationCollection.size(); i++) {
            EmpPosOrgRelationInfo empPosOrgRelationInfo = empPosOrgRelationCollection.get(i);
            //变动操作编码
            String actionNumebr = empPosOrgRelationInfo.getAction().getNumber();
            //变动操作等于在入职 则执行人员恢复操作
            if (actionNumebr.equals("SHR02")) {
                personNumber.add(empPosOrgRelationInfo.getPerson().getNumber());
            }
        }
        logger.error("personNumber--" + personNumber);
        if (personNumber.size() > 0) {
            JSONObject params = new JSONObject();
            params.put("userpin", personNumber); //人员编号
            Map<String, String> queryParams = getToken();
            // 调用接口
            String urlPath = propt.getProperty("recoverUrlPath");
            String result = sendPostRequest(urlPath, params, queryParams);
            logger.error("result--" + result);
        }


    }

    /**
     * 人员恢复-反审批
     *
     * @param ctx
     * @param offSet
     * @param personNumber
     * @throws BOSException
     */
    @Override
    protected void _synRecoverPerson(
            Context ctx,
            int offSet,
            String personNumber
    ) throws BOSException {
        super._synRecoverPerson(ctx, offSet, personNumber);
        logger.error("_synRecoverPerson--");
        loadProperties();
        String dayBefore = getDayBefore(new Date(), offSet);
        logger.error("_recoverPerson--dayBefore--" + dayBefore);
        //员工
        IPerson iPerson = PersonFactory.getLocalInstance(ctx);
        FilterInfo filterInfo = new FilterInfo();
        FilterItemCollection filterItems = filterInfo.getFilterItems();
        if (!StringUtils.isEmpty(personNumber)) {
            filterItems.add(new FilterItemInfo("number", AtsUtil.toSet(personNumber), CompareType.INCLUDE));
        } else {
            filterItems.add(new FilterItemInfo("hireDate", dayBefore, CompareType.GREATER_EQUALS));
            filterItems.add(new FilterItemInfo("hireDate", new Date(), CompareType.LESS_EQUALS));
        }
        SelectorItemCollection sic = new SelectorItemCollection();
        sic.add("number");
        sic.add("name");
        sic.add("id");
        sic.add("hireDate");
        sic.add("nCell");
        sic.add("gender");
        sic.add("email");
        sic.add("employeeType.number");
        sic.add("employeeType.id");
        EntityViewInfo entityViewInfo = EntityViewInfo.getInstance(filterInfo, sic, null);
        logger.error("filterInfo--" + filterInfo.toSql());
        //获取时间段的人员
        PersonCollection personCollection = iPerson.getPersonCollection(entityViewInfo);
        logger.error("personCollection--" + personCollection.size());
        JSONObject personNumberAll = getPersonNumberAll();
        logger.error("personNumberAll--" + personNumberAll);
        if (personNumberAll.size() > 0) {
            //中控不存在的人员，
            JSONArray notExistArray = new JSONArray();
            if (personCollection.size() > 0) {
                for (int i = 0; i < personCollection.size(); i++) {
                    PersonInfo personInfo = personCollection.get(i);
                    String name = personInfo.getName();
                    String perNumber = personInfo.getNumber();
                    String number = personInfo.getEmployeeType().getNumber();
                    //对shr在职人员进行人员恢复
                    if (!"010".equals(number) && !"009".equals(number) && !"S09".equals(number)) {
                        //判断中控是否存在该人员
                        if (!personNumberAll.containsKey(perNumber)) {
                            notExistArray.add(perNumber);
                        }
                    }
                }
                if (notExistArray.size() > 0) {
                    logger.error("notExistArray--" + notExistArray.size());
                    //对查询到中控人员 进行人员恢复操作
                    JSONObject params = new JSONObject();
                    params.put("userpin", notExistArray); //人员编号
                    Map<String, String> queryParams = getToken();
                    // 调用接口
                    String urlPath = propt.getProperty("recoverUrlPath");
                    String result = sendPostRequest(urlPath, params, queryParams);
                    logger.error("result--" + result);
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    //判断是否存在总控不存在的人员
                    if (jsonObject.containsKey("error_list")) {
                        JSONArray errorList = jsonObject.getJSONArray("error_list");
                        StringBuilder personNumbers = new StringBuilder();
                        for (int i = 0; i < errorList.size(); i++) {
                            Object number = errorList.get(i);
                            personNumbers.append(number).append(",");
                        }
                        personNumbers.deleteCharAt(personNumbers.lastIndexOf(","));
                        logger.error("personNumbers--" + personNumbers);
                        try {
                            //调用人员更新接口
                            updatePerson(ctx, personNumbers.toString());
                        } catch (EASBizException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        }
    }

    /**
     * 获取所有中控人员
     *
     * @return
     */
    public JSONObject getPersonNumberAll() {
        JSONObject jsonObject = new JSONObject();
        Map<String, String> queryParams = getToken();
        // 调用接口
        String urlPath = propt.getProperty("employeeUrlPath");
        logger.error("getPersonNumberAll--urlPath---" + urlPath);
        String response = sendPostRequest(urlPath, queryParams);
        JSONObject result = JSONObject.parseObject(response);
        logger.error("getPersonNumberAll--result---" + result);
        Integer ret = result.getInteger("ret");
        if (ret == 0) {
            JSONObject data = result.getJSONObject("data");
            String count = data.containsKey("count") ? data.getString("count") : "";
            logger.error("getPersonNumberAll--count---" + count);
            JSONArray items = data.getJSONArray("items");
            for (int i = 0; i < items.size(); i++) {
                JSONObject item = items.getJSONObject(i);
                String pin = item.getString("pin");
                String name = item.getString("name");
                jsonObject.put(pin, name);
            }
            return jsonObject;
        }
        return new JSONObject();
    }

    /**
     * 获取时间内的人员ID
     *
     * @param ctx
     * @param dayBefore
     * @throws BOSException
     */
    private Set getPersonDateByDate(Context ctx, String dayBefore) throws BOSException {
        //员工
        IPerson iPerson = PersonFactory.getLocalInstance(ctx);
        FilterInfo filterInfo = new FilterInfo();
        FilterItemCollection filterItems = filterInfo.getFilterItems();
        filterItems.add(new FilterItemInfo("hireDate", dayBefore, CompareType.GREATER_EQUALS));
        filterItems.add(new FilterItemInfo("hireDate", new Date(), CompareType.LESS_EQUALS));
        EntityViewInfo entityViewInfo = EntityViewInfo.getInstance(filterInfo, null, null);
        logger.error("filterInfo--" + filterInfo.toSql());
        //获取时间段的人员
        PersonCollection personCollection = iPerson.getPersonCollection(entityViewInfo);
        logger.error("personCollection--" + personCollection.size());
        Set personSet = new HashSet();
        for (int i = 0; i < personCollection.size(); i++) {
            PersonInfo personInfo = personCollection.get(i);
            personSet.add(personInfo.getId());
        }
        return personSet;
    }

    /**
     * 往前推多少天
     *
     * @param specifiedDay
     * @param x
     * @return
     */
    public String getDayBefore(Date specifiedDay, int x) {
        Calendar c = Calendar.getInstance();
        Date date = specifiedDay;
        c.setTime(date);
        int day = c.get(Calendar.DATE);
        c.set(Calendar.DATE, day - x);    //往前推几天
        //c.set(Calendar.DATE, day + x);  往后推几天

        String dayBefore = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
        //System.out.println(dayBefore);
        return dayBefore;
    }

    /**
     * 同步人员
     *
     * @param ctx
     * @param personNumbers
     * @throws BOSException
     * @throws EASBizException
     */
    @Override
    protected void _updatePerson(Context ctx, String personNumbers) throws BOSException, EASBizException {
        logger.error("_updatePerson--");
        loadProperties();
        IPersonPosition iPersonPosition = PersonPositionFactory.getLocalInstance(ctx);
        //离职单
        SelectorItemCollection sic = getSic();
        FilterInfo filterInfo = new FilterInfo();
        if (personNumbers.equals(null) || personNumbers.equals("")) {
            throw new BOSException("同步人员编码不能为空！！");
        }
        filterInfo.getFilterItems().add(new FilterItemInfo("person.number", AtsUtil.toSet(personNumbers), CompareType.INCLUDE));
        EntityViewInfo entityViewInfo = EntityViewInfo.getInstance(filterInfo, sic, null);
        PersonPositionCollection personPositionCollection = iPersonPosition.getPersonPositionCollection(entityViewInfo);
        logger.error("personPositionCollection--" + personPositionCollection.size());
        List<PersonPositionInfo> PersonPositionList = new ArrayList();
        for (int i = 0; i < personPositionCollection.size(); i++) {
            PersonPositionInfo personPositionInfo = personPositionCollection.get(i);
            PersonPositionList.add(personPositionInfo);
        }
        logger.error("PersonPositionList--" + PersonPositionList.size());
        JSONArray msgArray = new JSONArray();
        Map messageMap = null;
        if (PersonPositionList.size() > 180) {
            List<PersonPositionCollection> objects = splitList(PersonPositionList, 180);
            for (int i = 0; i < objects.size(); i++) {
                PersonPositionCollection coll = objects.get(i);
                messageMap = updateSynPersonData(coll);
                msgArray.add(messageMap);
            }
        } else {
            messageMap = updateSynPersonData(personPositionCollection);
            msgArray.add(messageMap);
        }
        //Map messageMap = synPersonData(personPositionCollection, iResignBizBillEntry);
        logger.error("msgArray--" + msgArray);
    }

    /**
     * 更新人员-逻辑
     *
     * @param personPositionCollection
     * @return
     * @throws BOSException
     */
    private Map updateSynPersonData(PersonPositionCollection personPositionCollection) throws BOSException {
        logger.error("updateSynPersonData--");
        Map messageMap = new HashMap();
        //更新人员数据
        JSONArray params = new JSONArray();
        for (int i = 0; i < personPositionCollection.size(); i++) {
            PersonPositionInfo personPositionInfo = personPositionCollection.get(i);
            PersonInfo person = personPositionInfo.getPerson();
            EmployeeTypeInfo employeeType = person.getEmployeeType();
            //判断是否是离职人员
            String number = employeeType.getNumber();
            logger.error("person--" + person.getName() + "--employeeType--" + number);
            if (!number.equals("010") && !number.equals("009") && !number.equals("S09")) {
                // 构建请求体（自动处理时间范围）
                JSONObject param = new JSONObject();
                param.put("name", person.getName()); //员工名称
                param.put("pin", person.getNumber()); //员工编码
                param.put("deptnumber", "1");  //部门编码
                params.add(param);
            }
        }
        logger.error("updateSynPersonData--params--" + params);
        if (params.size() > 0) {
            //更新人员
            String response = synPerson(params);
            // 处理响应
            if (response != null) {
                messageMap.put("updatePersonMsg", response);
            }
        }
        return messageMap;
    }

    /**
     * 人员初始化
     *
     * @param ctx
     * @throws BOSException
     * @throws EASBizException
     */
    @Override
    protected void _initializePerson(Context ctx) throws BOSException {
        logger.error("_initializePerson--");
        loadProperties();
        IPersonPosition iPersonPosition = PersonPositionFactory.getLocalInstance(ctx);
        //离职单
        IResignBizBillEntry iResignBizBillEntry = ResignBizBillEntryFactory.getLocalInstance(ctx);
        //获取查询参数
        SelectorItemCollection sic = getSic();
        EntityViewInfo entityViewInfo = EntityViewInfo.getInstance(null, sic, null);
        PersonPositionCollection personPositionCollection = iPersonPosition.getPersonPositionCollection(entityViewInfo);
        logger.error("personPositionCollection--" + personPositionCollection.size());
        List<PersonPositionInfo> PersonPositionList = new ArrayList();
        for (int i = 0; i < personPositionCollection.size(); i++) {
            PersonPositionList.add(personPositionCollection.get(i));
        }
        logger.error("PersonPositionList--" + PersonPositionList.size());
        JSONArray msgArray = new JSONArray();
        Map messageMap = null;
        if (PersonPositionList.size() > 180) {
            List<PersonPositionCollection> objects = splitList(PersonPositionList, 180);
            for (int i = 0; i < objects.size(); i++) {
                PersonPositionCollection coll = objects.get(i);
                messageMap = initializeSynPersonData(coll, iResignBizBillEntry);
                msgArray.add(messageMap);
            }
        } else {
            messageMap = initializeSynPersonData(personPositionCollection, iResignBizBillEntry);
            msgArray.add(messageMap);
        }
        //Map messageMap = synPersonData(personPositionCollection, iResignBizBillEntry);
        logger.error("msgArray--" + msgArray);
    }

    /**
     * 初始化同步人员数据
     *
     * @param personPositionCollection
     * @param iResignBizBillEntry
     * @return
     * @throws BOSException
     */
    private Map initializeSynPersonData(PersonPositionCollection personPositionCollection, IResignBizBillEntry iResignBizBillEntry) throws BOSException {
        Map messageMap = new HashMap();
        //更新人员数据
        JSONArray params = new JSONArray();
        //人员离职数据
        JSONArray leavePersonMsg = new JSONArray();
        List<PersonInfo> deletePersonList = new ArrayList();
        for (int i = 0; i < personPositionCollection.size(); i++) {
            PersonPositionInfo personPositionInfo = personPositionCollection.get(i);
            PersonInfo person = personPositionInfo.getPerson();
            EmployeeTypeInfo employeeType = person.getEmployeeType();
            //判断是否是离职人员
            String number = employeeType.getNumber();
            logger.error("person--" + person.getName() + "--employeeType--" + number);
            if (number.equals("010") || number.equals("009") || number.equals("S09")) {
                //离职人员
                deletePersonList.add(person);
            } else {
                // 构建请求体（自动处理时间范围）
                JSONObject param = new JSONObject();
                param.put("name", person.getName()); //员工名称
                param.put("pin", person.getNumber()); //员工编码
                param.put("deptnumber", "1");  //部门编码
                params.add(param);
            }
        }
        messageMap.put("leavePersonMsg", leavePersonMsg.toString());
        if (params.size() > 0) {
            //更新人员
            String response = synPerson(params);
            // 处理响应
            if (response != null) {
                messageMap.put("updatePersonMsg", response);
            }
        }
        //新增人员后再更新离职人员
        for (int i = 0; i < deletePersonList.size(); i++) {
            PersonInfo person = deletePersonList.get(i);
            //人员离职
            JSONObject result = synLeavePerson(iResignBizBillEntry, person);
            if (result != null) {
                leavePersonMsg.add(result);
            }
        }
        return messageMap;
    }

    /**
     * 查询参数
     */
    public SelectorItemCollection getSic() {
        SelectorItemCollection sic = new SelectorItemCollection();
        sic.add("*");
        sic.add("person.number");
        sic.add("person.name");
        sic.add("person.id");
        sic.add("person.hireDate");
        sic.add("person.nCell");
        sic.add("person.gender");
        sic.add("person.email");
        sic.add("person.employeeType.number");
        sic.add("personDep.name");
        sic.add("personDep.number");
        sic.add("personDep.id");
        sic.add("personDep.parent.id");
        return sic;
    }

    /**
     * 分割数据
     *
     * @param coll
     * @param len
     * @return
     */
    public List<PersonPositionCollection> splitList(List coll, int len) {
        List<PersonPositionCollection> result = new ArrayList();
        int size = coll.size();
        int count = (size + len - 1) / len;
        for (int i = 0; i < count; i++) {
            PersonPositionCollection personPositionCollection = new PersonPositionCollection();
            List<PersonPositionInfo> subList = coll.subList(i * len, ((i + 1) * len > size) ? size : (len * (i + 1)));
            for (int p = 0; p < subList.size(); p++) {
                PersonPositionInfo personPositionInfo = subList.get(p);
                personPositionCollection.add(personPositionInfo);
            }
            result.add(personPositionCollection);
        }
        return result;

    }

    /**
     * 人员离职
     *
     * @param personInfo
     */
    public JSONObject synLeavePerson(IResignBizBillEntry iResignBizBillEntry, PersonInfo personInfo) throws BOSException {
        logger.error("synLeavePerson-----");
        ResignBizBillEntryCollection entryInfo = iResignBizBillEntry.getResignBizBillEntryCollection("where person.id = '" + personInfo.getId() + "'");
        JSONObject param = new JSONObject();
        if (entryInfo.size() > 0) {
            ResignBizBillEntryInfo resignBizBillEntryInfo = entryInfo.get(0);
            Date bizDate = resignBizBillEntryInfo.getBizDate();
            param.put("pin", personInfo.getNumber()); //员工编码
            param.put("leavedate", DateTimeUtil.getFmtDate(bizDate, "yyyy-MM-dd HH:mm")); //离职日期
            param.put("leavetype", 0); //员工编码
        }
        // 生成 Token 和 URL 参数
        Map<String, String> queryParams = getToken();
        // 调用接口
        String urlPath = propt.getProperty("leaveUrlPath");
        String response = sendPostRequest(urlPath, param, queryParams);
        // 处理响应
        if (response != null) {
            JSONObject result = JSONObject.parseObject(response);
            if ("0".equals(result.getString("ret"))) {
                logger.error(personInfo.getId() + "_" + personInfo.getName() + "result--" + result);
            }
            return result;
        }
        return null;
    }

    /**
     * 更新人员
     *
     * @param params
     * @return
     */
    private String synPerson(JSONArray params) {
        Map<String, String> queryParams = getToken();
        // 调用接口
        String urlPath = propt.getProperty("updateUrlPath");
        return sendPostRequest(urlPath, params, queryParams);
    }

    /**
     * 获取Token
     *
     * @return
     */
    public Map getToken() {
        // 生成 Token 和 URL 参数
        long currentTime = Instant.now().getEpochSecond();
        String secretKey = propt.getProperty("SECRET_KEY");
        String token = DigestUtils.md5Hex(secretKey + currentTime);
        // 构建查询参数
        Map<String, String> queryParams = new HashMap<>();
        queryParams.put("timestamp", String.valueOf(currentTime));
        queryParams.put("token", token);
        return queryParams;
    }

    /**
     * 发送 POST 请求（JSON 格式） 用于查询所有数据
     *
     * @param urlPath     接口地址（可含路径参数，如 `/api/v2/transaction/get`）
     * @param queryParams URL 查询参数（如 `timestamp` 和 `token`）
     * @return 响应体字符串（失败返回 null）
     */
    public static String sendPostRequest(String urlPath, Map<String, String> queryParams) {
        try {
            // 1. 构建完整 URL（含查询参数）
            HttpUrl.Builder urlBuilder = HttpUrl.parse(urlPath).newBuilder();
            if (queryParams != null) {
                queryParams.forEach(urlBuilder::addQueryParameter);
            }
            String fullUrl = urlBuilder.build().toString();
            // 2. 创建请求体
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, "");
            // 3. 构建请求
            Request request = new Request.Builder()
                    .url(fullUrl)
                    .post(body)
                    .addHeader("Content-Type", "application/json")
                    .build();
            // 4. 发送请求并处理响应
            try (Response response = client.newCall(request).execute()) {
                if (response.isSuccessful() && response.body() != null) {
                    return response.body().string();
                } else {
                    logger.error("请求失败，状态码: " + response.code());
                }
            }
        } catch (IOException e) {
            logger.error("请求异常: " + e.getMessage(), e);
        }
        return null;
    }

    /**
     * 发送 POST 请求（JSON 格式）
     *
     * @param urlPath     接口地址（可含路径参数，如 `/api/v2/transaction/get`）
     * @param params      JSON 请求体
     * @param queryParams URL 查询参数（如 `timestamp` 和 `token`）
     * @return 响应体字符串（失败返回 null）
     */
    public static String sendPostRequest(String urlPath, JSONArray params, Map<String, String> queryParams) {
        try {
            // 1. 构建完整 URL（含查询参数）
            HttpUrl.Builder urlBuilder = HttpUrl.parse(urlPath).newBuilder();
            if (queryParams != null) {
                queryParams.forEach(urlBuilder::addQueryParameter);
            }
            String fullUrl = urlBuilder.build().toString();

            // 2. 创建请求体
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, params.toJSONString());

            // 3. 构建请求
            Request request = new Request.Builder()
                    .url(fullUrl)
                    .post(body)
                    .addHeader("Content-Type", "application/json")
                    .build();

            // 4. 发送请求并处理响应
            try (Response response = client.newCall(request).execute()) {
                if (response.isSuccessful() && response.body() != null) {
                    return response.body().string();
                } else {
                    logger.error("请求失败，状态码: " + response.code());
                }
            }
        } catch (IOException e) {
            logger.error("请求异常: " + e.getMessage(), e);
        }
        return null;
    }

    /**
     * 发送 POST 请求（JSON 格式）
     *
     * @param urlPath     接口地址（可含路径参数，如 `/api/v2/transaction/get`）
     * @param params      JSON 请求体
     * @param queryParams URL 查询参数（如 `timestamp` 和 `token`）
     * @return 响应体字符串（失败返回 null）
     */
    public static String sendPostRequest(String urlPath, JSONObject params, Map<String, String> queryParams) {
        try {
            // 1. 构建完整 URL（含查询参数）
            HttpUrl.Builder urlBuilder = HttpUrl.parse(urlPath).newBuilder();
            if (queryParams != null) {
                queryParams.forEach(urlBuilder::addQueryParameter);
            }
            String fullUrl = urlBuilder.build().toString();

            // 2. 创建请求体
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, params.toJSONString());

            // 3. 构建请求
            Request request = new Request.Builder()
                    .url(fullUrl)
                    .post(body)
                    .addHeader("Content-Type", "application/json")
                    .build();

            // 4. 发送请求并处理响应
            try (Response response = client.newCall(request).execute()) {
                if (response.isSuccessful() && response.body() != null) {
                    return response.body().string();
                } else {
                    logger.error("请求失败，状态码: " + response.code());
                }
            }
        } catch (IOException e) {
            logger.error("请求异常: " + e.getMessage(), e);
        }
        return null;
    }


}
