package com.malk.hengyilong.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.malk.hengyilong.service.EqbHylService;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.server.common.McR;
import com.malk.service.aliwork.YDClient;
import com.malk.utils.UtilMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;

/**
 * 功能：
 * 作者：hanxue
 * 日期：2026/4/24 18:00
 */
@RequestMapping
@RestController
@Slf4j
public class HylEqbController {
    @Autowired
    private YDClient ydClient;
    @Autowired
    private EqbHylService eqbService;
    @PostMapping("/quotationToEqb")
    public McR syncClient(@RequestBody Map map){
        return eqbService.quotationToEqb(map);
    }

    // 使用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 McR callback(@RequestBody Map map) {
        log.info("e签宝回调： {}", JSON.toJSONString(map));
        //签署回调通知：SIGN_MISSON_COMPLETE   签署流程完成：SIGN_FLOW_FINISH
        String action = UtilMap.getString(map, "action");
        String signFlowId = UtilMap.getString(map, "signFlowId");//e签宝签署流程id

        String info = action + "-" + signFlowId;

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

        if (isCallbackProcessed(info)){
            log.info("info:{},重复回调,不做处理",info);
        }else {
            eventList.put(info, System.currentTimeMillis());
            //签署回调结束
            if ("SIGN_MISSON_COMPLETE".equals(action)) {
                int signResult = UtilMap.getInt(map, "signResult");//2 - 签署完成，4 - 拒签
                String processInstanceId = UtilMap.getString(map, "customBizNum");//宜搭审批实例id
                if (2 == signResult) {
//                   更新宜搭报价单状态
                    ydClient.operateData(YDParam.builder()
                            .formInstanceId(processInstanceId)
                            .updateFormDataJson(JSONObject.toJSONString(UtilMap.map("selectField_mpcayrsc","已签署")))
                            .build(), YDConf.FORM_OPERATION.update);
                }else {
                    ydClient.operateData(YDParam.builder()
                            .formInstanceId(processInstanceId)
                            .updateFormDataJson(JSONObject.toJSONString(UtilMap.map("selectField_mpcayrsc","拒签")))
                            .build(), YDConf.FORM_OPERATION.update);
                }
            }
        }
        return McR.success();
    }

    /**
     * 检查并清理过期事件
     */
    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);
    }

}
