package org.dromara.elevator.controller.wechat;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaMessage;
import cn.binarywang.wx.miniapp.constant.WxMaConstants;
import cn.binarywang.wx.miniapp.message.WxMaMessageRouter;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dromara.common.core.domain.R;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.elevator.domain.vo.EElevatorInfoVo;
import org.dromara.elevator.service.IEElevatorInfoService;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * 微信小程序
 *
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 */
@RestController
@AllArgsConstructor
@RequestMapping("/wechat/portal/ma/{appid}")
@Slf4j
public class WxMaPortalController {
    private final WxMaService wxMaService;
    private final WxMaMessageRouter wxMaMessageRouter;
    private final IEElevatorInfoService elevatorInfoService;

    /**
     * 认证消息
     */
    @GetMapping(produces = "text/plain;charset=utf-8")
    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("\n小程序接收到来自微信服务器的认证消息：signature = [{}], timestamp = [{}], nonce = [{}], echostr = [{}]",
            signature, timestamp, nonce, echostr);

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

        if (!wxMaService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }

        if (wxMaService.checkSignature(timestamp, nonce, signature)) {
            WxMaConfigHolder.remove();//清理ThreadLocal
            return echostr;
        }
        WxMaConfigHolder.remove();//清理ThreadLocal
        return "非法请求";
    }

    /**
     * 推送消息
     */
    @PostMapping(produces = "application/xml; charset=UTF-8")
    public String post(@PathVariable String appid,
                       @RequestBody String requestBody,
                       @RequestParam(name = "msg_signature", required = false) String msgSignature,
                       @RequestParam(name = "encrypt_type", required = false) String encryptType,
                       @RequestParam(name = "signature", required = false) String signature,
                       @RequestParam("timestamp") String timestamp,
                       @RequestParam("nonce") String nonce) {
        log.info("\n小程序接收微信请求：[msg_signature=[{}], encrypt_type=[{}], signature=[{}]," +
                " timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ",
            msgSignature, encryptType, signature, timestamp, nonce, requestBody);

        if (!wxMaService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }

        final boolean isJson = Objects.equals(wxMaService.getWxMaConfig().getMsgDataFormat(),
            WxMaConstants.MsgDataFormat.JSON);
        if (StringUtils.isBlank(encryptType)) {
            // 明文传输的消息
            WxMaMessage inMessage;
            if (isJson) {
                inMessage = WxMaMessage.fromJson(requestBody);
            } else {//xml
                inMessage = WxMaMessage.fromXml(requestBody);
            }

            this.route(inMessage);
            WxMaConfigHolder.remove();//清理ThreadLocal
            return "success";
        }

        if ("aes".equals(encryptType)) {
            // 是aes加密的消息
            WxMaMessage inMessage;
            if (isJson) {
                inMessage = WxMaMessage.fromEncryptedJson(requestBody, wxMaService.getWxMaConfig());
            } else {//xml
                inMessage = WxMaMessage.fromEncryptedXml(requestBody, wxMaService.getWxMaConfig(),
                    timestamp, nonce, msgSignature);
            }
            log.error("mini:{}", JsonUtils.toJsonString(inMessage));
            this.route(inMessage);
            WxMaConfigHolder.remove();//清理ThreadLocal
            return "success";
        }
        WxMaConfigHolder.remove();//清理ThreadLocal
        throw new RuntimeException("不可识别的加密类型：" + encryptType);
    }

    /**
     * 小程序查询电梯信息
     *
     * @param id 电梯id
     * @return 电梯信息
     */
    @GetMapping("/getEleInfo/{id}")
    public R<EElevatorInfoVo> getElevatorInfo(@PathVariable Long id) {
        return R.ok(elevatorInfoService.queryById(id));
    }

    private void route(WxMaMessage message) {
        try {
            wxMaMessageRouter.route(message);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

}
