package com.mortals.xhx.module.dingding.personal.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.dingtalkattendance_1_0.Client;
import com.aliyun.dingtalkattendance_1_0.models.GetLeaveRecordsHeaders;
import com.aliyun.dingtalkattendance_1_0.models.GetLeaveRecordsResponse;
import com.aliyun.dingtalkattendance_1_0.models.GetLeaveRecordsResponseBody;
import com.aliyun.dingtalkworkflow_1_0.models.*;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.*;
import com.dingtalk.api.response.*;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.mortals.framework.common.Rest;
import com.mortals.xhx.common.code.AppealResultEnum;
import com.mortals.xhx.common.code.LeaveRulesEnum;
import com.mortals.xhx.module.attendance.dingmsg.DingCallbackCrypto;
import com.mortals.xhx.module.attendance.model.AttendanceLeaveRecordEntity;
import com.mortals.xhx.module.attendance.model.AttendanceVacationBalanceEntity;
import com.mortals.xhx.module.attendance.model.AttendanceVacationBalanceQuery;
import com.mortals.xhx.module.attendance.service.AttendanceLeaveRecordService;
import com.mortals.xhx.module.attendance.service.AttendanceVacationBalanceService;
import com.mortals.xhx.module.dingding.AbstractDingTalkService;
import com.mortals.xhx.module.dingding.personal.model.req.workmsg.WorkMsgReq;
import com.mortals.xhx.module.dingding.personal.service.IDingPersonService;
import com.mortals.xhx.module.staff.model.StaffEntity;
import com.mortals.xhx.module.staff.model.StaffQuery;
import com.mortals.xhx.module.staff.service.StaffService;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.Log;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


@Service("dingPersonService")
@Slf4j
public class DingPersonServiceImpl extends AbstractDingTalkService implements IDingPersonService {

    @Autowired
    private AttendanceLeaveRecordService attendanceLeaveRecordService;
    @Autowired
    private StaffService staffService;
    @Autowired
    private AttendanceVacationBalanceService balanceService;

    /**
     * 钉钉根据电话查询钉钉用户 id
     *
     * @param mobile
     * @return
     */
    @Override
    public Rest<String> getPersonByMobile(String mobile) {
        try {
            DingTalkClient client = getDingTalkClient("/topapi/v2/user/getbymobile");
            OapiV2UserGetbymobileRequest req = new OapiV2UserGetbymobileRequest();
            req.setMobile(mobile);
            log.info("getPersonByMobile:{}", mobile);
            OapiV2UserGetbymobileResponse rsp = client.execute(req, getToken());
            log.info("OapiV2UserGetbymobileResponse:{}", rsp.getBody());
            if (rsp.getErrcode() == 0) {
                return Rest.ok("成功", rsp.getResult().getUserid());
            } else {
                return Rest.fail(String.format("code:%s,msg:%s", rsp.getErrcode(), rsp.getErrmsg()));
            }
        } catch (ApiException e) {
            log.info("根据手机号码查询人员异常", e);
            return Rest.fail(e.getMessage());
        }
    }

    /**
     * 钉钉根据id查询员工信息
     *
     * @param id
     * @return
     */
    @Override
    public Rest<String> getPersonById(String id) {
        try {
            DingTalkClient client = getDingTalkClient("/topapi/v2/user/get");
            OapiV2UserGetRequest req = new OapiV2UserGetRequest();
            req.setUserid(id);   //用户id
            log.info("getPersonByID:{}", id);
            OapiV2UserGetResponse rsp = client.execute(req, getToken());
            log.info("钉钉返回用户信息:{}", rsp.getBody());
            if (rsp.getErrcode() == 0) {
                return Rest.ok("成功", rsp.getResult().getMobile());
            } else {
                return Rest.fail(String.format("code:%s,msg:%s", rsp.getErrcode(), rsp.getErrmsg()));
            }
        } catch (ApiException e) {
            log.info("根据手机号码查询人员异常", e);
            return Rest.fail(e.getMessage());
        }
    }

    /**
     * 根据code查询用户id
     *
     * @param code
     * @return
     */
    @Override
    public Rest<String> getPersonByCode(String code) {
        try {
            DingTalkClient client = getDingTalkClient("/topapi/v2/user/getuserinfo");
            OapiV2UserGetuserinfoRequest req = new OapiV2UserGetuserinfoRequest();
            req.setCode(code);
            log.info("getPersonByCode:{}", code);
            OapiV2UserGetuserinfoResponse rsp = client.execute(req, getToken());
            log.info("OapiV2UserGetuserinfoResponse:{}", rsp.getBody());
            if (rsp.getErrcode() == 0) {
                return Rest.ok("成功", rsp.getResult().getUserid());
            } else {
                return Rest.fail(String.format("code:%s,msg:%s", rsp.getErrcode(), rsp.getErrmsg()));
            }
        } catch (ApiException e) {
            log.info("根据code查询人员异常", e);
            return Rest.fail(e.getMessage());
        }
    }

    @Override
    public Rest<String> sendWorkMsg(WorkMsgReq workMsgReq) {
        try {
            DingTalkClient client = getDingTalkClient("/topapi/message/corpconversation/asyncsend_v2");
            OapiMessageCorpconversationAsyncsendV2Request req = new OapiMessageCorpconversationAsyncsendV2Request();
            req.setAgentId(agentId);
            req.setUseridList(workMsgReq.getUseridList());
            //.setMsg(JSON.toJSONString(workMsgReq.getMsg()));
            log.info("workMsgReq:{}", JSON.toJSONString(workMsgReq));
            OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();

            if ("link".equals(workMsgReq.getMsg().getMsgtype())) {
                OapiMessageCorpconversationAsyncsendV2Request.Link link = new OapiMessageCorpconversationAsyncsendV2Request.Link();
                link.setMessageUrl(workMsgReq.getMsg().getLink().getMessageUrl());
                link.setText(workMsgReq.getMsg().getLink().getText());
                link.setTitle(workMsgReq.getMsg().getLink().getTitle());

                link.setPicUrl("@lADOADmaWMzazQKA");
                msg.setLink(link);
                msg.setMsgtype("link");
            } else if ("text".equals(workMsgReq.getMsg().getMsgtype())) {
                OapiMessageCorpconversationAsyncsendV2Request.Text text = new OapiMessageCorpconversationAsyncsendV2Request.Text();
                text.setContent(workMsgReq.getMsg().getText().getContent());
                msg.setMsgtype("text");
                msg.setText(text);
            }
            req.setMsg(msg);
            //  workMsgReq.getMsg().getLink().setPicUrl("@lADOADmaWMzazQKA");
            log.info("sendWorkMsg:{}", JSON.toJSONString(req));
            OapiMessageCorpconversationAsyncsendV2Response rsp = client.execute(req, getToken());
            log.info("OapiMessageResponse:{}", rsp.getBody());
            if (rsp.getErrcode() == 0) {
                return Rest.ok(rsp.getMsg(), rsp.getRequestId());
            } else {
                return Rest.fail(String.format("code:%s,msg:%s", rsp.getErrcode(), rsp.getErrmsg()));
            }
        } catch (ApiException e) {
            log.info("根据用户id发送工作消息异常", e);
            return Rest.fail(e.getMessage());
        }
    }

    /**
     * 设置client的config参数
     *
     * @return Client
     * @throws Exception
     */
    public com.aliyun.teaopenapi.models.Config setConfig() {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();
       // config.protocol = "http";
        config.protocol = oaScheme;
        config.regionId = "central";
        config.endpoint = oaUrl;
        return config;
    }

