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.HashMap;
import java.util.Map;

/**
 * 邮件分发工具类
 * 调用AI邮件发送接口发送反馈邮件
 */
@Slf4j
@Component
@RefreshScope
@RequiredArgsConstructor
public class AiFeedbackEmailUtil {

    private final RestTemplate restTemplate;

    /**
     * 邮件发送接口地址
     */
    @Value("${feedback-email-url:http://124.93.18.180:9000/ai/smart-customer/api/v1/feedback_email/send}")
    private String feedbackEmailUrl;

    /**
     * 反馈类型枚举
     */
    public enum FeedbackType {
        BUG("0", "bug反馈"),
        OPTIMIZATION("1", "优化反馈"),
        NEW_FEATURE("2", "新增功能反馈");

        private final String code;
        private final String desc;

        FeedbackType(String code, String desc) {
            this.code = code;
            this.desc = desc;
        }

        public String getCode() {
            return code;
        }

        public String getDesc() {
            return desc;
        }
    }

    /**
     * 邮件发送结果类
     */
    public static class EmailSendResult {
        private boolean success;
        private String message;
        private Long ticketId;

        public EmailSendResult(boolean success, String message, Long ticketId) {
            this.success = success;
            this.message = message;
            this.ticketId = ticketId;
        }

        public boolean isSuccess() {
            return success;
        }

        public String getMessage() {
            return message;
        }

        public Long getTicketId() {
            return ticketId;
        }
    }

    /**
     * 发送反馈邮件
     *
     * @param feedbackType 问题反馈类型（0-bug反馈，1-优化反馈，2-新增功能反馈）
     * @param feedbackContent 反馈内容（必填）
     * @param userId 用户ID（可选）
     * @param feedbackSource 反馈来源（可选，0,1）
     * @param contactWay 联系方式（可选）
     * @return 邮件发送结果
     */
    public EmailSendResult sendFeedbackEmail(String feedbackType, String feedbackContent, 
                                             Integer userId, String feedbackSource, String contactWay) {
        log.info("开始发送反馈邮件：feedbackType={}, feedbackContent={}, userId={}, feedbackSource={}, contactWay={}",
                feedbackType, feedbackContent, userId, feedbackSource, contactWay);

        // 参数校验
        if (!StringUtils.hasText(feedbackContent)) {
            log.error("反馈内容不能为空");
            return new EmailSendResult(false, "反馈内容不能为空", null);
        }

        try {
            // 调用邮件发送接口
            return callFeedbackEmailApi(feedbackType, feedbackContent, userId, feedbackSource, contactWay);
        } catch (Exception e) {
            log.error("发送反馈邮件异常", e);
            return new EmailSendResult(false, "发送邮件异常：" + e.getMessage(), null);
        }
    }

    /**
     * 调用邮件发送接口
     *
     * @param feedbackType 问题反馈类型
     * @param feedbackContent 反馈内容
     * @param userId 用户ID
     * @param feedbackSource 反馈来源
     * @param contactWay 联系方式
     * @return 邮件发送结果
     */
    private EmailSendResult callFeedbackEmailApi(String feedbackType, String feedbackContent,
                                                 Integer userId, String feedbackSource, String contactWay) {
        try {
            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            if (StringUtils.hasText(feedbackType)) {
                requestBody.put("feedback_type", feedbackType);
            }
            requestBody.put("feedback_content", feedbackContent);
            if (userId != null) {
                requestBody.put("user_id", userId);
            }
            if (StringUtils.hasText(feedbackSource)) {
                requestBody.put("feedback_source", feedbackSource);
            }
            if (StringUtils.hasText(contactWay)) {
                requestBody.put("contact_way", contactWay);
            }

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);

            log.info("调用邮件发送接口：url={}, requestBody={}", feedbackEmailUrl, requestBody);

            // 发送请求
            ResponseEntity<String> response = restTemplate.postForEntity(feedbackEmailUrl, 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 parseEmailSendResult(jsonResponse);
                } else {
                    log.error("邮件发送接口返回空响应");
                    return new EmailSendResult(false, "邮件发送接口返回空响应", null);
                }
            } else {
                log.error("邮件发送接口调用失败，状态码：{}", response.getStatusCode());
                return new EmailSendResult(false, "邮件发送接口调用失败，状态码：" + response.getStatusCode(), null);
            }

        } catch (org.springframework.web.client.HttpClientErrorException e) {
            log.error("调用邮件发送接口失败，HTTP错误: {}, 响应体: {}", 
                    e.getStatusCode(), e.getResponseBodyAsString(), e);
            return new EmailSendResult(false, "调用邮件发送接口失败: " + e.getStatusCode() + 
                    ", 响应: " + e.getResponseBodyAsString(), null);
        } catch (Exception e) {
            log.error("调用邮件发送接口异常", e);
            return new EmailSendResult(false, "调用邮件发送接口异常：" + e.getMessage(), null);
        }
    }

    /**
     * 解析邮件发送结果
     *
     * @param jsonResponse API响应JSON
     * @return 邮件发送结果
     */
    private EmailSendResult parseEmailSendResult(JSONObject jsonResponse) {
        try {
            // API返回格式：
            // {
            //     "success": true,
            //     "message": "邮件通知已发送成功",
            //     "ticket_id": 1769655115282
            // }

            Boolean success = jsonResponse.getBoolean("success");
            String message = jsonResponse.getString("message");
            Long ticketId = jsonResponse.getLong("ticket_id");

            if (Boolean.TRUE.equals(success)) {
                log.info("邮件发送成功：ticketId={}, message={}", ticketId, message);
                return new EmailSendResult(true, message, ticketId);
            } else {
                log.warn("邮件发送失败：message={}", message);
                return new EmailSendResult(false, message != null ? message : "邮件发送失败", ticketId);
            }

        } catch (Exception e) {
            log.error("解析邮件发送结果异常", e);
            return new EmailSendResult(false, "解析邮件发送结果异常：" + e.getMessage(), null);
        }
    }
}

