package org.dromara.main.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.domain.R;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.web.core.BaseController;
import org.dromara.main.config.WxPayConfig;
import org.dromara.main.domain.bo.CsOrderCardBo;
import org.dromara.main.domain.vo.CsOrderCardVo;
import org.dromara.main.service.ICsOrderCardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;

import org.dromara.common.satoken.utils.LoginHelper;

@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/main/order-card")
public class CsOrderCardController extends BaseController {

    @Autowired
    private WxPayConfig wxPayConfig;

    private final ICsOrderCardService orderCardService;

    /**
     * 发送结算单
     */
    @Log(title = "发送结算单", businessType = BusinessType.INSERT)
    @PostMapping("/send")
    public R<CsOrderCardVo> sendOrderCard(@Validated @RequestBody CsOrderCardBo bo) {
        // 注入当前登录客服ID（与消息发送保持一致逻辑）
        Long currentUserId = LoginHelper.getUserId();
        if (currentUserId != null) {
            bo.setSenderId(currentUserId);
        }
        return R.ok(orderCardService.sendOrderCard(bo));
    }

    /**
     * 查询结算单状态
     */
    @GetMapping("/{orderCardId}")
    public R<CsOrderCardVo> getInfo(@PathVariable Long orderCardId) {
        return R.ok(orderCardService.queryById(orderCardId));
    }

    /**
     * 用户支付结算单
     */
//    @Log(title = "支付结算单", businessType = BusinessType.UPDATE)
//    @PostMapping("/{orderCardId}/pay")
//    public R<Void> payOrderCard(@PathVariable Long orderCardId, @RequestParam Long userId) {
//        return toAjax(orderCardService.payOrderCard(orderCardId, userId));
//    }

    /**
     * 取消结算单
     */
    @Log(title = "取消结算单", businessType = BusinessType.UPDATE)
    @PutMapping("/{orderCardId}/cancel")
    public R<Void> cancelOrderCard(@PathVariable Long orderCardId) {
        return toAjax(orderCardService.cancelOrderCard(orderCardId));
    }


    @PostMapping("/{orderCardId}/create-order")
    public R<Map<String, Object>> createPayOrder(@PathVariable Long orderCardId, @RequestParam Long userId) {
        log.info("========== createPayOrder 请求: orderCardId={}, userId={} ==========", orderCardId, userId);
        return R.ok(orderCardService.createPayOrder(orderCardId, userId));
    }

    /**
     * 测评咨询时自动创建结算单
     */
    @PostMapping("/auto-create")
    public R<CsOrderCardVo> autoCreateForAssessment(
            @RequestParam Long sessionId,
            @RequestParam Long studentId,
            @RequestParam String orderName,
            @RequestParam java.math.BigDecimal orderPrice,
            @RequestParam(required = false) String orderType) {
        return R.ok(orderCardService.autoCreateForAssessment(sessionId, studentId, orderName, orderPrice, orderType));
    }


    @PostMapping("/wx-pay-notify")
    @SaIgnore
    public void wxPayNotify(HttpServletRequest request, HttpServletResponse response) {
        log.info("========== 微信支付回调入口已触发 ==========");
        log.info("请求URL: {}", request.getRequestURL().toString());
        log.info("请求Method: {}", request.getMethod());
        try {
            // 微信支付回调验签和解密（技术实现照搬photo）
            String timestamp = request.getHeader("Wechatpay-Timestamp");
            String nonce = request.getHeader("Wechatpay-Nonce");
            String signature = request.getHeader("Wechatpay-Signature");

            log.info("收到微信支付回调 - Timestamp: {}, Nonce: {}, Signature: {}", timestamp, nonce, signature);

            // 读取请求体
            StringBuilder body = new StringBuilder();
            try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    body.append(line);
                }
            }

            String requestBody = body.toString();
            log.info("微信支付回调请求体: {}", requestBody);

            // 解析支付结果
            JSONObject data = JSON.parseObject(requestBody);
            JSONObject resource = data.getJSONObject("resource");
            String ciphertext = resource.getString("ciphertext");
            String associatedData = resource.getString("associated_data");
            String nonceStr = resource.getString("nonce");

            // 解密数据
            String decryptedData = decryptFromWechat(ciphertext, associatedData, nonceStr);
            log.info("微信支付回调解密结果: {}", decryptedData);
            JSONObject paymentResult = JSON.parseObject(decryptedData);

            String orderNo = paymentResult.getString("out_trade_no");
            String tradeState = paymentResult.getString("trade_state");
            log.info("支付回调解析内容 - 订单号: {}, 交易状态: {}", orderNo, tradeState);

            if ("SUCCESS".equals(tradeState)) {
                orderCardService.handlePaySuccess(orderNo);
            } else {
                log.warn("支付状态不为SUCCESS: {}", tradeState);
            }

            // 响应微信
            response.setStatus(200);
            response.setContentType("application/json");
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", "SUCCESS");
            jsonObject.put("message", "SUCCESS");
            response.getOutputStream().write(jsonObject.toJSONString().getBytes(StandardCharsets.UTF_8));
            response.flushBuffer();

        } catch (Exception e) {
            log.error("微信支付回调处理失败", e);
            // 错误响应...
        }
    }

    private String decryptFromWechat(String ciphertext, String associatedData, String nonce) throws Exception {
        // 使用APIv3密钥解密
        byte[] key = wxPayConfig.getApiV3Key().getBytes(StandardCharsets.UTF_8);
        byte[] nonceBytes = nonce.getBytes(StandardCharsets.UTF_8);
        byte[] associatedDataBytes = associatedData.getBytes(StandardCharsets.UTF_8);
        byte[] ciphertextBytes = Base64.getDecoder().decode(ciphertext);

        // 使用AES-GCM解密
        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
        GCMParameterSpec spec = new GCMParameterSpec(128, nonceBytes);

        cipher.init(Cipher.DECRYPT_MODE, keySpec, spec);
        cipher.updateAAD(associatedDataBytes);

        byte[] plainTextBytes = cipher.doFinal(ciphertextBytes);
        return new String(plainTextBytes, StandardCharsets.UTF_8);
    }


}
