package com.mortals.xhx.module.attendance.dingmsg.api;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.dingtalkattendance_1_0.models.GetLeaveRecordsResponseBody;
import com.aliyun.dingtalkworkflow_1_0.models.GetProcessInstanceResponseBody;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.response.OapiAttendanceVacationQuotaListResponse;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.mortals.framework.annotation.UnAuth;
import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException;
import com.mortals.xhx.common.code.LeaveRulesEnum;
import com.mortals.xhx.common.pdu.ApiRespPdu;
import com.mortals.xhx.module.attendance.dingmsg.DingCallbackCrypto;
import com.mortals.xhx.module.attendance.dingmsg.dingmsgreq.DingResponsMeassageReq;
import com.mortals.xhx.module.attendance.dingmsg.dingmsgreq.EncryptReq;
import com.mortals.xhx.module.attendance.model.AttendanceLeaveRecordEntity;
import com.mortals.xhx.module.attendance.model.AttendanceLeaveRecordQuery;
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.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 lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.Log;
import org.apache.poi.ss.formula.functions.T;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static cn.hutool.core.date.DatePattern.*;

/**
 *
 * 接收钉钉的审批消息推送
 *
 * @author ZYW
 * @date 2023-07-18 9:52
 */
@RestController
@Slf4j
public class DingMessageController {

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

    /**
     * appKey
     */
    @Value("${dingtalk.AppKey:''}")
    protected String appKey;
    /**
     * aesKey
     */
    @Value("${dingtalk.AesKey:''}")
    protected String aesKey;

    /**
     * 订阅消息token
     */
    @Value("${dingtalk.token:''}")
    protected String token;

