package com.nbport.zgwl.seal.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.nbport.zgwl.common.R;
import com.nbport.zgwl.seal.config.SealConfig;
import com.nbport.zgwl.seal.service.SealTokenService;
import com.nbport.zgwl.seal.utils.SealHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * 签章平台代理控制器
 *
 * @author xiaofengzhou
 */
@RestController
@RequestMapping("/seal/api")
public class SealProxyController {

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

    @Autowired
    private SealConfig sealConfig;

    @Autowired
    private SealTokenService sealTokenService;

    private String proxyPost(String apiPath, String requestBody) {
        String accessToken = sealTokenService.getAccessToken();
        String url = sealConfig.getBaseUrl() + apiPath;
        log.info("代理请求签章平台: {} body: {}", url, requestBody);
        return SealHttpClient.post(url, requestBody, accessToken, MediaType.APPLICATION_JSON_VALUE);
    }

    private String proxyPost(String apiPath) {
        return proxyPost(apiPath, "{}");
    }

    private R<Object> parseSealResponse(String responseJson) {
        try {
            JSONObject result = JSON.parseObject(responseJson);
            if (result.getBooleanValue("isSuccess")) {
                return R.success(result.get("data"));
            } else {
                return R.error(result.getString("msg"));
            }
        } catch (Exception e) {
            log.error("解析签章平台响应失败: {}", responseJson, e);
            return R.error("解析签章平台响应失败: " + e.getMessage());
        }
    }

    @PostMapping("/token/getAccessToken")
    public R<Object> getAccessToken() {
        try {
            String token = sealTokenService.forceRefreshToken();
            Map<String, Object> data = new HashMap<>();
            data.put("access_token", token);
            data.put("expires_in", 7200);
            return R.success(data);
        } catch (Exception e) {
            log.error("获取Token失败", e);
            return R.error("获取Token失败: " + e.getMessage());
        }
    }

    @PostMapping("/token/clear")
    public R<String> clearToken() {
        sealTokenService.clearToken();
        return R.success("Token已清除");
    }

    @PostMapping("/qrcode/getLoginQrCode")
    public R<Object> getLoginQrCode(@RequestBody Map<String, String> params) {
        try {
            String notifyUrl = params.get("notifyUrl");
            JSONObject body = new JSONObject();
            body.put("notifyUrl", notifyUrl);
            String response = proxyPost("/saas/api/qrcode/getLoginQrCode", body.toJSONString());
            return parseSealResponse(response);
        } catch (Exception e) {
            log.error("获取身份认证二维码失败", e);
            return R.error("获取身份认证二维码失败: " + e.getMessage());
        }
    }

    @PostMapping("/contract/start")
    public R<Object> startContract(@RequestParam("file") MultipartFile file,
                                   @RequestParam("contractName") String contractName,
                                   @RequestParam(value = "description", required = false) String description) {
        try {
            String accessToken = sealTokenService.getAccessToken();
            String url = sealConfig.getBaseUrl() + "/saas/api/contract/start";
            String response = SealHttpClient.postMultipart(url, file, contractName, description, accessToken);
            return parseSealResponse(response);
        } catch (Exception e) {
            log.error("创建签署流程失败", e);
            return R.error("创建签署流程失败: " + e.getMessage());
        }
    }

    @PostMapping("/qrcode/getStandardSignQrCode")
    public R<Object> getStandardSignQrCode(@RequestBody Map<String, Object> params) {
        try {
            JSONObject body = buildSignQrCodeBody(params);
            String response = proxyPost("/saas/api/qrcode/getStandardSignQrCode", body.toJSONString());
            return parseSealResponse(response);
        } catch (Exception e) {
            log.error("获取标准签章二维码失败", e);
            return R.error("获取标准签章二维码失败: " + e.getMessage());
        }
    }

    @PostMapping("/qrcode/getPreSignQrCode")
    public R<Object> getPreSignQrCode(@RequestBody Map<String, Object> params) {
        try {
            JSONObject body = buildPreSignBody(params);
            String response = proxyPost("/saas/api/qrcode/getPreSignQrCode", body.toJSONString());
            return parseSealResponse(response);
        } catch (Exception e) {
            log.error("获取预盖章二维码失败", e);
            return R.error("获取预盖章二维码失败: " + e.getMessage());
        }
    }

