package com.ruoyi.ai.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.ai.domain.*;
import com.ruoyi.ai.service.*;
import com.ruoyi.common.core.domain.entity.AiUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.sign.RSAUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
public class YuZhouService implements IYuZhouService {

    @Value("${yuzhou.url}")
    private String url;
    @Value("${yuzhou.appId}")
    private String appId;
    @Value("${yuzhou.publicKey}")
    private String publicKey;
    @Value("${yuzhou.secretKey}")
    private String secretKey;
    @Value("${yuzhou.redirectUrl}")
    private String redirectUrl;
    @Value("${yuzhou.callbackUrl}")
    private String callbackUrl;
    @Autowired
    private IAiUserService aiUserService;
    @Autowired
    private IAiRechargeGiftGearService aiRechargeGiftGearService;
    @Autowired
    private IAiRechargeService aiRechargeService;
    @Autowired
    private IAiRechargeGiftService aiRechargeGiftService;


    @Override
    public PayResVO pay(Long gearId) throws Exception {

        //充值挡位查询
        AiRechargeGiftGear aiRechargeGiftGear = aiRechargeGiftGearService.selectAiRechargeGiftGearById(gearId);
        if (aiRechargeGiftGear == null) {
            throw new ServiceException("The gear position does not exist.", -1);
        }
        BigDecimal amount = aiRechargeGiftGear.getRechargeAmount();
        //汇率
        //amount = amount.multiply(new BigDecimal(60.00));

        String uuid = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 8);
        String dateTime = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String orderNo = dateTime + "yz" + uuid;

        // 获取用户信息
        AiUser userInfo = aiUserService.getUserInfo(SecurityUtils.getAiUserId());
        
        // 处理用户姓名，如果没有则使用默认值
        String firstName = "John";
        String lastName = "Doe";
        if (userInfo.getNickname() != null && !userInfo.getNickname().trim().isEmpty()) {
            String[] nameParts = userInfo.getNickname().trim().split("\\s+");
            if (nameParts.length >= 2) {
                firstName = nameParts[0];
                lastName = nameParts[nameParts.length - 1];
            } else if (nameParts.length == 1) {
                firstName = nameParts[0];
            }
        }
        
        // 从用户表获取邮箱
        String email = userInfo.getEmail();
        if (email == null || email.trim().isEmpty()) {
            log.warn("用户邮箱为空 userId: {}, nickname: {}", userInfo.getId(), userInfo.getNickname());
            // 如果用户邮箱为空，使用默认邮箱格式
            email = "user" + userInfo.getId() + "@example.com";
        } else {
            email = email.trim();
        }
        
        // 处理电话，如果没有则使用默认值
        String phone = userInfo.getPhone();
        if (phone == null || phone.trim().isEmpty()) {
            phone = "1234567890";
        } else {
            // 确保电话是10位数字
            phone = phone.replaceAll("[^0-9]", "");
            if (phone.length() < 10) {
                // 如果不足10位，用0补齐
                phone = String.format("%010d", phone.length() > 0 ? Long.parseLong(phone) : 0);
            } else if (phone.length() > 10) {
                // 如果超过10位，取后10位
                phone = phone.substring(phone.length() - 10);
            }
        }

        // 构建请求参数
        Map<String, Object> createMap = new HashMap<>();
        createMap.put("merchantNo", appId);
        createMap.put("orderNo", orderNo);
        createMap.put("money", amount.toString());
        createMap.put("description", "Recharge");
        createMap.put("email", email);
        createMap.put("phone", phone);
        createMap.put("notifyUrl", callbackUrl + "/api/pay/yuzhou-callBack");
        createMap.put("expiredPeriod", "1440");
        createMap.put("currency", "USD");
        createMap.put("firstName", firstName);
        createMap.put("lastName", lastName);
        createMap.put("street", "123 Main Street");
        createMap.put("city", "New York");
        createMap.put("state", "NY");
        createMap.put("country", userInfo.getCountry() != null && !userInfo.getCountry().trim().isEmpty() ? userInfo.getCountry() : "US");
        createMap.put("postcode", "10001");
        
        // 生成签名（注意：签名时不包括signature字段）
        String signedStr = RSAUtils.getSignStr(createMap, secretKey);
        createMap.put("signature", signedStr);
        
        String postStr = JSONUtil.toJsonStr(createMap);
        log.info("yuzhou支付请求参数: {}", postStr);
        