    /**
     * 根据系统电话查询指定时间的审批表单
     *
     * @param processCode 审批流的唯一码（详见doc下 审批表单列表.txt）。
     *                    请假：PROC-2E5C0DFF-3615-4409-A614-A2011FED5D38
     *                    外出：PROC-56D3ADEE-45A4-47BC-931A-2A0DC067DE32
     *                    出差：PROC-578CBDDF-B768-496D-9918-44A3F1D9CAE7
     * @param startTime   审批实例开始时间，Unix时间戳，单位毫秒
     * @param endTime     审批实例结束时间，Unix时间戳，单位毫秒。 查询时间范围不能超过120天
     * @param nextToken   分页游标。如果是非首次调用，该参数传上次调用时返回的nextToken。
     * @param maxResults  分页参数，每页大小，最多传20。
     * @param userIds     发起人id列表  最大列表长度为10
     * @return 返回示例 {
     * "result" : {
     * "list" : [ "123" ],
     * "nextToken" : "10"
     * },
     * "success" : true
     * }
     */
    public Rest<ListProcessInstanceIdsResponseBody.ListProcessInstanceIdsResponseBodyResult> getProcessInstanceIdByUserIds(String processCode, long startTime, long endTime, Long nextToken, long maxResults, String userIds) throws Exception {
        if (!userIds.equals("")) {
            com.aliyun.dingtalkworkflow_1_0.Client client = new com.aliyun.dingtalkworkflow_1_0.Client(setConfig());
            com.aliyun.dingtalkworkflow_1_0.models.ListProcessInstanceIdsHeaders listProcessInstanceIdsHeaders = new com.aliyun.dingtalkworkflow_1_0.models.ListProcessInstanceIdsHeaders();
            listProcessInstanceIdsHeaders.xAcsDingtalkAccessToken = getToken();
            HashMap<String, String> map = new HashMap<>();
            listProcessInstanceIdsHeaders.setCommonHeaders(map);
            log.info("oaUrl===>{}",oaUrl);
            if(!ObjectUtils.isEmpty(oaUrl)){
                listProcessInstanceIdsHeaders.getCommonHeaders().put("host", oaUrl);
            }
            // listProcessInstanceIdsHeaders.getCommonHeaders().put("host", "172.15.28.113:8919");

            com.aliyun.dingtalkworkflow_1_0.models.ListProcessInstanceIdsRequest listProcessInstanceIdsRequest = new ListProcessInstanceIdsRequest()
                    .setProcessCode(processCode)
                    .setStartTime(startTime)
                    .setEndTime(endTime)
                    .setNextToken(nextToken)
                    .setMaxResults(maxResults)
                    .setStatuses(Arrays.asList("COMPLETED"))
                    .setUserIds(java.util.Arrays.asList(userIds));
            try {
                RuntimeOptions runtimeOptions = new RuntimeOptions();
                runtimeOptions.setReadTimeout(60000);
                runtimeOptions.setConnectTimeout(60000);
                ListProcessInstanceIdsResponse rsp = client.listProcessInstanceIdsWithOptions(listProcessInstanceIdsRequest, listProcessInstanceIdsHeaders, runtimeOptions);

                if (rsp.getBody().getSuccess()) {
                    return Rest.ok(rsp.getBody().getResult());
                } else {
                    log.info("获取审批实例列表失败->" + JSONObject.toJSONString(rsp));
                    return Rest.fail("查询失败:" + rsp.getBody().getSuccess());
                }
            } catch (Exception _err) {
                TeaException err = new TeaException(_err.getMessage(), _err);
                log.error("获取审批实例列表失败->",_err);
                if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                    // err 中含有 code 和 message 属性，可帮助开发定位问题
                    log.error("code = " + com.aliyun.teautil.Common.empty(err.code) + " message = " + com.aliyun.teautil.Common.empty(err.message));
                }
                return Rest.fail("获取审批实例列表失败:" + com.aliyun.teautil.Common.empty(err.message));
            }
        } else {
            return Rest.fail("userid为空");
        }


    }

    /**
     * 根据审批实例id查询审批详情
     *
     * @param processInstanceId 审批实例ID。
     * @return
     */
    @Override
    public Rest<GetProcessInstanceResponseBody.GetProcessInstanceResponseBodyResult> getOaRecordsById(String processInstanceId) {
        try {
            com.aliyun.dingtalkworkflow_1_0.Client client = new com.aliyun.dingtalkworkflow_1_0.Client(setConfig());
            com.aliyun.dingtalkworkflow_1_0.models.GetProcessInstanceHeaders getProcessInstanceHeaders = new com.aliyun.dingtalkworkflow_1_0.models.GetProcessInstanceHeaders();
            getProcessInstanceHeaders.xAcsDingtalkAccessToken = getToken();
            HashMap<String, String> map = new HashMap<>();
            getProcessInstanceHeaders.setCommonHeaders(map);
            if(!ObjectUtils.isEmpty(oaUrl)){
                getProcessInstanceHeaders.getCommonHeaders().put("host", oaUrl);
            }

            com.aliyun.dingtalkworkflow_1_0.models.GetProcessInstanceRequest getProcessInstanceRequest = new com.aliyun.dingtalkworkflow_1_0.models.GetProcessInstanceRequest()
                    .setProcessInstanceId(processInstanceId);
            log.info("processInstanceId:{}", processInstanceId);
            GetProcessInstanceResponse rsp = client.getProcessInstanceWithOptions(getProcessInstanceRequest, getProcessInstanceHeaders, new com.aliyun.teautil.models.RuntimeOptions());
            return Rest.ok("成功", rsp.getBody().getResult());
        } catch (Exception e) {
            log.error("根据用户查询审批详情失败", e);
            return Rest.fail(e.getMessage());

        }
    }


    /**
     * 查询假期余额
     *
     * @param user_id    被查询员工的id集合 多个用,分隔
     * @param leave_code 假期类型编码
     * @return
     */
    @Override
    public Rest<OapiAttendanceVacationQuotaListResponse.OapiLeaveQuotaUserListVo> getLeaveRecordByUserId(String user_id, String leave_code) {
        try {
            DingTalkClient client = getDingTalkClient("/topapi/attendance/vacation/quota/list");
            OapiAttendanceVacationQuotaListRequest req = new OapiAttendanceVacationQuotaListRequest();
            req.setLeaveCode(leave_code);
            req.setOpUserid(opUserId);
            req.setUserids(user_id);
            req.setOffset(0L);
            req.setSize(50L);
            OapiAttendanceVacationQuotaListResponse rsp = client.execute(req, getToken());
            log.info("假期余额:{}", JSON.toJSONString(rsp.getResult()));
            if (rsp.getErrcode() == 0) {
                return Rest.ok("成功", rsp.getResult());
            } else {
                return Rest.fail(String.format("code:%s,msg:%s", rsp.getErrcode(), rsp.getErrmsg()));
            }
        } catch (ApiException e) {
            e.printStackTrace();
            log.error("根据id查询假期余额异常", e);
            return Rest.fail(e.getMessage());
        }

    }

    /**
     * 根据审批详情处理审批（插入请假数据）
     *
     * @param processInstanceId 实例id
     */
    public void handleByProcessInstanceId(String processInstanceId) {
        try {
            if (processInstanceId != null) {
                Rest<GetProcessInstanceResponseBody.GetProcessInstanceResponseBodyResult> rest = getOaRecordsById(processInstanceId);
                if (rest.getCode() == Rest.SUCCESS) {
                    GetProcessInstanceResponseBody.GetProcessInstanceResponseBodyResult result = rest.getData();
                    log.info("审批详情：" + JSONObject.toJSONString(result));

                    if (result.getTitle().contains("请假") || result.getTitle().contains("外出")) {  //只处理请假的审批单
                        AttendanceLeaveRecordEntity leaveRecordEntity = new AttendanceLeaveRecordEntity();

                        leaveRecordEntity.initAttrValue();
                        leaveRecordEntity.setRemark(processInstanceId);   //将钉钉的事物id作为备注填入数据库

                        Rest<String> mobileRest = getPersonById(result.getOriginatorUserId());
                        if (mobileRest.getCode() == Rest.SUCCESS) {
                            String mobile = mobileRest.getData();
                            StaffEntity staffEntity = staffService.selectOne(new StaffQuery().phoneNumber(mobile));
                            if (!ObjectUtils.isEmpty(staffEntity)) {

                                leaveRecordEntity.setLeavePersonId(staffEntity.getId());
                                leaveRecordEntity.setLeavePerson(staffEntity.getName());
                                leaveRecordEntity.setDeptId(staffEntity.getDeptId());
                                leaveRecordEntity.setDeptName(staffEntity.getDeptName());
                                leaveRecordEntity.setPhoneNumber(staffEntity.getPhoneNumber());
                                leaveRecordEntity.setSalaId(staffEntity.getSalaId());
                                leaveRecordEntity.setSalaName(staffEntity.getSalaName());

                                String leave_code = LeaveRulesEnum.事假.getLeave_code();
                                String leave_name = "事假";
                                if (result.getTitle().contains("请假")) {
                                    leave_name = "事假";
                                    if (result.getFormComponentValues().size() > 0) {
                                        JSONArray jsonArray = JSONArray.parseArray(result.getFormComponentValues().get(0).getValue());
                                        if (jsonArray != null && jsonArray.size() > 0) {
                                            Date startTime1 = dateFormat(jsonArray.get(0).toString(), "yyyy-MM-dd HH:mm", true);
                                            leaveRecordEntity.setStartTime(startTime1);
                                        }
                                        if (jsonArray != null && jsonArray.size() > 1) {
                                            Date endTime1 = dateFormat(jsonArray.get(1).toString(), "yyyy-MM-dd HH:mm", false);
                                            leaveRecordEntity.setEndTime(endTime1);
                                        }
                                        if (jsonArray != null && jsonArray.size() > 2) {
                                            if (jsonArray.size() > 3) {
                                                switch (jsonArray.get(3).toString()) {
                                                    case "halfDay":
                                                    case "day":
                                                        leaveRecordEntity.setDuration((int) (Float.parseFloat(jsonArray.get(2).toString()) * 60 * 60 * 8)); //天转换成秒 一天工作时间9小时
                                                        leaveRecordEntity.setSourceDingTime(jsonArray.get(2).toString() + "天");
                                                        break;
                                                    default:  //除了按天和半天计算的假期  其余都是按小时返回
                                                        leaveRecordEntity.setDuration((int) (Float.parseFloat(jsonArray.get(2).toString()) * 60 * 60)); //小时转换成秒
                                                        leaveRecordEntity.setSourceDingTime(jsonArray.get(2).toString() + "小时");
                                                        break;

                                                }
                                            }

                                        }
                                        if (jsonArray != null && jsonArray.size() > 4) {
                                            leave_name = jsonArray.get(4).toString();
                                            switch (leave_name) {
                                                case "事假":
                                                    leaveRecordEntity.setLeaveType(1);
                                                    leave_code = LeaveRulesEnum.事假.getLeave_code();
                                                    break;
                                                case "调休":
                                                    leaveRecordEntity.setLeaveType(2);
                                                    leave_code = LeaveRulesEnum.调休.getLeave_code();
                                                    break;
                                                case "病假":
                                                    leaveRecordEntity.setLeaveType(3);
                                                    leave_code = LeaveRulesEnum.病假.getLeave_code();
                                                    break;
                                                case "年假":
                                                    leaveRecordEntity.setLeaveType(4);
                                                    leave_code = LeaveRulesEnum.年假.getLeave_code();
                                                    break;
                                                case "产假":
                                                    leaveRecordEntity.setLeaveType(5);
                                                    leave_code = LeaveRulesEnum.产假.getLeave_code();
                                                    break;
                                                case "陪产假":
                                                    leaveRecordEntity.setLeaveType(6);
                                                    leave_code = LeaveRulesEnum.陪产假.getLeave_code();
                                                    break;
                                                case "婚假":
                                                    leaveRecordEntity.setLeaveType(7);
                                                    leave_code = LeaveRulesEnum.婚假.getLeave_code();
                                                    break;
                                                case "例假":
                                                    leaveRecordEntity.setLeaveType(8);
                                                    leave_code = LeaveRulesEnum.例假.getLeave_code();
                                                    break;
                                                case "哺乳假":
                                                    leaveRecordEntity.setLeaveType(9);
                                                    leave_code = LeaveRulesEnum.哺乳假.getLeave_code();
                                                    break;
                                                case "丧假":
                                                    leaveRecordEntity.setLeaveType(10);
                                                    leave_code = LeaveRulesEnum.丧假.getLeave_code();
                                                    break;
                                                case "回单位":
                                                    leaveRecordEntity.setLeaveType(11);
                                                    break;
                                                case "因公请假":
                                                    leaveRecordEntity.setLeaveType(12);
                                                    break;
                                                case "外出勘验":
                                                    leaveRecordEntity.setLeaveType(13);
                                                    break;
                                                case "值班补班":
                                                    leaveRecordEntity.setLeaveType(14);
                                                    break;
                                                case "体检":
                                                    leaveRecordEntity.setLeaveType(15);
                                                    break;
                                                case "隔离":
                                                    leaveRecordEntity.setLeaveType(16);
                                                    break;
                                                case "因公外出":
                                                    leaveRecordEntity.setLeaveType(17);
                                                    break;
                                                case "公休":
                                                    leaveRecordEntity.setLeaveType(18);
                                                    break;
                                                case "育儿假":
                                                    leaveRecordEntity.setLeaveType(19);
                                                    break;
                                                case "调回单位":
                                                    leaveRecordEntity.setLeaveType(20);
                                                    break;
                                                case "探亲假":
                                                    leaveRecordEntity.setLeaveType(21);
                                                    leave_code = LeaveRulesEnum.探亲假.getLeave_code();
                                                    break;
                                                default:
                                                    leaveRecordEntity.setLeaveType(22);  //默认其他
                                                    break;

                                            }

                                        }

                                    }
                                    if (result.getFormComponentValues().size() > 1) {  //请假理由
                                        GetProcessInstanceResponseBody.GetProcessInstanceResponseBodyResultFormComponentValues resonEntity = result.getFormComponentValues().get(1);
                                        leaveRecordEntity.setReason(resonEntity.getValue());
                                    }
                                    if (result.getFormComponentValues().size() > 2) {  //上传的附件
                                        GetProcessInstanceResponseBody.GetProcessInstanceResponseBodyResultFormComponentValues picEntity = result.getFormComponentValues().get(2);
                                        if (picEntity.getName().equals("图片") && picEntity.getValue() != null) {
                                            leaveRecordEntity.setAttachmentPath(picEntity.getValue());
                                        }
                                    }
                                } else if (result.getTitle().contains("外出")) {
                                    leave_name = "因公外出";
                                    leaveRecordEntity.setLeaveType(17);
                                    List<GetProcessInstanceResponseBody.GetProcessInstanceResponseBodyResultFormComponentValues> comList = result.getFormComponentValues();
                                    if (!comList.isEmpty()) {
                                        for (GetProcessInstanceResponseBody.GetProcessInstanceResponseBodyResultFormComponentValues componentValues : comList) {
                                            switch (componentValues.name) {
                                                case "开始时间":
                                                    Date startTime1 = dateFormat(componentValues.getValue(), "yyyy-MM-dd HH:mm", true);
                                                    leaveRecordEntity.setStartTime(startTime1);
                                                    break;
                                                case "结束时间":
                                                    Date endTime1 = dateFormat(componentValues.getValue(), "yyyy-MM-dd HH:mm", false);
                                                    leaveRecordEntity.setEndTime(endTime1);
                                                    break;
                                                case "时长":
                                                    leaveRecordEntity.setDuration(Integer.parseInt(componentValues.getValue()) * 60 * 60 * 8); //天转换成秒 一天工作时间9小时
                                                    leaveRecordEntity.setSourceDingTime(Integer.parseInt(componentValues.getValue()) + "天");
                                                    break;
                                                case "外出事由":
                                                    leaveRecordEntity.setReason(componentValues.getValue());
                                                    break;
                                                case "图片":
                                                    leaveRecordEntity.setAttachmentPath(componentValues.getValue());
                                                    break;
                                            }
                                        }
                                    }
                                } else if (result.getTitle().contains("出差")) {
                                    leave_name = "因公外出";
                                    leaveRecordEntity.setLeaveType(17);
                                    List<GetProcessInstanceResponseBody.GetProcessInstanceResponseBodyResultFormComponentValues> comList = result.getFormComponentValues();
                                    if (!comList.isEmpty()) {
                                        for (GetProcessInstanceResponseBody.GetProcessInstanceResponseBodyResultFormComponentValues componentValues : comList) {
                                            switch (componentValues.name) {
                                                case "行程":
                                                    Gson gson = new Gson();
                                                    JsonArray jsonArray = gson.fromJson(componentValues.getValue(), JsonArray.class);
                                                    JsonObject jsonObject = jsonArray.get(0).getAsJsonObject(); // 获取第一个对象
                                                    JsonElement rowValueElement = jsonObject.get("rowValue"); // 获取rowValue字段的值
                                                    JsonArray rowValueArray = rowValueElement.getAsJsonArray(); // 获取数组
                                                    for (JsonElement element : rowValueArray) { // 遍历数组中的每个元素
                                                        JsonObject jsonObject1 = element.getAsJsonObject(); // 获取每个元素作为对象
                                                        String label = jsonObject1.get("label").getAsString(); // 获取label字段的值
                                                        String value = jsonObject1.get("value").getAsString();
                                                        if (label.contains("开始时间")) {
                                                            Date startTime1 = dateFormat(value, "yyyy-MM-dd HH:mm", true);
                                                            leaveRecordEntity.setStartTime(startTime1);
                                                        }
                                                        if (label.contains("结束时间")) {
                                                            Date endTime1 = dateFormat(value, "yyyy-MM-dd HH:mm", false);
                                                            leaveRecordEntity.setEndTime(endTime1);
                                                        }
                                                    }


                                                    break;
                                                case "出差天数":
                                                    leaveRecordEntity.setDuration(Integer.parseInt(componentValues.getValue()) * 60 * 60 * 8); //天转换成秒 一天工作时间9小时
                                                    leaveRecordEntity.setSourceDingTime(Integer.parseInt(componentValues.getValue()) + "天");
                                                    break;
                                                case "出差事由":
                                                    leaveRecordEntity.setReason(componentValues.getValue());
                                                    break;
                                                case "图片":
                                                    leaveRecordEntity.setAttachmentPath(componentValues.getValue());
                                                    break;
                                            }
                                        }
                                    }
                                }


                                if (result.getStatus().compareToIgnoreCase("NEW") == 0 || result.getStatus().compareToIgnoreCase("RUNNING") == 0) {
                                    leaveRecordEntity.setProcessStatus(1);
                                } else if (result.getStatus().compareToIgnoreCase("COMPLETED") == 0 || result.getStatus().compareToIgnoreCase("CANCELED") == 0
                                        || result.getStatus().compareToIgnoreCase("TERMINATED") == 0) {
                                    leaveRecordEntity.setProcessStatus(2);
                                }


                                if (result.getResult().compareToIgnoreCase("AGREE") == 0) {
                                    leaveRecordEntity.setAuditResult(AppealResultEnum.通过.getValue());
                                    //10/19增加撤销审批状态
                                    if (result.getTasks().size() > 1) {
                                        if ((result.getTasks().get(1).getStatus().compareToIgnoreCase("CANCELED") == 0) ||
                                                result.getBizAction().compareToIgnoreCase("REVOKE") == 0) {
                                            leaveRecordEntity.setAuditResult(4);  //撤销审批完成
                                            leaveRecordEntity.setAuditResult(AppealResultEnum.撤销审批通过.getValue());
                                        }
                                    }

                                }
                                else if (result.getResult().compareToIgnoreCase("REFUSE") == 0) {  //拒绝审批
                                    leaveRecordEntity.setAuditResult(AppealResultEnum.不通过.getValue());  //拒绝审批
                                }
                                else if (result.equals("")) {  //撤销假期审批中result会为空  撤销审批通过后result为AGREE
                                    if (result.getTasks().size() > 1) {
                                        log.info("status" + result.getTasks().get(1).getStatus());
                                        if (result.getTasks().get(1).getStatus().compareToIgnoreCase("CANCELED") != 0) {
                                            leaveRecordEntity.setAuditResult(AppealResultEnum.撤销审批中.getValue());  //撤销审批中
                                        }
                                    }
                                } else {
                                    leaveRecordEntity.setAuditResult(AppealResultEnum.审核中.getValue());  //请假审批中
                                }


                                log.info("钉钉返回的result:" + result.getResult() + "---auditresult:" + leaveRecordEntity.getAuditResult());
                                leaveRecordEntity.setAuditDesc(result.getOperationRecords().get(0).getRemark());
                                if (result.getOperationRecords().get(0).getRemark() != null && !result.getOperationRecords().get(0).getRemark().equals("")) {
                                    leaveRecordEntity.setReason(result.getOperationRecords().get(0).getRemark());
                                }
                                //更新请假记录表
//                                    AttendanceLeaveRecordEntity recordEntity = attendanceLeaveRecordService.selectOne(new AttendanceLeaveRecordQuery().remark(processInstanceId));
//                                    if(ObjectUtils.isEmpty(recordEntity)){
//
//                                        leaveRecordEntity.setCreateTime(new Date());
//                                        leaveRecordEntity.setCreateUserId(1L);
//                                        attendanceLeaveRecordService.save(leaveRecordEntity);
//                                    }else{
//                                        leaveRecordEntity.setId(recordEntity.getId());
//
//                                        leaveRecordEntity.setUpdateUserId(1L);
//                                        leaveRecordEntity.setUpdateTime(new Date());
//
//                                        attendanceLeaveRecordService.update(leaveRecordEntity);
//                                    }
                                attendanceLeaveRecordService.doUpdateRecord(processInstanceId, leaveRecordEntity);

                                //假期余额
                                AttendanceVacationBalanceEntity attendanceVacationBalanceEntity = new AttendanceVacationBalanceEntity();
                                //查询假期余额
                                Rest<OapiAttendanceVacationQuotaListResponse.OapiLeaveQuotaUserListVo> leaveRecordsResponseBodyResultRest = getLeaveRecordByUserId(result.getOriginatorUserId(), leave_code);
                                AttendanceVacationBalanceEntity balanceEntity = balanceService.selectOne(new AttendanceVacationBalanceQuery().staffId(staffEntity.getId()));
                                if (ObjectUtils.isEmpty(balanceEntity)) {  //先判断数据库里没有这个人的请假记录就初始化对象
                                    attendanceVacationBalanceEntity.initAttrValue();
                                }
                                attendanceVacationBalanceEntity.setRemark(processInstanceId); // 将钉钉的事物id存入假期余额  用于判断是否为同一条请假数据
                                attendanceVacationBalanceEntity.setStaffId(staffEntity.getId());
                                attendanceVacationBalanceEntity.setStaffName(staffEntity.getName());
                                attendanceVacationBalanceEntity.setDeptId(staffEntity.getDeptId());
                                attendanceVacationBalanceEntity.setDeptName(staffEntity.getDeptName());
                                attendanceVacationBalanceEntity.setSalaId(staffEntity.getSalaId());
                                attendanceVacationBalanceEntity.setSalaName(staffEntity.getSalaName());
                                attendanceVacationBalanceEntity.setEntryTime(staffEntity.getEntryDate());
                                if (leaveRecordsResponseBodyResultRest.getCode() == Rest.SUCCESS) {
                                    OapiAttendanceVacationQuotaListResponse.OapiLeaveQuotaUserListVo result1 = leaveRecordsResponseBodyResultRest.getData();
                                    double leaveBlance = 0;
//                                    //如果钉钉有假期余额就写入钉钉返回的余额   否则用数据库表数据减去当前请假的天数
//                                    if(result1.getLeaveQuotas() != null && result1.getLeaveQuotas().size() > 0){
//                                        if(leaveRecordEntity.getAuditResult() == 4) { //撤销休假  要把已经扣除的假期加回来
//                                            if(!ObjectUtils.isEmpty(balanceEntity) && balanceEntity.getCompensatedLeaveDays() != null){
//                                                leaveBlance = balanceEntity.getCompensatedLeaveDays().floatValue() + result1.getLeaveQuotas().get(0).getUsedNumPerDay()/100;
//                                            }else {
//                                                leaveBlance = result1.getLeaveQuotas().get(0).getUsedNumPerDay()/100;  //秒转换为天
//                                            }
//                                        }else {
//                                            if(!ObjectUtils.isEmpty(balanceEntity) && balanceEntity.getCompensatedLeaveDays() != null){
//                                                leaveBlance = balanceEntity.getCompensatedLeaveDays().floatValue() - result1.getLeaveQuotas().get(0).getUsedNumPerDay()/100;
//                                            }else {
//                                                leaveBlance = - result1.getLeaveQuotas().get(0).getUsedNumPerDay()/100;  //秒转换为天
//                                            }
//                                        }
//                                    }

                                    switch (leave_name) {
                                        case "事假":
                                            if (leaveBlance == 0) {
                                                if (!ObjectUtils.isEmpty(balanceEntity) && balanceEntity.getPersonalLeaveDays() != null) {
                                                    leaveBlance = balanceEntity.getPersonalLeaveDays().floatValue() - converMillsToDays(leaveRecordEntity.getDuration());
                                                } else {
                                                    leaveBlance = -converMillsToDays(leaveRecordEntity.getDuration());  //秒转换为天
                                                }
                                            }
                                            attendanceVacationBalanceEntity.setPersonalLeaveDays(BigDecimal.valueOf(leaveBlance));  //默认事假
                                            break;
                                        case "调休":
                                            if (leaveBlance == 0) {
                                                if (!ObjectUtils.isEmpty(balanceEntity) && balanceEntity.getCompensatedLeaveDays() != null) {
                                                    leaveBlance = balanceEntity.getCompensatedLeaveDays().floatValue() - converMillsToDays(leaveRecordEntity.getDuration());
                                                } else {
                                                    leaveBlance = -converMillsToDays(leaveRecordEntity.getDuration());  //秒转换为天
                                                }
                                            }
                                            attendanceVacationBalanceEntity.setCompensatedLeaveDays(BigDecimal.valueOf(leaveBlance));
                                            break;
                                        case "病假":
                                            if (leaveBlance == 0) {
                                                if (!ObjectUtils.isEmpty(balanceEntity) && balanceEntity.getSickLeaveDays() != null) {
                                                    leaveBlance = balanceEntity.getSickLeaveDays().floatValue() - converMillsToDays(leaveRecordEntity.getDuration());
                                                } else {
                                                    leaveBlance = -converMillsToDays(leaveRecordEntity.getDuration());  //秒转换为天
                                                }
                                            }
                                            attendanceVacationBalanceEntity.setSickLeaveDays(BigDecimal.valueOf(leaveBlance));
                                            break;
                                        case "年假":
                                            if (leaveBlance == 0) {
                                                if (!ObjectUtils.isEmpty(balanceEntity) && balanceEntity.getAnnualLeaveDays() != null) {
                                                    leaveBlance = balanceEntity.getAnnualLeaveDays().floatValue() - converMillsToDays(leaveRecordEntity.getDuration());
                                                } else {
                                                    leaveBlance = -converMillsToDays(leaveRecordEntity.getDuration());  //秒转换为天
                                                }
                                            }
                                            attendanceVacationBalanceEntity.setAnnualLeaveDays(BigDecimal.valueOf(leaveBlance));
                                            break;
                                        case "产假":
                                            if (leaveBlance == 0) {
                                                if (!ObjectUtils.isEmpty(balanceEntity) && balanceEntity.getMaternityLeaveDays() != null) {
                                                    leaveBlance = balanceEntity.getMaternityLeaveDays().floatValue() - converMillsToDays(leaveRecordEntity.getDuration());
                                                } else {
                                                    leaveBlance = -converMillsToDays(leaveRecordEntity.getDuration());  //秒转换为天
                                                }
                                            }
                                            attendanceVacationBalanceEntity.setMaternityLeaveDays(BigDecimal.valueOf(leaveBlance));
                                            break;
                                        case "陪产假":
                                            if (leaveBlance == 0) {
                                                if (!ObjectUtils.isEmpty(balanceEntity) && balanceEntity.getPaternityLeaveDays() != null) {
                                                    leaveBlance = balanceEntity.getPaternityLeaveDays().floatValue() - converMillsToDays(leaveRecordEntity.getDuration());
                                                } else {
                                                    leaveBlance = -converMillsToDays(leaveRecordEntity.getDuration());  //秒转换为天
                                                }
                                            }
                                            attendanceVacationBalanceEntity.setPaternityLeaveDays(BigDecimal.valueOf(leaveBlance));
                                            break;
                                        case "婚假":
                                            if (leaveBlance == 0) {
                                                if (!ObjectUtils.isEmpty(balanceEntity) && balanceEntity.getMarriageLeaveDays() != null) {
                                                    leaveBlance = balanceEntity.getMarriageLeaveDays().floatValue() - converMillsToDays(leaveRecordEntity.getDuration());
                                                } else {
                                                    leaveBlance = -converMillsToDays(leaveRecordEntity.getDuration());  //秒转换为天
                                                }
                                            }
                                            attendanceVacationBalanceEntity.setMarriageLeaveDays(BigDecimal.valueOf(leaveBlance));
                                            break;
                                        case "例假":
                                            if (leaveBlance == 0) {
                                                if (!ObjectUtils.isEmpty(balanceEntity) && balanceEntity.getMenstrualLeaveDays() != null) {
                                                    leaveBlance = balanceEntity.getMenstrualLeaveDays().floatValue() - converMillsToDays(leaveRecordEntity.getDuration());
                                                } else {
                                                    leaveBlance = -converMillsToDays(leaveRecordEntity.getDuration());  //秒转换为天
                                                }
                                            }
                                            attendanceVacationBalanceEntity.setMenstrualLeaveDays(BigDecimal.valueOf(leaveBlance));
                                            break;
                                        case "哺乳假":
                                            if (leaveBlance == 0) {
                                                if (!ObjectUtils.isEmpty(balanceEntity) && balanceEntity.getBreastfeedingLeaveDays() != null) {
                                                    leaveBlance = balanceEntity.getBreastfeedingLeaveDays().floatValue() - converMillsToDays(leaveRecordEntity.getDuration());
                                                } else {
                                                    leaveBlance = -converMillsToDays(leaveRecordEntity.getDuration());  //秒转换为天
                                                }
                                            }
                                            attendanceVacationBalanceEntity.setBreastfeedingLeaveDays(BigDecimal.valueOf(leaveBlance));
                                            break;
                                        case "丧假":
                                            if (leaveBlance == 0) {
                                                if (!ObjectUtils.isEmpty(balanceEntity) && balanceEntity.getBereavementLeaveDays() != null) {
                                                    leaveBlance = balanceEntity.getBereavementLeaveDays().floatValue() - converMillsToDays(leaveRecordEntity.getDuration());
                                                } else {
                                                    leaveBlance = -converMillsToDays(leaveRecordEntity.getDuration());  //秒转换为天
                                                }
                                            }
                                            attendanceVacationBalanceEntity.setBereavementLeaveDays(BigDecimal.valueOf(leaveBlance));
                                            break;
                                        case "回单位":
                                            if (leaveBlance == 0) {
                                                if (!ObjectUtils.isEmpty(balanceEntity) && balanceEntity.getBackToUnit() != null) {
                                                    leaveBlance = balanceEntity.getBackToUnit().floatValue() - converMillsToDays(leaveRecordEntity.getDuration());
                                                } else {
                                                    leaveBlance = -converMillsToDays(leaveRecordEntity.getDuration());  //秒转换为天
                                                }
                                            }
                                            attendanceVacationBalanceEntity.setBackToUnit(BigDecimal.valueOf(leaveBlance));
                                            break;
                                        case "因公请假":
                                            if (leaveBlance == 0) {
                                                if (!ObjectUtils.isEmpty(balanceEntity) && balanceEntity.getOnDutyLeave() != null) {
                                                    leaveBlance = balanceEntity.getOnDutyLeave().floatValue() - converMillsToDays(leaveRecordEntity.getDuration());
                                                } else {
                                                    leaveBlance = -converMillsToDays(leaveRecordEntity.getDuration());  //秒转换为天
                                                }
                                            }
                                            attendanceVacationBalanceEntity.setOnDutyLeave(BigDecimal.valueOf(leaveBlance));
                                            break;
                                        case "外出勘验":
                                            if (leaveBlance == 0) {
                                                if (!ObjectUtils.isEmpty(balanceEntity) && balanceEntity.getOutOfOffice() != null) {
                                                    leaveBlance = balanceEntity.getOutOfOffice().floatValue() - converMillsToDays(leaveRecordEntity.getDuration());
                                                } else {
                                                    leaveBlance = -converMillsToDays(leaveRecordEntity.getDuration());  //秒转换为天
                                                }
                                            }
                                            attendanceVacationBalanceEntity.setOutOfOffice(BigDecimal.valueOf(leaveBlance));
                                            break;
                                        case "值班补班":
                                            if (leaveBlance == 0) {
                                                if (!ObjectUtils.isEmpty(balanceEntity) && balanceEntity.getShiftCompensation() != null) {
                                                    leaveBlance = balanceEntity.getShiftCompensation().floatValue() - converMillsToDays(leaveRecordEntity.getDuration());
                                                } else {
                                                    leaveBlance = -converMillsToDays(leaveRecordEntity.getDuration());  //秒转换为天
                                                }
                                            }
                                            attendanceVacationBalanceEntity.setShiftCompensation(BigDecimal.valueOf(leaveBlance));
                                            break;
                                        case "体检":
                                            if (leaveBlance == 0) {
                                                if (!ObjectUtils.isEmpty(balanceEntity) && balanceEntity.getPhysicalExamination() != null) {
                                                    leaveBlance = balanceEntity.getPhysicalExamination().floatValue() - converMillsToDays(leaveRecordEntity.getDuration());
                                                } else {
                                                    leaveBlance = -converMillsToDays(leaveRecordEntity.getDuration());  //秒转换为天
                                                }
                                            }
                                            attendanceVacationBalanceEntity.setPhysicalExamination(BigDecimal.valueOf(leaveBlance));
                                            break;
                                        case "隔离":
                                            if (leaveBlance == 0) {
                                                if (!ObjectUtils.isEmpty(balanceEntity) && balanceEntity.getQuarantine() != null) {
                                                    leaveBlance = balanceEntity.getQuarantine().floatValue() - converMillsToDays(leaveRecordEntity.getDuration());
                                                } else {
                                                    leaveBlance = -converMillsToDays(leaveRecordEntity.getDuration());  //秒转换为天
                                                }
                                            }
                                            attendanceVacationBalanceEntity.setQuarantine(BigDecimal.valueOf(leaveBlance));
                                            break;
                                        case "因公外出":
                                            if (leaveBlance == 0) {
                                                if (!ObjectUtils.isEmpty(balanceEntity) && balanceEntity.getBusinessTrip() != null) {
                                                    leaveBlance = balanceEntity.getBusinessTrip().floatValue() - converMillsToDays(leaveRecordEntity.getDuration());
                                                } else {
                                                    leaveBlance = -converMillsToDays(leaveRecordEntity.getDuration());  //秒转换为天
                                                }
                                            }
                                            attendanceVacationBalanceEntity.setBusinessTrip(BigDecimal.valueOf(leaveBlance));
                                            break;
                                        case "公休":
                                            if (leaveBlance == 0) {
                                                if (!ObjectUtils.isEmpty(balanceEntity) && balanceEntity.getPublicHoliday() != null) {
                                                    leaveBlance = balanceEntity.getPublicHoliday().floatValue() - converMillsToDays(leaveRecordEntity.getDuration());
                                                } else {
                                                    leaveBlance = -converMillsToDays(leaveRecordEntity.getDuration());  //秒转换为天
                                                }
                                            }
                                            attendanceVacationBalanceEntity.setPublicHoliday(BigDecimal.valueOf(leaveBlance));
                                            break;
                                        case "育儿假":
                                            if (leaveBlance == 0) {
                                                if (!ObjectUtils.isEmpty(balanceEntity) && balanceEntity.getChildRearingLeave() != null) {
                                                    leaveBlance = balanceEntity.getChildRearingLeave().floatValue() - converMillsToDays(leaveRecordEntity.getDuration());
                                                } else {
                                                    leaveBlance = -converMillsToDays(leaveRecordEntity.getDuration());  //秒转换为天
                                                }
                                            }
                                            attendanceVacationBalanceEntity.setChildRearingLeave(BigDecimal.valueOf(leaveBlance));
                                            break;
                                        case "调回单位":
                                            if (leaveBlance == 0) {
                                                if (!ObjectUtils.isEmpty(balanceEntity) && balanceEntity.getTransferBack() != null) {
                                                    leaveBlance = balanceEntity.getTransferBack().floatValue() - converMillsToDays(leaveRecordEntity.getDuration());
                                                } else {
                                                    leaveBlance = -converMillsToDays(leaveRecordEntity.getDuration());  //秒转换为天
                                                }
                                            }
                                            attendanceVacationBalanceEntity.setTransferBack(BigDecimal.valueOf(leaveBlance));
                                            break;
                                        case "探亲假":
                                            if (leaveBlance == 0) {
                                                if (!ObjectUtils.isEmpty(balanceEntity) && balanceEntity.getHomeLeave() != null) {
                                                    leaveBlance = balanceEntity.getHomeLeave().floatValue() - converMillsToDays(leaveRecordEntity.getDuration());
                                                } else {
                                                    leaveBlance = -converMillsToDays(leaveRecordEntity.getDuration());  //秒转换为天
                                                }
                                            }
                                            attendanceVacationBalanceEntity.setHomeLeave(BigDecimal.valueOf(leaveBlance));
                                            break;
                                        default:
                                            if (leaveBlance == 0) {
                                                if (!ObjectUtils.isEmpty(balanceEntity) && balanceEntity.getPersonalLeaveDays() != null) {
                                                    leaveBlance = balanceEntity.getPersonalLeaveDays().floatValue() - converMillsToDays(leaveRecordEntity.getDuration());
                                                } else {
                                                    leaveBlance = -converMillsToDays(leaveRecordEntity.getDuration());  //秒转换为天
                                                }
                                            }
                                            attendanceVacationBalanceEntity.setOther(BigDecimal.valueOf(leaveBlance));
                                            break;
                                    }
                                }

                                //审批状态为同意过后再修改假期余额
                                if (result.getResult().compareToIgnoreCase("AGREE") == 0) {
                                    AttendanceVacationBalanceEntity entity = balanceService.selectOne(new AttendanceVacationBalanceQuery().remark(processInstanceId));
                                    if (ObjectUtils.isEmpty(entity)) {  //当表中没有这条processInstanceId关联的数据表示没有扣除假期（钉钉会推送两条余额数据过来 需要加这个判断）
                                        //更新假期余额表
                                        if (ObjectUtils.isEmpty(balanceEntity)) {
                                            attendanceVacationBalanceEntity.setCreateUserId(1L);
                                            attendanceVacationBalanceEntity.setCreateTime(new Date());
                                            balanceService.save(attendanceVacationBalanceEntity);
                                        } else {
                                            //更新对象必须传入id
                                            attendanceVacationBalanceEntity.setId(balanceEntity.getId());

                                            attendanceVacationBalanceEntity.setUpdateUserId(1L);
                                            attendanceVacationBalanceEntity.setUpdateTime(new Date());
                                            balanceService.update(attendanceVacationBalanceEntity);
                                        }
                                    }

                                }


                            } else {
                                log.info("该号码(" + mobile + ")未在本系统绑定");
                            }


                        } else {
                            log.info("根据id在钉钉平台查询电话失败" + mobileRest.getMsg());
                        }
                    }


                }

            }
        } catch (DingCallbackCrypto.DingTalkEncryptException e) {
            e.printStackTrace();
        } catch (Exception e) {
            log.info("请假记录表操作异常->" + e.toString());
            throw new RuntimeException(e);
        }


    }

    /**
     * 将秒转换成天数
     *
     * @param milliseconds
     * @return
     */
    private float converMillsToDays(long milliseconds) {
        float days = ((float) milliseconds) / (60 * 60 * 8);
        return days;
    }

    /**
     * @param dateString
     * @param format
     * @param tag        标志位 是否为开始时间 如是开始时间 2023-08-03 上午 转换成 2023-08-03 9：00  如不是是开始时间 2023-08-03 上午 转换成 2023-08-03 12：00
     * @return
     */
    private Date dateFormat(String dateString, String format, boolean tag) {
        if (dateString.contains("上午")) {
            if (tag) {
                dateString = dateString.replace("上午", "09:00");
            } else {
                dateString = dateString.replace("上午", "12:00");
            }
        } else {
            if (tag) {
                dateString = dateString.replace("下午", "13:00");
            } else {
                dateString = dateString.replace("下午", "18:00");
            }
        }

        //只有日期的字符串要处理加上时间  否则会转换出错
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            sdf.parse(dateString);

            if (tag) {
                dateString += " 09:00";
            } else {
                dateString += " 18:00";
            }

            //该日期字符串只包含日期部分！
        } catch (ParseException e) {
            //该日期字符串不合法或者包含时间部分！不作处理
        }

        SimpleDateFormat dateFormat_ = new SimpleDateFormat(format);

        Date t;
        try {
            t = dateFormat_.parse(dateString);
            return t;
        } catch (ParseException e) {
            return new Date(System.currentTimeMillis());
        }
    }