    @PostMapping("/qrcode/getTrusteeshipSealQrCode")
    public R<Object> getTrusteeshipSealQrCode(@RequestBody Map<String, String> params) {
        try {
            JSONObject body = new JSONObject();
            body.put("notifyUrl", params.get("notifyUrl"));
            String response = proxyPost("/saas/api/qrcode/getTrusteeshipSealQrCode", body.toJSONString());
            return parseSealResponse(response);
        } catch (Exception e) {
            log.error("获取托管章二维码失败", e);
            return R.error("获取托管章二维码失败: " + e.getMessage());
        }
    }

    @PostMapping("/contract/confirmSign")
    public R<Object> confirmSign(@RequestBody Map<String, Object> params) {
        try {
            JSONObject body = new JSONObject(params);
            String response = proxyPost("/saas/api/contract/confirmSign", body.toJSONString());
            return parseSealResponse(response);
        } catch (Exception e) {
            log.error("托管签署失败", e);
            return R.error("托管签署失败: " + e.getMessage());
        }
    }

    @PostMapping("/seal/getTimestamp")
    public R<Object> getTimestamp(@RequestBody Map<String, String> params) {
        try {
            JSONObject body = new JSONObject();
            body.put("formatPattern", params.getOrDefault("formatPattern", "yyyy-MM-dd"));
            String response = proxyPost("/saas/api/seal/getTimestamp", body.toJSONString());
            return parseSealResponse(response);
        } catch (Exception e) {
            log.error("获取时间戳印章失败", e);
            return R.error("获取时间戳印章失败: " + e.getMessage());
        }
    }

    @PostMapping("/contract/signTimestamp")
    public R<Object> signTimestamp(@RequestBody Map<String, Object> params) {
        try {
            JSONObject body = new JSONObject(params);
            String response = proxyPost("/saas/api/contract/signTimestamp", body.toJSONString());
            return parseSealResponse(response);
        } catch (Exception e) {
            log.error("签署时间签章失败", e);
            return R.error("签署时间签章失败: " + e.getMessage());
        }
    }

    @PostMapping("/seal/getCommentSeal")
    public R<Object> getCommentSeal(@RequestBody Map<String, Object> params) {
        try {
            JSONObject body = new JSONObject();
            body.put("text", params.get("text"));
            body.put("fontSize", params.get("fontSize"));
            String response = proxyPost("/saas/api/seal/getCommentSeal", body.toJSONString());
            return parseSealResponse(response);
        } catch (Exception e) {
            log.error("获取批注章预览失败", e);
            return R.error("获取批注章预览失败: " + e.getMessage());
        }
    }

    @PostMapping("/contract/signCommentSeal")
    public R<Object> signCommentSeal(@RequestBody Map<String, Object> params) {
        try {
            JSONObject body = new JSONObject(params);
            String response = proxyPost("/saas/api/contract/signCommentSeal", body.toJSONString());
            return parseSealResponse(response);
        } catch (Exception e) {
            log.error("签署批注签章失败", e);
            return R.error("签署批注签章失败: " + e.getMessage());
        }
    }

    @PostMapping("/contract/complete")
    public R<Object> completeContract(@RequestBody Map<String, String> params) {
        try {
            JSONObject body = new JSONObject();
            body.put("contractId", params.get("contractId"));
            String response = proxyPost("/saas/api/contract/complete", body.toJSONString());
            return parseSealResponse(response);
        } catch (Exception e) {
            log.error("完成签署流程失败", e);
            return R.error("完成签署流程失败: " + e.getMessage());
        }
    }

    @PostMapping("/contract/cancel")
    public R<Object> cancelContract(@RequestBody Map<String, String> params) {
        try {
            JSONObject body = new JSONObject();
            body.put("contractId", params.get("contractId"));
            String response = proxyPost("/saas/api/contract/cancel", body.toJSONString());
            return parseSealResponse(response);
        } catch (Exception e) {
            log.error("取消签署流程失败", e);
            return R.error("取消签署流程失败: " + e.getMessage());
        }
    }

    @PostMapping("/user/getUserUniqueId")
    public R<Object> getUserUniqueId(@RequestBody Map<String, String> params) {
        try {
            JSONObject body = new JSONObject();
            body.put("name", params.get("name"));
            body.put("mobile", params.get("mobile"));
            body.put("idCode", params.get("idCode"));
            String response = proxyPost("/saas/api/user/getUserUniqueId ", body.toJSONString());
            return parseSealResponse(response);
        } catch (Exception e) {
            log.error("获取用户身份编码失败", e);
            return R.error("获取用户身份编码失败: " + e.getMessage());
        }
    }