    /**
     * 接收钉钉消息
     *
     * @return
     */
    @PostMapping("/dingtalk/getOaMeassge")
    @UnAuth
    public Map<String, String> getOaMessage(@RequestParam(value = "msg_signature", required = false) String msg_signature,
                                            @RequestParam(value = "timestamp", required = false) String timeStamp,
                                            @RequestParam(value = "nonce", required = false) String nonce,
                                            @RequestBody(required = false) JSONObject json)  {
        log.info("钉钉推送参数：" + msg_signature+"---"+timeStamp+"---"+nonce+"---"+json.toJSONString() );
        try {
            //  从http请求中获取加解密参数
            DingCallbackCrypto callbackCrypto = new DingCallbackCrypto(token, aesKey, appKey);
            String encryptMsg = json.getString("encrypt");
            String decryptMsg = callbackCrypto.getDecryptMsg(msg_signature, timeStamp, nonce, encryptMsg);

            // 反序列化回调事件json数据
            JSONObject eventJson = JSON.parseObject(decryptMsg);
            String eventType = eventJson.getString("EventType");
            String processInstanceId = eventJson.getString("processInstanceId");

            // 根据EventType分类处理
            if("bpms_instance_change".equals(eventType) || "bpms_task_change".equals(eventType)){  //请假等需要审批的消息
                // 处理审批实例始末（审批任务开始、结束）
                // 存入数据库
//                log.info("发生了：" + eventType + "事件" );
                if(processInstanceId != null){
                    Rest<GetProcessInstanceResponseBody.GetProcessInstanceResponseBodyResult> rest = dingPersonService.getOaRecordsById(processInstanceId);
                    if(rest.getCode() == Rest.SUCCESS){
                        GetProcessInstanceResponseBody.GetProcessInstanceResponseBodyResult result = rest.getData();
                        log.info("审批详情："+JSONObject.toJSONString(result) );
                        AttendanceLeaveRecordEntity leaveRecordEntity = new AttendanceLeaveRecordEntity();

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

                        Rest<String> mobileRest = dingPersonService.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());



//                                if(result.getTasks().size() >0 ){
//                                    if(result.getTasks().get(0).getCreateTime() != null && result.getTasks().get(0).getFinishTime() != null){
//                                        Date startTime = dateFormat(result.getTasks().get(0).getCreateTime(),"yyyy-MM-dd'T'HH:mm'Z'",false);
//
//                                        Date endTime = dateFormat(result.getTasks().get(0).getFinishTime(),"yyyy-MM-dd'T'HH:mm'Z'",false);
//                                        leaveRecordEntity.setStartTime(startTime);
//                                        leaveRecordEntity.setEndTime(endTime);
//                                        leaveRecordEntity.setDuration((int) ((endTime.getTime() - startTime.getTime())/1000));
//                                    }
//                                }

                                String leave_code = LeaveRulesEnum.事假.getLeave_code();
                                String leave_name = "事假";
                                if(result.getFormComponentValues().size() > 0 ){
                                    JSONArray jsonArray = JSONArray.parseArray(result.getFormComponentValues().get(0).getValue());
                                    if(jsonArray.size() > 0){
                                        Date startTime1 = dateFormat(jsonArray.get(0).toString(),"yyyy-MM-dd HH:mm",true);
                                        leaveRecordEntity.setStartTime(startTime1);
                                    }
                                    if(jsonArray.size() > 1){
                                        Date endTime1 = dateFormat(jsonArray.get(1).toString(),"yyyy-MM-dd HH:mm",false);
                                        leaveRecordEntity.setEndTime(endTime1);
                                    }
                                    if(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*24)); //天转换成秒
                                                    break;
                                                default:  //除了按天和半天计算的假期  其余都是按小时返回
                                                    leaveRecordEntity.setDuration((int) (Float.parseFloat(jsonArray.get(2).toString())*60*60)); //小时转换成秒
                                                    break;

                                            }
                                        }

                                    }
                                    if(jsonArray.size() > 4){
                                        leave_name = jsonArray.get(4).toString();
                                        switch (leave_name){
                                            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(1);  //默认事假
                                                leave_code = LeaveRulesEnum.事假.getLeave_code();
                                                break;

                                        }

                                    }

                                } else if (result.getFormComponentValues().size() > 1) {  //请假理由
                                    GetProcessInstanceResponseBody.GetProcessInstanceResponseBodyResultFormComponentValues resonEntity = result.getFormComponentValues().get(1);
                                    leaveRecordEntity.setReason(resonEntity.getValue());
                                }else if (result.getFormComponentValues().size() > 2) {  //上传的附件
                                    GetProcessInstanceResponseBody.GetProcessInstanceResponseBodyResultFormComponentValues picEntity = result.getFormComponentValues().get(2);
                                    if(picEntity.getName().equals("图片") && picEntity.getValue() != null){
                                        leaveRecordEntity.setAttachmentPath(picEntity.getValue());
                                    }
                                }


                                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){
//                                    if(result.getTasks().size() > 1){
//                                        if(result.getTasks().get(1).getStatus().compareToIgnoreCase("CANCELED") == 0){
//                                            leaveRecordEntity.setAuditResult(4);  //撤销审批完成
//                                        }else {
//                                            leaveRecordEntity.setAuditResult(1);
//                                        }
//                                    }
                                    leaveRecordEntity.setAuditResult(1);
                                }
                                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(3);  //撤销审批中
                                        }
                                    }
                                }
                                else {
                                    leaveRecordEntity.setAuditResult(2);  //请假审批中
                                }




                                log.info("钉钉返回的result:"+result.getResult()+"---auditresult:"+leaveRecordEntity.getAuditResult());
                                leaveRecordEntity.setAuditDesc(result.getOperationRecords().get(0).getRemark());
                                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);
                                }

                                //假期余额
                                AttendanceVacationBalanceEntity attendanceVacationBalanceEntity = new AttendanceVacationBalanceEntity();
                                //查询假期余额
                                Rest<OapiAttendanceVacationQuotaListResponse.OapiLeaveQuotaUserListVo> leaveRecordsResponseBodyResultRest =
                                        dingPersonService.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.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.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.setPersonalLeaveDays(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());
                        }





                    }

                }
            }
            else {
                // 添加其他已注册的
                log.info("发生了：" + eventType + "事件");
            }

            // 5. 返回success的加密数据
            Map<String, String> successMap = callbackCrypto.getEncryptedMap("success");
            return successMap;

        } catch (DingCallbackCrypto.DingTalkEncryptException e) {
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 将秒转换成天数
     * @param milliseconds
     * @return
     */
    private float converMillsToDays(long milliseconds){
        float days = ((float) milliseconds) / (60*60*24);
        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 dateFormat_ = new SimpleDateFormat(format);

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

}
