package com.malk.boyang.controller;

import com.alibaba.fastjson.JSON;
import com.malk.boyang.service.BoyangService;
import com.malk.server.common.McR;
import com.malk.utils.UtilMap;
import com.malk.utils.UtilServlet;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping()
public class BoyangController {

    @Autowired
    private BoyangService boyangService;

    @PostMapping("/sign")
    public McR sign(@RequestBody Map body) {
        return boyangService.eSignSubmit(body);
    }
    @GetMapping("/retrySign")
    public McR retrySign(String businessId) {
        return boyangService.retrySign(businessId);
    }


    @GetMapping("/getOrganization")
    public McR getOrganization(String name) {
        return boyangService.getOrganization(name);
    }

    // 使用ConcurrentHashMap保证线程安全
    private final ConcurrentMap<String, Long> eventList = new ConcurrentHashMap<>();
    // 记录最后一次清理时间
    private volatile long lastCleanTime = System.currentTimeMillis();
    // 清理间隔时间(毫秒)
    private static final long CLEAN_INTERVAL = 60_000;

    @PostMapping("/callback")
    public Map callback(@RequestBody Map body) {
//        Map data = UtilServlet.getParamMap(request);
        log.info("data, {}", JSON.toJSONString(body));

        //签署流程开始：SIGN_FLOW_START；签署节点完成：SIGN_SIGNER_SIGNED；签署流程完成：SIGN_FLOW_FINISH
        String callBackDesc = UtilMap.getString(body, "callBackDesc");
        int callBackEnum = UtilMap.getInt(body, "callBackEnum");

        Map callBackProcessVO = UtilMap.getMap(body, "callBackProcessVO");
        String signFlowId = UtilMap.getString(callBackProcessVO, "processId");//e签宝签署流程id
        String processInstanceId = UtilMap.getString(callBackProcessVO, "businessNo");//钉钉审批实例id

        String info = callBackDesc + "-" + callBackEnum + signFlowId;

        // 定期清理过期记录
        cleanExpiredEvents();

        if (isCallbackProcessed(info)){
            log.info("info:{},重复回调,不做处理",info);
        }else {
            eventList.put(info, System.currentTimeMillis());
            //签署开始回写签署详情地址
            if ("SIGN_FLOW_START".equals(callBackDesc)) {
//                String signPreUrl = UtilMap.getString(callBackProcessVO, "signPreUrl");
                boyangService.start(processInstanceId,signFlowId);
            }
            //签署完成回写审批单
            if ("SIGN_FLOW_FINISH".equals(callBackDesc)) {
                boyangService.signed(processInstanceId,signFlowId);
            }
        }

        Map map = new HashMap();
        map.put("code", 0);
        map.put("msg","success");
        return map;
    }

    /**
     * 检查并清理过期事件
     */
    private void cleanExpiredEvents() {
        long currentTime = System.currentTimeMillis();
        // 只在达到清理间隔时执行清理
        if (currentTime - lastCleanTime > CLEAN_INTERVAL) {
            synchronized (this) {
                // 双重检查，避免重复清理
                if (currentTime - lastCleanTime > CLEAN_INTERVAL) {
                    long expirationTime = currentTime - TimeUnit.MINUTES.toMillis(1);
                    eventList.entrySet().removeIf(entry -> entry.getValue() < expirationTime);
                    lastCleanTime = currentTime;
                }
            }
        }
    }

    /**
     * 检查该回调事件在一分钟内是否处理过
     */
    private boolean isCallbackProcessed(String detail) {
        return eventList.containsKey(detail);
    }
}
