package com.nbport.zgwl.seal.controller;

import com.alibaba.fastjson2.JSON;
import com.nbport.zgwl.common.R;
import com.nbport.zgwl.contractlaunch.utils.ContractLaunchConstants;
import com.nbport.zgwl.seal.handler.SealWebSocketHandler;
import com.nbport.zgwl.seal.service.SealLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
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;

/**
 * 签章平台回调接口控制器
 *
 * 接收签章平台推送的回调通知，将关键回调写入合同操作日志表，
 * 实现签署过程全程留痕。
 *
 * @author xiaofengzhou
 */
@RestController
@RequestMapping("/seal/callback")
public class SealCallbackController {

    private static final Logger log = LoggerFactory.getLogger(SealCallbackController.class);

    @Autowired
    private SealWebSocketHandler webSocketHandler;

    @Autowired
    private SealLogService sealLogService;

    @PostMapping("/login")
    public R<String> loginCallback(@RequestBody Map<String, Object> params) {
        log.info("收到身份认证回调: {}", JSON.toJSONString(params));

        try {
            String requestId = (String) params.get("requestId");
            webSocketHandler.sendCallbackMessage(requestId, "login", params);
            // 身份认证回调记录日志（不关联具体合同）
            sealLogService.logSealAction(null, ContractLaunchConstants.ACTION_SEAL_CALLBACK,
                    "身份认证回调", "身份认证回调已接收，requestId: " + requestId, params);
            return R.success("回调接收成功");
        } catch (Exception e) {
            log.error("处理身份认证回调失败", e);
            sealLogService.logSealAction(null, ContractLaunchConstants.ACTION_SEAL_CALLBACK,
                    "身份认证回调", ContractLaunchConstants.ACTION_STATUS_FAILED,
                    "处理身份认证回调失败: " + e.getMessage(), params);
            return R.error("回调处理失败: " + e.getMessage());
        }
    }

    @PostMapping("/sign")
    public R<String> signCallback(@RequestBody Map<String, Object> params) {
        log.info("收到签署回调: {}", JSON.toJSONString(params));

        try {
            String contractId = (String) params.get("contractId");
            String requestId = (String) params.get("requestId");
            webSocketHandler.sendCallbackMessage(requestId, "sign", params);
            webSocketHandler.sendCallbackMessage(contractId, "contract_status", params);
            // 签署回调记录日志（关联到本系统合同）
            Long internalContractId = sealLogService.findContractIdBySealContractId(contractId);
            sealLogService.logSealAction(internalContractId, ContractLaunchConstants.ACTION_SEAL_CALLBACK,
                    "签署回调", "收到签章平台签署回调，签章平台合同ID: " + contractId, params);
            return R.success("回调接收成功");
        } catch (Exception e) {
            log.error("处理签署回调失败", e);
            String contractId = (String) params.get("contractId");
            Long internalContractId = sealLogService.findContractIdBySealContractId(contractId);
            sealLogService.logSealAction(internalContractId, ContractLaunchConstants.ACTION_SEAL_CALLBACK,
                    "签署回调", ContractLaunchConstants.ACTION_STATUS_FAILED,
                    "处理签署回调失败: " + e.getMessage(), params);
            return R.error("回调处理失败: " + e.getMessage());
        }
    }

    @PostMapping("/presign")
    public R<String> presignCallback(@RequestBody Map<String, Object> params) {
        log.info("收到预盖章回调: {}", JSON.toJSONString(params));

        try {
            String contractId = (String) params.get("contractId");
            String requestId = (String) params.get("requestId");
            webSocketHandler.sendCallbackMessage(requestId, "presign", params);
            webSocketHandler.sendCallbackMessage(contractId, "contract_status", params);
            // 预盖章回调记录日志（关联到本系统合同）
            Long internalContractId = sealLogService.findContractIdBySealContractId(contractId);
            sealLogService.logSealAction(internalContractId, ContractLaunchConstants.ACTION_SEAL_CALLBACK,
                    "预盖章回调", "收到签章平台预盖章回调，签章平台合同ID: " + contractId, params);
            return R.success("回调接收成功");
        } catch (Exception e) {
            log.error("处理预盖章回调失败", e);
            String contractId = (String) params.get("contractId");
            Long internalContractId = sealLogService.findContractIdBySealContractId(contractId);
            sealLogService.logSealAction(internalContractId, ContractLaunchConstants.ACTION_SEAL_CALLBACK,
                    "预盖章回调", ContractLaunchConstants.ACTION_STATUS_FAILED,
                    "处理预盖章回调失败: " + e.getMessage(), params);
            return R.error("回调处理失败: " + e.getMessage());
        }
    }

    @PostMapping("/trusteeship")
    public R<String> trusteeshipCallback(@RequestBody Map<String, Object> params) {
        log.info("收到托管章回调: {}", JSON.toJSONString(params));

        try {
            String requestId = (String) params.get("requestId");
            webSocketHandler.sendCallbackMessage(requestId, "trusteeship", params);
            // 托管章回调记录日志
            sealLogService.logSealAction(null, ContractLaunchConstants.ACTION_SEAL_CALLBACK,
                    "托管章回调", "收到签章平台托管章回调，requestId: " + requestId, params);
            return R.success("回调接收成功");
        } catch (Exception e) {
            log.error("处理托管章回调失败", e);
            sealLogService.logSealAction(null, ContractLaunchConstants.ACTION_SEAL_CALLBACK,
                    "托管章回调", ContractLaunchConstants.ACTION_STATUS_FAILED,
                    "处理托管章回调失败: " + e.getMessage(), params);
            return R.error("回调处理失败: " + e.getMessage());
        }
    }

    @PostMapping("/signQrCode")
    public R<String> signQrCodeCallback(@RequestBody Map<String, Object> params) {
        log.info("收到签名二维码回调: {}", JSON.toJSONString(params));

        try {
            String requestId = (String) params.get("requestId");
            webSocketHandler.sendCallbackMessage(requestId, "signQrCode", params);
            // 签名二维码回调记录日志
            sealLogService.logSealAction(null, ContractLaunchConstants.ACTION_SEAL_CALLBACK,
                    "签名二维码回调", "收到签章平台签名二维码回调，requestId: " + requestId, params);
            return R.success("回调接收成功");
        } catch (Exception e) {
            log.error("处理签名二维码回调失败", e);
            sealLogService.logSealAction(null, ContractLaunchConstants.ACTION_SEAL_CALLBACK,
                    "签名二维码回调", ContractLaunchConstants.ACTION_STATUS_FAILED,
                    "处理签名二维码回调失败: " + e.getMessage(), params);
            return R.error("回调处理失败: " + e.getMessage());
        }
    }

    @GetMapping("/poll/{requestId}")
    public R<Map<String, Object>> pollCallback(@PathVariable String requestId) {
        Map<String, Object> callbackData = webSocketHandler.getCallbackData(requestId);
        return R.success(callbackData);
    }
}