    @PostMapping("/seal/getSealBySignerId")
    public R<Object> getSealBySignerId(@RequestBody Map<String, Object> params) {
        try {
            JSONObject body = new JSONObject(params);
            String response = proxyPost("/saas/api/seal/getSealBySignerId", body.toJSONString());
            return parseSealResponse(response);
        } catch (Exception e) {
            log.error("获取用户印章失败", e);
            return R.error("获取用户印章失败: " + e.getMessage());
        }
    }

    @PostMapping("/contract/getDetail")
    public R<Object> getContractDetail(@RequestBody Map<String, String> params) {
        try {
            JSONObject body = new JSONObject();
            body.put("contractId", params.get("contractId"));
            String response = proxyPost("/saas/api/contract/getDetail", body.toJSONString());
            return parseSealResponse(response);
        } catch (Exception e) {
            log.error("获取合约详情失败", e);
            return R.error("获取合约详情失败: " + e.getMessage());
        }
    }

    @PostMapping("/contract/preview")
    public R<Object> previewContract(@RequestBody Map<String, String> params) {
        try {
            JSONObject body = new JSONObject();
            body.put("contractId", params.get("contractId"));
            String response = proxyPost("/saas/api/contract/preview", body.toJSONString());
            return parseSealResponse(response);
        } catch (Exception e) {
            log.error("预览合约文件失败", e);
            return R.error("预览合约文件失败: " + e.getMessage());
        }
    }

    @PostMapping("/contract/download")
    public R<Object> downloadContract(@RequestBody Map<String, String> params) {
        try {
            JSONObject body = new JSONObject();
            body.put("contractId", params.get("contractId"));
            String response = proxyPost("/saas/api/contract/download", body.toJSONString());
            return parseSealResponse(response);
        } catch (Exception e) {
            log.error("下载合约文件失败", e);
            return R.error("下载合约文件失败: " + e.getMessage());
        }
    }

    @PostMapping("/user/getUserInfos")
    public R<Object> getUserInfos(@RequestBody Map<String, String> params) {
        try {
            JSONObject body = new JSONObject();
            body.put("requestId", params.get("requestId"));
            String response = proxyPost("/api/user/getUserInfos", body.toJSONString());
            return parseSealResponse(response);
        } catch (Exception e) {
            log.error("获取用户隐私数据失败", e);
            return R.error("获取用户隐私数据失败: " + e.getMessage());
        }
    }

    @PostMapping("/qrcode/getSignQrCode")
    public R<Object> getSignQrCode(@RequestBody Map<String, String> params) {
        try {
            JSONObject body = new JSONObject();
            body.put("notifyUrl", params.get("notifyUrl"));
            body.put("originalBase64Str", params.get("originalBase64Str"));
            String response = proxyPost("/saas/api/qrcode/getSignQrCode", body.toJSONString());
            return parseSealResponse(response);
        } catch (Exception e) {
            log.error("获取签名二维码失败", e);
            return R.error("获取签名二维码失败: " + e.getMessage());
        }
    }

    private JSONObject buildSignQrCodeBody(Map<String, Object> params) {
        JSONObject body = new JSONObject();
        body.put("contractId", params.get("contractId"));
        body.put("notifyUrl", params.get("notifyUrl"));
        body.put("isNeedUrlLink", params.getOrDefault("isNeedUrlLink", false));
        body.put("sealConfigs", params.get("sealConfigs"));
        body.put("pagingSealConfig", params.get("pagingSealConfig"));
        return body;
    }

    private JSONObject buildPreSignBody(Map<String, Object> params) {
        JSONObject body = new JSONObject();
        body.put("contractId", params.get("contractId"));
        body.put("notifyUrl", params.get("notifyUrl"));
        body.put("isNeedUrlLink", params.getOrDefault("isNeedUrlLink", false));
        body.put("sealConfigs", params.get("sealConfigs"));
        body.put("pagingSealConfigs", params.get("pagingSealConfigs"));
        body.put("timestampSealConfigs", params.get("timestampSealConfigs"));
        return body;
    }
}