//    public static void main(String[] args) {
//        String result = "{\"attachedProcessInstanceIds\":[],\"bizAction\":\"NONE\",\"businessId\":\"202401161705000413779\",\"ccUserIds\":[\"2359336301844466\",\"2352352656711393\",\"254868153920685466\"],\"createTime\":\"2024-01-16T17:05Z\",\"finishTime\":\"2024-01-17T10:15Z\",\"formComponentValues\":[{\"bizAlias\":\"type\",\"componentType\":\"DDSelectField\",\"id\":\"DDSelectField-K2BJK0RV\",\"name\":\"外出类型\"},{\"bizAlias\":\"startTime\",\"componentType\":\"DDDateField\",\"id\":\"DDDateField-K2BJK0RW\",\"name\":\"开始时间\",\"value\":\"2024-01-17\"},{\"bizAlias\":\"finishTime\",\"componentType\":\"DDDateField\",\"id\":\"DDDateField-K2BJK0RX\",\"name\":\"结束时间\",\"value\":\"2024-01-17\"},{\"bizAlias\":\"duration\",\"componentType\":\"NumberField\",\"extValue\":\"{\\\"compressedValue\\\":\\\"1f8b08000000000000009550cb4ec33010fc973d1b94422222df2a2244257a81704088c3ca76a9851b475e1b5445f977d669a141ea05dfe6a1d9f10ca0d0a9e4309ab5d706e442803611ad7bb01441be0ea053c0687db7ea1adcb3e1b228c48cbcf72980ac27766330a66008e400d8f76e7f17fcaeb5bb9c7b535465b5288bfcc4416dfd4cabafeba3a61c123d1995f3e94f85b5cd4455b2c9747aa98227c60774368a228638f34df84ca1f14d80a54793bfbc414746c0a709c4274102ff1846015ba4dbdcecd7d13bec561ae4056ff6e5c347c3231e73af8a9f0659c807b97a8a7999b29eaefd63d5133b0f39f1cf9de5dad02c5f804b25dab6f8ce18c66f8db64c7edd010000\\\",\\\"extension\\\":\\\"{\\\\\\\"tag\\\\\\\":\\\\\\\"\\\\\\\"}\\\",\\\"unit\\\":\\\"DAY\\\",\\\"_from\\\":\\\"2024-01-17\\\",\\\"_overTimeApplyUserId\\\":\\\"01575932040926359398\\\",\\\"pushTag\\\":\\\"\\\",\\\"detailList\\\":[{\\\"classInfo\\\":{\\\"restSections\\\":[],\\\"hasClass\\\":false,\\\"sections\\\":[{\\\"endAcross\\\":0,\\\"startTime\\\":1705451400000,\\\"endTime\\\":1705483800000,\\\"startAcross\\\":0}]},\\\"workDate\\\":1705420800000,\\\"isRest\\\":false,\\\"workTimeMinutes\\\":480,\\\"approveInfo\\\":{\\\"fromAcross\\\":0,\\\"toAcross\\\":0,\\\"fromTime\\\":1705451400000,\\\"durationInDay\\\":1,\\\"durationInHour\\\":8,\\\"toTime\\\":1705483800000}}],\\\"durationInDay\\\":1,\\\"_to\\\":\\\"2024-01-17\\\",\\\"isModifiable\\\":true,\\\"durationInHour\\\":8}\",\"id\":\"NumberField-K2BJK0RY\",\"name\":\"时长\",\"value\":\"1\"},{\"componentType\":\"TextareaField\",\"id\":\"外出事由\",\"name\":\"外出事由\",\"value\":\"市局有事\"},{\"componentType\":\"DDPhotoField\",\"id\":\"图片\",\"name\":\"图片\"}],\"operationRecords\":[{\"date\":\"2024-01-16T17:05Z\",\"result\":\"NONE\",\"type\":\"START_PROCESS_INSTANCE\",\"userId\":\"01575932040926359398\"},{\"date\":\"2024-01-17T09:24Z\",\"result\":\"AGREE\",\"type\":\"EXECUTE_TASK_NORMAL\",\"userId\":\"0355254921955583\"},{\"date\":\"2024-01-17T10:15Z\",\"result\":\"AGREE\",\"type\":\"EXECUTE_TASK_NORMAL\",\"userId\":\"31102532391173290\"},{\"ccUserIds\":[\"2352352656711393\",\"2359336301844466\"],\"date\":\"2024-01-17T10:15Z\",\"remark\":\"\",\"result\":\"NONE\",\"type\":\"PROCESS_CC\",\"userId\":\"01575932040926359398\"},{\"ccUserIds\":[\"254868153920685466\"],\"date\":\"2024-01-17T10:15Z\",\"remark\":\"\",\"result\":\"NONE\",\"type\":\"PROCESS_CC\",\"userId\":\"01575932040926359398\"}],\"originatorDeptId\":\"895306500\",\"originatorDeptName\":\"2B税务大厅-劳务外包人员咨询组\",\"originatorUserId\":\"01575932040926359398\",\"result\":\"agree\",\"status\":\"COMPLETED\",\"tasks\":[{\"activityId\":\"1ebf_7ae5\",\"createTime\":\"2024-01-16T17:05Z\",\"finishTime\":\"2024-01-17T09:24Z\",\"mobileUrl\":\"aflow.dingtalk.com?procInsId=9HLoKgFLTNiz1KO08qc85A07481705395941&taskId=84557347599&businessId=202401161705000413779\",\"pcUrl\":\"aflow.dingtalk.com?procInsId=9HLoKgFLTNiz1KO08qc85A07481705395941&taskId=84557347599&businessId=202401161705000413779\",\"result\":\"AGREE\",\"status\":\"COMPLETED\",\"taskId\":84557347599,\"userId\":\"0355254921955583\"},{\"activityId\":\"075a_e01a\",\"createTime\":\"2024-01-17T09:24Z\",\"finishTime\":\"2024-01-17T10:15Z\",\"mobileUrl\":\"aflow.dingtalk.com?procInsId=9HLoKgFLTNiz1KO08qc85A07481705395941&taskId=84566067197&businessId=202401161705000413779\",\"pcUrl\":\"aflow.dingtalk.com?procInsId=9HLoKgFLTNiz1KO08qc85A07481705395941&taskId=84566067197&businessId=202401161705000413779\",\"result\":\"AGREE\",\"status\":\"COMPLETED\",\"taskId\":84566067197,\"userId\":\"31102532391173290\"}],\"title\":\"李玉洁提交的外出\"}";
//        new DingPersonServiceImpl().test(result);
//    }
//
//
//    private void  test(String resultString){
//        GetProcessInstanceResponseBody.GetProcessInstanceResponseBodyResult result = JSONObject.parseObject(resultString,GetProcessInstanceResponseBody.GetProcessInstanceResponseBodyResult.class);
//        if(result.getTitle().contains("外出")){
//            List<GetProcessInstanceResponseBody.GetProcessInstanceResponseBodyResultFormComponentValues> comList = result.getFormComponentValues();
//            if(!comList.isEmpty()){
//                for (GetProcessInstanceResponseBody.GetProcessInstanceResponseBodyResultFormComponentValues componentValues : comList){
//                    switch (componentValues.name){
//                        case "开始时间":
//                            Date startTime1 = dateFormat(componentValues.getValue(), "yyyy-MM-dd HH:mm", true);
//                            log.info("开始时间："+startTime1);
//                            break;
//                        case "结束时间":
//                            Date endTime1 = dateFormat(componentValues.getValue(), "yyyy-MM-dd HH:mm", false);
//                            log.info("结束时间："+endTime1);
//                            break;
//                        case "时长":
//                            log.info("时长："+Integer.parseInt(componentValues.getValue()) + "天");
//                            break;
//                        case "外出事由":
//                            log.info("外出事由："+componentValues.getValue());
//                            break;
//                        case "图片":
//                            log.info("图片："+componentValues.getValue());
//                            break;
//                    }
//                }
//            }
//        }else if(result.getTitle().contains("出差")) {
//            List<GetProcessInstanceResponseBody.GetProcessInstanceResponseBodyResultFormComponentValues> comList = result.getFormComponentValues();
//            if (!comList.isEmpty()) {
//                for (GetProcessInstanceResponseBody.GetProcessInstanceResponseBodyResultFormComponentValues componentValues : comList) {
//                    switch (componentValues.name) {
//                        case "行程":
//                            Gson gson = new Gson();
//                            JsonArray jsonArray = gson.fromJson(componentValues.getValue(), JsonArray.class);
//                            JsonObject jsonObject = jsonArray.get(0).getAsJsonObject(); // 获取第一个对象
//                            JsonElement rowValueElement = jsonObject.get("rowValue"); // 获取rowValue字段的值
//                            JsonArray rowValueArray = rowValueElement.getAsJsonArray(); // 获取数组
//                            for (JsonElement element : rowValueArray) { // 遍历数组中的每个元素
//                                JsonObject jsonObject1 = element.getAsJsonObject(); // 获取每个元素作为对象
//                                String label = jsonObject1.get("label").getAsString(); // 获取label字段的值
//                                String value = jsonObject1.get("value").getAsString();
//                                if (label.contains("开始时间")) {
//                                    Date startTime1 = dateFormat(value, "yyyy-MM-dd HH:mm", true);
//                                    log.info("开始时间："+startTime1);
//                                }
//                                if (label.contains("结束时间")) {
//                                    Date endTime1 = dateFormat(value, "yyyy-MM-dd HH:mm", false);
//                                    log.info("结束时间："+endTime1);
//                                }
//                            }
//
//
//                            break;
//                        case "出差天数":
//                            log.info("出差天数："+Integer.parseInt(componentValues.getValue()) + "天");
//                            break;
//                        case "出差事由":
//                            log.info("出差事由："+componentValues.getValue());
//                            break;
//                        case "图片":
//                            log.info("图片："+componentValues.getValue());
//                            break;
//                    }
//                }
//            }
//        }
//    }
}