        // 调用新的接口地址
        String response = HttpRequest.post(url + "/gateway/US/payIn")
                .header("Content-Type", "application/json; charset=utf-8")
                .body(postStr)
                .execute()
                .body();
        
        log.info("yuzhou支付响应: {}", response);
        
        JSONObject returnObj = JSONUtil.parseObj(response);
        Integer code = returnObj.getInt("code");
        if (200 != code) {
            String msg = returnObj.getStr("msg");
            log.error("yuzhou支付请求的响应异常 code: {}, msg: {}, response: {}", code, msg, returnObj);
            throw new ServiceException("yuzhoupay request failed: " + (msg != null ? msg : "unknown error"), code);
        }
        
        JSONObject data = returnObj.getJSONObject("data");
        if (data == null) {
            log.error("yuzhou支付响应数据为空: {}", returnObj);
            throw new ServiceException("yuzhoupay response data is null", -1);
        }
        
        String money = data.getStr("money");
        String payUrl = data.getStr("url");
        String platformOrderNo = data.getStr("platformOrderNo");
        
        if (payUrl == null || payUrl.trim().isEmpty()) {
            log.error("yuzhou支付URL为空: {}", data);
            throw new ServiceException("yuzhoupay url is null", -1);
        }
        
        // 创建充值管理
        AiRecharge aiRecharge = new AiRecharge();
        aiRecharge.setOrderNum(orderNo);
        aiRecharge.setUserId(SecurityUtils.getAiUserId());
        aiRecharge.setAmount(new BigDecimal(money != null ? money : amount.toString()));
        aiRecharge.setGearId(gearId);
        aiRecharge.setSource(userInfo.getSource());
        aiRecharge.setGearAmount(aiRechargeGiftGear.getRechargeAmount());
        AiRechargeGift aiRechargeGift = aiRechargeGiftService.selectAiRechargeGiftById(aiRechargeGiftGear.getRechargeId());
        aiRecharge.setPayType(aiRechargeGift.getPayType());
        aiRecharge.setPayUrl(payUrl);
        aiRechargeService.insertAiRecharge(aiRecharge);
        
        PayResVO payResVO = new PayResVO();
        payResVO.setOrderNo(orderNo);
        payResVO.setPayUrl(payUrl);
        return payResVO;
    }

    @Override
    public String callBack(Map<String, Object> map) throws Exception {
        log.info("yuzhou支付回调接收参数: {}", map);
        
        // 验证必要参数
        if (map == null || map.isEmpty()) {
            log.error("yuzhou支付回调参数为空");
            return "FAIL";
        }
        
        Object statusObj = map.get("status");
        Object orderNoObj = map.get("orderNo");
        
        if (statusObj == null || orderNoObj == null) {
            log.error("yuzhou支付回调缺少必要参数: status={}, orderNo={}", statusObj, orderNoObj);
            return "FAIL";
        }
        
        int status = Integer.parseInt(statusObj.toString());
        String orderNo = orderNoObj.toString();
        
        log.info("yuzhou支付回调 orderNo: {}, status: {}", orderNo, status);
        
        // 验证签名
        Object signatureObj = map.get("signature");
        if (signatureObj == null) {
            log.error("yuzhou支付回调缺少签名参数 orderNo: {}", orderNo);
            return "FAIL";
        }
        
        JSONObject entries = JSONUtil.parseObj(map);
        boolean verifyResult = RSAUtils.verifySign(entries, publicKey);
        if (!verifyResult) {
            log.error("yuzhou支付回调签名验证失败 orderNo: {}", orderNo);
            log.error("yuzhou支付回调签名: {}", signatureObj);
            log.error("yuzhou支付回调完整报文: {}", map);
            return "FAIL";
        }
        
        log.info("yuzhou支付回调签名验证成功 orderNo: {}", orderNo);
        
        // 判断订单状态，10表示成功
        if (10 != status) {
            log.warn("yuzhou支付订单状态非成功 orderNo: {}, status: {}", orderNo, status);
            return "SUCCESS"; // 即使失败也返回SUCCESS，避免重复回调
        }
        
        // 充值成功处理
        try {
            aiRechargeService.addRecharge(orderNo);
            log.info("yuzhou支付回调处理成功 orderNo: {}", orderNo);
            return "SUCCESS";
        } catch (Exception e) {
            log.error("yuzhou支付回调处理失败 orderNo: {}", orderNo, e);
            return "FAIL";
        }
    }


}
