package shop.alien.store.util.ai;

import com.alibaba.fastjson2.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Objects;

/**
 * 小票审核工具类
 * 调用消费凭证核验接口审核评论图片是否为真实消费凭证（小票、支付记录等）
 */
@Slf4j
@Component
@RefreshScope
@RequiredArgsConstructor
public class ReceiptAuditUtil {

    private final RestTemplate restTemplate;
    private final AiAuthTokenUtil aiAuthTokenUtil;

    /**
     * 小票审核接口地址
     */
    @Value("${ai.service.receipt-audit-url:http://183.252.196.135:9000/ai/multimodal-services/api/v1/consumption-proof/verify}")
    private String receiptAuditUrl;

    /**
     * 审核结果类
     */
    public static class ReceiptAuditResult {
        private boolean passed;
        private String failureReason;
        private boolean isValidProof;
        private String proofType;

        public ReceiptAuditResult(boolean passed, String failureReason) {
            this.passed = passed;
            this.failureReason = failureReason;
        }

        public ReceiptAuditResult(boolean passed, String failureReason, boolean isValidProof, String proofType) {
            this.passed = passed;
            this.failureReason = failureReason;
            this.isValidProof = isValidProof;
            this.proofType = proofType;
        }

        public boolean isPassed() {
            return passed;
        }

        public String getFailureReason() {
            return failureReason;
        }

        public boolean isValidProof() {
            return isValidProof;
        }

        public String getProofType() {
            return proofType;
        }
    }

    /**
     * 审核评论图片是否为真实消费凭证
     *
     * @param imageUrls 图片URL列表
     * @param storeName 店铺名称（可选，用于核验凭证中的商户是否匹配）
     * @return 审核结果
     */
    public ReceiptAuditResult auditReceipt(List<String> imageUrls, String storeName) {
        log.info("开始小票审核：imageCount={}, storeName={}",
                imageUrls != null ? imageUrls.size() : 0, storeName);

        try {
            // 如果没有图片，直接返回审核通过（不强制要求必须有小票）
            if (imageUrls == null || imageUrls.isEmpty()) {
                log.info("没有图片，跳过小票审核");
                return new ReceiptAuditResult(true, null, false, null);
            }

            // 调用审核接口
            return callReceiptAuditApi(imageUrls, storeName);

        } catch (Exception e) {
            log.error("小票审核异常", e);
            // 审核异常时，为了不影响用户体验，默认通过（但记录日志）
            return new ReceiptAuditResult(true, "小票审核异常，已通过", false, null);
        }
    }

    /**
     * 调用小票审核接口
     *
     * @param imageUrls 图片URL列表
     * @param storeName 店铺名称
     * @return 审核结果
     */
    private ReceiptAuditResult callReceiptAuditApi(List<String> imageUrls, String storeName) {
        try {
            // 获取访问令牌
            String accessToken = aiAuthTokenUtil.getAccessToken();
            if (!StringUtils.hasText(accessToken)) {
                log.error("调用小票审核接口失败，获取accessToken失败");
                return new ReceiptAuditResult(true, "获取访问令牌失败，已通过", false, null);
            }
            
            // 构建请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + accessToken);

            // 构建请求体
            JSONObject requestBody = new JSONObject();
            requestBody.put("image_urls", imageUrls);
            if (StringUtils.hasText(storeName)) {
                requestBody.put("store_name", storeName);
            }

            String requestBodyStr = requestBody.toJSONString();
            if (requestBodyStr == null || requestBodyStr.isEmpty()) {
                log.error("构建小票审核请求体失败");
                return new ReceiptAuditResult(true, "构建请求体失败，已通过", false, null);
            }
            // 确保 requestBodyStr 不为 null（用于消除 IDE 警告）
            String nonNullRequestBody = Objects.requireNonNull(requestBodyStr);
            HttpEntity<String> requestEntity = new HttpEntity<>(nonNullRequestBody, headers);

            log.info("调用小票审核接口：url={}, imageCount={}, storeName={}",
                    receiptAuditUrl, imageUrls.size(), storeName);

            // 发送请求
            ResponseEntity<String> response = restTemplate.postForEntity(receiptAuditUrl, requestEntity, String.class);

            if (response.getStatusCode() == HttpStatus.OK) {
                String responseBody = response.getBody();
                log.info("小票审核接口响应：{}", responseBody);

                if (StringUtils.hasText(responseBody)) {
                    JSONObject jsonResponse = JSONObject.parseObject(responseBody);
                    return parseReceiptAuditResult(jsonResponse);
                } else {
                    log.error("小票审核接口返回空响应");
                    return new ReceiptAuditResult(true, "小票审核接口返回空响应，已通过", false, null);
                }
            } else {
                log.error("小票审核接口调用失败，状态码：{}", response.getStatusCode());
                return new ReceiptAuditResult(true, "小票审核接口调用失败，已通过", false, null);
            }

        } catch (Exception e) {
            log.error("调用小票审核接口异常", e);
            return new ReceiptAuditResult(true, "小票审核接口调用异常，已通过", false, null);
        }
    }

    /**
     * 解析小票审核结果
     *
     * @param jsonResponse API响应JSON
     * @return 审核结果
     */
    private ReceiptAuditResult parseReceiptAuditResult(JSONObject jsonResponse) {
        try {
            // API返回格式：
            // {
            //     "code": 200,
            //     "message": "操作成功",
            //     "data": {
            //         "can_comment": true/false,
            //         "is_valid_proof": true/false,
            //         "proof_type": "小票"/"支付记录"等,
            //         "reason": "核验结论说明",
            //         "image_results": [...]
            //     },
            //     "timestamp": 1704067200.123
            // }

            Integer code = jsonResponse.getInteger("code");
            if (code == null || code != 200) {
                String message = jsonResponse.getString("message");
                log.warn("小票审核接口返回错误：code={}, message={}", code, message);
                // 接口返回错误时，为了不影响用户体验，默认通过
                return new ReceiptAuditResult(true, "小票审核接口返回错误，已通过", false, null);
            }

            JSONObject data = jsonResponse.getJSONObject("data");
            if (data == null) {
                log.warn("小票审核接口返回数据为空");
                return new ReceiptAuditResult(true, "小票审核接口返回数据为空，已通过", false, null);
            }

            Boolean canComment = data.getBoolean("can_comment");
            Boolean isValidProof = data.getBoolean("is_valid_proof");
            String proofType = data.getString("proof_type");
            String reason = data.getString("reason");

            if (canComment != null && canComment) {
                // 允许评论，审核通过
                log.info("小票审核通过：isValidProof={}, proofType={}, reason={}", isValidProof, proofType, reason);
                return new ReceiptAuditResult(true, null, isValidProof != null && isValidProof, proofType);
            } else {
                // 不允许评论，审核失败
                String failureReason = StringUtils.hasText(reason) ? reason : "图片不是有效的消费凭证";
                log.warn("小票审核失败：reason={}", failureReason);
                return new ReceiptAuditResult(false, failureReason, isValidProof != null && isValidProof, proofType);
            }

        } catch (Exception e) {
            log.error("解析小票审核结果异常", e);
            return new ReceiptAuditResult(true, "解析小票审核结果异常，已通过", false, null);
        }
    }
}
