package com.gxwebsoft.hjm.controller;

import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.hjm.dto.SubscribeMessageRequest;
import com.gxwebsoft.hjm.dto.TemplateMessageRequest;
import com.gxwebsoft.hjm.service.WxNotificationService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信通知测试控制器
 *
 * @author 科技小王子
 * @since 2025-06-15
 */
@Slf4j
@Tag(name = "微信通知测试")
@RestController
@RequestMapping("/api/hjm/wx-notification-test")
public class WxNotificationTestController extends BaseController {

    @Resource
    private WxNotificationService wxNotificationService;

    /**
     * 测试发送订单确认通知
     */
    @Operation(summary = "测试发送订单确认通知")
    @PostMapping("/test-order-notification")
    public ApiResult<?> testOrderNotification(@RequestParam String openId,
                                            @RequestParam String orderNo,
                                            @RequestParam(required = false) String templateId) {
        try {
            User loginUser = getLoginUser();
            Integer tenantId = loginUser != null ? loginUser.getTenantId() : 0;

            // 构建模板消息请求
            TemplateMessageRequest request = new TemplateMessageRequest();
            request.setToUser(openId);
            request.setTemplateId(templateId != null ? templateId : "your_order_template_id");
            request.setUrl("https://your-domain.com/order/" + orderNo);
            request.setTopColor("#173177");

            // 构建模板数据
            Map<String, TemplateMessageRequest.TemplateDataItem> data = new HashMap<>();
            data.put("first", new TemplateMessageRequest.TemplateDataItem("您的订单已确认", "#173177"));
            data.put("keyword1", new TemplateMessageRequest.TemplateDataItem(orderNo, "#173177"));
            data.put("keyword2", new TemplateMessageRequest.TemplateDataItem(
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()), "#173177"));
            data.put("remark", new TemplateMessageRequest.TemplateDataItem("感谢您的使用，如有疑问请联系客服！", "#173177"));

            request.setData(data);

            // 发送消息
            boolean success = wxNotificationService.sendTemplateMessage(tenantId, request);

            if (success) {
                return success("订单确认通知发送成功");
            } else {
                return fail("订单确认通知发送失败");
            }

        } catch (Exception e) {
            log.error("测试发送订单确认通知失败", e);
            return fail("发送失败：" + e.getMessage());
        }
    }

    /**
     * 测试发送支付成功通知
     */
    @Operation(summary = "测试发送支付成功通知")
    @PostMapping("/test-payment-notification")
    public ApiResult<?> testPaymentNotification(@RequestParam String openId,
                                              @RequestParam String orderNo,
                                              @RequestParam String amount,
                                              @RequestParam(required = false) String templateId) {
        try {
            User loginUser = getLoginUser();
            Integer tenantId = loginUser != null ? loginUser.getTenantId() : 0;

            TemplateMessageRequest request = new TemplateMessageRequest();
            request.setToUser(openId);
            request.setTemplateId(templateId != null ? templateId : "your_payment_template_id");
            request.setUrl("https://your-domain.com/order/" + orderNo);

            Map<String, TemplateMessageRequest.TemplateDataItem> data = new HashMap<>();
            data.put("first", new TemplateMessageRequest.TemplateDataItem("支付成功通知", "#173177"));
            data.put("keyword1", new TemplateMessageRequest.TemplateDataItem(orderNo, "#173177"));
            data.put("keyword2", new TemplateMessageRequest.TemplateDataItem("¥" + amount, "#FF0000"));
            data.put("keyword3", new TemplateMessageRequest.TemplateDataItem(
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()), "#173177"));
            data.put("remark", new TemplateMessageRequest.TemplateDataItem("您的订单已支付成功，我们将尽快为您处理！", "#173177"));

            request.setData(data);

            boolean success = wxNotificationService.sendTemplateMessage(tenantId, request);

            if (success) {
                return success("支付成功通知发送成功");
            } else {
                return fail("支付成功通知发送失败");
            }

        } catch (Exception e) {
            log.error("测试发送支付成功通知失败", e);
            return fail("发送失败：" + e.getMessage());
        }
    }

    /**
     * 测试发送订阅消息
     */
    @Operation(summary = "测试发送订阅消息")
    @PostMapping("/test-subscribe-notification")
    public ApiResult<?> testSubscribeNotification(@RequestParam String openId,
                                                 @RequestParam String title,
                                                 @RequestParam String content,
                                                 @RequestParam(required = false) String templateId) {
        try {
            User loginUser = getLoginUser();
            Integer tenantId = loginUser != null ? loginUser.getTenantId() : 0;

            SubscribeMessageRequest request = new SubscribeMessageRequest();
            request.setToUser(openId);
            request.setTemplateId(templateId != null ? templateId : "your_subscribe_template_id");
            request.setPage("pages/notification/detail");
            request.setMiniprogramState("formal");
            request.setLang("zh_CN");

            Map<String, SubscribeMessageRequest.SubscribeDataItem> data = new HashMap<>();
            data.put("thing1", new SubscribeMessageRequest.SubscribeDataItem(title));
            data.put("thing2", new SubscribeMessageRequest.SubscribeDataItem(content));
            data.put("time3", new SubscribeMessageRequest.SubscribeDataItem(
                new SimpleDateFormat("yyyy年MM月dd日 HH:mm").format(LocalDateTime.now())));

            request.setData(data);

            boolean success = wxNotificationService.sendSubscribeMessage(tenantId, request);

            if (success) {
                return success("订阅消息发送成功");
            } else {
                return fail("订阅消息发送失败");
            }

        } catch (Exception e) {
            log.error("测试发送订阅消息失败", e);
            return fail("发送失败：" + e.getMessage());
        }
    }

    /**
     * 测试发送系统通知
     */
    @Operation(summary = "测试发送系统通知")
    @PostMapping("/test-system-notification")
    public ApiResult<?> testSystemNotification(@RequestParam String openId,
                                             @RequestParam String message,
                                             @RequestParam(required = false) String templateId) {
        try {
            User loginUser = getLoginUser();
            Integer tenantId = loginUser != null ? loginUser.getTenantId() : 0;

            TemplateMessageRequest request = new TemplateMessageRequest();
            request.setToUser(openId);
            request.setTemplateId(templateId != null ? templateId : "your_system_template_id");
            request.setTopColor("#173177");

            Map<String, TemplateMessageRequest.TemplateDataItem> data = new HashMap<>();
            data.put("first", new TemplateMessageRequest.TemplateDataItem("系统通知", "#173177"));
            data.put("keyword1", new TemplateMessageRequest.TemplateDataItem("系统消息", "#173177"));
            data.put("keyword2", new TemplateMessageRequest.TemplateDataItem(message, "#173177"));
            data.put("keyword3", new TemplateMessageRequest.TemplateDataItem(
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()), "#173177"));
            data.put("remark", new TemplateMessageRequest.TemplateDataItem("如有疑问，请联系客服。", "#173177"));

            request.setData(data);

            boolean success = wxNotificationService.sendTemplateMessage(tenantId, request);

            if (success) {
                return success("系统通知发送成功");
            } else {
                return fail("系统通知发送失败");
            }

        } catch (Exception e) {
            log.error("测试发送系统通知失败", e);
            return fail("发送失败：" + e.getMessage());
        }
    }

    /**
     * 获取当前配置的模板列表
     */
    @Operation(summary = "获取当前配置的模板列表")
    @GetMapping("/get-templates")
    public ApiResult<?> getTemplates() {
        try {
            User loginUser = getLoginUser();
            Integer tenantId = loginUser != null ? loginUser.getTenantId() : 0;

            String response = wxNotificationService.getTemplateList(tenantId);
            return success("获取成功", response);

        } catch (Exception e) {
            log.error("获取模板列表失败", e);
            return fail("获取失败：" + e.getMessage());
        }
    }
}
