package org.dromara.mp.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.apache.commons.lang3.StringUtils;
import org.dromara.common.core.domain.R;
import org.dromara.common.web.core.BaseController;
import org.dromara.mp.annotation.SwitchoverCheck;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 微信公众号消息处理控制器
 *
 * @author pengles
 */
@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/wx/mp/portal/{appid}")
public class WxMpPortalController extends BaseController {

    private final WxMpService wxMpService;
    private final WxMpMessageRouter messageRouter;

    /**
     * 微信公众号服务器配置验证
     *
     * @param appid     公众号appid
     * @param signature 微信加密签名
     * @param timestamp 时间戳
     * @param nonce     随机数
     * @param echostr   随机字符串
     * @return 验证结果
     */
    @GetMapping(produces = "text/plain;charset=utf-8")
    @SwitchoverCheck
    public String authGet(@PathVariable String appid,
                          @RequestParam(name = "signature", required = false) String signature,
                          @RequestParam(name = "timestamp", required = false) String timestamp,
                          @RequestParam(name = "nonce", required = false) String nonce,
                          @RequestParam(name = "echostr", required = false) String echostr) {
        log.info("接收到来自微信服务器的认证消息：[{}, {}, {}, {}]", signature, timestamp, nonce, echostr);

        if (StringUtils.isAnyBlank(signature, timestamp, nonce, echostr)) {
            log.error("请求参数非法，请核实!");
            return "非法请求";
        }

        try {
            if (wxMpService.checkSignature(timestamp, nonce, signature)) {
                log.info("微信公众号验证成功");
                return echostr;
            } else {
                log.error("微信公众号验证失败");
                return "非法请求";
            }
        } catch (Exception e) {
            log.error("微信公众号验证异常: {}", e.getMessage(), e);
            return "验证异常";
        }
    }

    /**
     * 微信公众号消息处理
     *
     * @param appid        公众号appid
     * @param requestBody  请求体
     * @param signature    微信加密签名
     * @param timestamp    时间戳
     * @param nonce        随机数
     * @param openid       用户openid
     * @param encType      加密类型
     * @param msgSignature 消息签名
     * @param request      HTTP请求
     * @return 处理结果
     */
    @PostMapping(produces = "application/xml; charset=UTF-8")
    @SwitchoverCheck
    public String post(@PathVariable String appid,
                       @RequestBody String requestBody,
                       @RequestParam("signature") String signature,
                       @RequestParam("timestamp") String timestamp,
                       @RequestParam("nonce") String nonce,
                       @RequestParam("openid") String openid,
                       @RequestParam(name = "encrypt_type", required = false) String encType,
                       @RequestParam(name = "msg_signature", required = false) String msgSignature) {
        log.info("接收微信请求：[openid=[{}], [signature=[{}], encType=[{}], msgSignature=[{}], timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ]",
                openid, signature, encType, msgSignature, timestamp, nonce, requestBody);

        try {
            if (!wxMpService.checkSignature(timestamp, nonce, signature)) {
                log.error("非法请求，可能属于伪造的请求！");
                return "非法请求";
            }

            String out = null;
            if (encType == null) {
                // 明文传输的消息
                WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(requestBody);
                WxMpXmlOutMessage outMessage = this.route(inMessage);
                if (outMessage == null) {
                    return "";
                }
                out = outMessage.toXml();
            } else if ("aes".equalsIgnoreCase(encType)) {
                // aes加密的消息
                WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(requestBody, wxMpService.getWxMpConfigStorage(), timestamp, nonce, msgSignature);
                log.debug("消息解密后内容为：\n{} ", inMessage.toString());
                WxMpXmlOutMessage outMessage = this.route(inMessage);
                if (outMessage == null) {
                    return "";
                }
                out = outMessage.toEncryptedXml(wxMpService.getWxMpConfigStorage());
            }

            log.debug("组装回复信息：{}", out);
            return out;
        } catch (Exception e) {
            log.error("微信消息处理异常: {}", e.getMessage(), e);
            return "";
        }
    }

    /**
     * 消息路由处理
     *
     * @param message 微信消息
     * @return 回复消息
     */
    private WxMpXmlOutMessage route(WxMpXmlMessage message) {
        try {
            return this.messageRouter.route(message);
        } catch (Exception e) {
            log.error("路由消息时出现异常！", e);
            return null;
        }
    }

    /**
     * 获取微信公众号配置信息
     *
     * @param appid 公众号appid
     * @return 配置信息
     */
    @GetMapping("/config")
    @SwitchoverCheck
    public R<Object> getConfig(@PathVariable String appid) {
        try {
            Object config = wxMpService.getWxMpConfigStorage();
            return R.ok(config);
        } catch (Exception e) {
            log.error("获取微信公众号配置失败: {}", e.getMessage(), e);
            return R.fail("获取配置失败: " + e.getMessage());
        }
    }

    /**
     * 清理微信公众号配置缓存
     *
     * @param appid 公众号appid
     * @return 清理结果
     */
    @DeleteMapping("/config/cache")
    @SwitchoverCheck
    public R<Void> clearConfigCache(@PathVariable String appid) {
        try {
            // 这里可以添加清理缓存的逻辑
            log.info("清理微信公众号配置缓存: {}", appid);
            return R.ok();
        } catch (Exception e) {
            log.error("清理配置缓存失败: {}", e.getMessage(), e);
            return R.fail("清理缓存失败: " + e.getMessage());
        }
    }
}
