package com.corewing.app.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.corewing.app.common.Result;
import com.corewing.app.dto.FeedbackRequest;
import com.corewing.app.entity.Feedback;
import com.corewing.app.service.FeedbackService;
import com.corewing.app.util.DingTalkUtil;
import com.corewing.app.util.I18nUtil;
import com.corewing.app.util.Ip2RegionUtil;
import com.corewing.app.util.IpUtil;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 问题反馈 Controller
 */
@RestController
@RequestMapping("/feedback")
public class FeedbackController {

    private final FeedbackService feedbackService;
    private final DingTalkUtil dingTalkUtil;
    private final Ip2RegionUtil ip2RegionUtil;

    public FeedbackController(FeedbackService feedbackService, DingTalkUtil dingTalkUtil, Ip2RegionUtil ip2RegionUtil) {
        this.feedbackService = feedbackService;
        this.dingTalkUtil = dingTalkUtil;
        this.ip2RegionUtil = ip2RegionUtil;
    }

    /**
     * 创建反馈（支持匿名提交）
     */
    @PostMapping
    public Result<String> create(@RequestBody FeedbackRequest request, HttpServletRequest httpRequest) {
        try {
            // 尝试获取当前登录用户ID（如果未登录则为null）
            Long userId = null;
            try {
                userId = StpUtil.getLoginIdAsLong();
            } catch (Exception e) {
                // 未登录，userId 保持为 null
            }

            Feedback feedback = new Feedback();
            feedback.setUserId(userId);
            feedback.setFeedbackType(request.getFeedbackType());
            feedback.setTitle(request.getTitle());
            feedback.setContent(request.getContent());
            feedback.setContact(request.getContact());

            boolean success = feedbackService.createFeedback(feedback);
            if (success) {
                // 获取提交IP和归属地
                String submitIp = IpUtil.getClientIp(httpRequest);
                String submitRegion = ip2RegionUtil.getRegion(submitIp);

                // 推送到钉钉
                sendFeedbackToDingTalk(feedback, submitIp, submitRegion);
                return Result.success(I18nUtil.getMessage("feedback.submit.success"));
            }
            return Result.error(I18nUtil.getMessage("feedback.submit.failed"));
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 查询当前用户的反馈列表
     */
    @GetMapping("/my")
    public Result<List<Feedback>> getMyFeedbackList() {
        try {
            // 获取当前登录用户ID
            Long userId = StpUtil.getLoginIdAsLong();
            List<Feedback> feedbackList = feedbackService.listByUserId(userId);
            return Result.success(feedbackList);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 根据ID查询反馈详情
     */
    @GetMapping("/{id}")
    public Result<Feedback> getById(@PathVariable Long id) {
        try {
            Feedback feedback = feedbackService.getById(id);
            if (feedback != null) {
                return Result.success(feedback);
            }
            return Result.error(I18nUtil.getMessage("feedback.not.found"));
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 分页查询反馈列表
     *
     * @param current      当前页码
     * @param size         每页数量
     * @param userId       用户ID（可选）
     * @param feedbackType 问题类型（可选）
     * @param status       状态（可选）
     */
    @GetMapping("/page")
    public Result<IPage<Feedback>> getPageList(
            @RequestParam(defaultValue = "1") Long current,
            @RequestParam(defaultValue = "10") Long size,
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false) String feedbackType,
            @RequestParam(required = false) Integer status) {
        try {
            Page<Feedback> page = new Page<>(current, size);
            IPage<Feedback> pageResult = feedbackService.pageList(page, userId, feedbackType, status);
            return Result.success(pageResult);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 更新反馈状态
     */
    @PutMapping("/{id}/status")
    public Result<String> updateStatus(@PathVariable Long id, @RequestParam Integer status) {
        try {
            boolean success = feedbackService.updateStatus(id, status);
            if (success) {
                return Result.success(I18nUtil.getMessage("feedback.status.update.success"));
            }
            return Result.error(I18nUtil.getMessage("feedback.status.update.failed"));
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 删除反馈
     */
    @DeleteMapping("/{id}")
    public Result<String> delete(@PathVariable Long id) {
        try {
            boolean success = feedbackService.removeById(id);
            if (success) {
                return Result.success(I18nUtil.getMessage("feedback.delete.success"));
            }
            return Result.error(I18nUtil.getMessage("feedback.delete.failed"));
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 测试钉钉推送
     */
    @GetMapping("/test-dingtalk")
    public Result<String> testDingTalk() {
        try {
            String title = I18nUtil.getMessage("feedback.dingtalk.test.message");
            String text = "### 🔔 钉钉推送测试\n\n这是一条测试消息，用于验证钉钉推送功能是否正常工作。\n\n**测试时间：** " +
                LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

            boolean success = dingTalkUtil.sendMarkdownMessage(title, text);
            if (success) {
                return Result.success(I18nUtil.getMessage("feedback.dingtalk.test.success"));
            } else {
                return Result.error(I18nUtil.getMessage("feedback.dingtalk.test.failed"));
            }
        } catch (Exception e) {
            return Result.error(I18nUtil.getMessage("feedback.dingtalk.test.error", e.getMessage()));
        }
    }

    /**
     * 发送反馈信息到钉钉
     */
    private void sendFeedbackToDingTalk(Feedback feedback, String submitIp, String submitRegion) {
        try {
            String title = I18nUtil.getMessage("dingtalk.feedback.title");
            StringBuilder text = new StringBuilder();
            text.append(I18nUtil.getMessage("dingtalk.feedback.header")).append("\n\n");
            text.append("---\n\n");

            // 用户信息
            if (feedback.getUserId() != null) {
                text.append(I18nUtil.getMessage("dingtalk.feedback.user.id")).append(" ")
                    .append(feedback.getUserId()).append("\n\n");
            } else {
                text.append(I18nUtil.getMessage("dingtalk.feedback.user.id")).append(" ")
                    .append(I18nUtil.getMessage("dingtalk.feedback.user.anonymous")).append("\n\n");
            }

            // 反馈类型
            text.append(I18nUtil.getMessage("dingtalk.feedback.type")).append(" ")
                .append(feedback.getFeedbackType()).append("\n\n");

            // 反馈标题
            text.append(I18nUtil.getMessage("dingtalk.feedback.title.label")).append(" ")
                .append(feedback.getTitle()).append("\n\n");

            // 反馈内容
            if (feedback.getContent() != null && !feedback.getContent().trim().isEmpty()) {
                text.append(I18nUtil.getMessage("dingtalk.feedback.content.label")).append(" \n\n")
                    .append(feedback.getContent()).append("\n\n");
            }

            // 联系方式
            if (feedback.getContact() != null && !feedback.getContact().trim().isEmpty()) {
                text.append(I18nUtil.getMessage("dingtalk.feedback.contact")).append(" ")
                    .append(feedback.getContact()).append("\n\n");
            }

            // IP 和归属地
            text.append(I18nUtil.getMessage("dingtalk.feedback.submit.ip")).append(" ")
                .append(submitIp).append("\n\n");
            text.append(I18nUtil.getMessage("dingtalk.feedback.submit.region")).append(" ")
                .append(submitRegion).append("\n\n");

            // 提交时间
            text.append(I18nUtil.getMessage("dingtalk.feedback.submit.time")).append(" ").append(
                LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
            ).append("\n\n");

            text.append("---\n\n");
            text.append(I18nUtil.getMessage("dingtalk.feedback.footer"));

            // 异步发送钉钉消息（避免阻塞用户请求）
            new Thread(() -> dingTalkUtil.sendMarkdownMessage(title, text.toString())).start();
        } catch (Exception e) {
            // 钉钉推送失败不影响反馈提交，只记录日志
            // log.error("推送反馈到钉钉失败: {}", e.getMessage(), e);
        }
    }
}
