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

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.annotation.UnAuth;

import com.mortals.xhx.module.attendance.dingmsg.DingCallbackCrypto;

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.service.StaffService;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

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.util.Map;



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

    @Autowired
    private IDingPersonService dingPersonService;

    /**
     * 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 + "事件" );
                dingPersonService.handleByProcessInstanceId(processInstanceId);
            } else {
                // 添加其他已注册的
                log.info("发生了：" + eventType + "事件");
            }

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

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

    }

}
