package com.cpop.oam.business.controller.callback;

import com.cpop.common.utils.JsonUtils;
import com.cpop.common.utils.StringUtils;
import com.cpop.oam.business.service.OamWxCpService;
import com.cpop.oam.framework.config.wxCp.WxCpConfiguration;
import io.swagger.annotations.Api;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.message.WxCpXmlMessage;
import me.chanjar.weixin.cp.bean.message.WxCpXmlOutMessage;
import me.chanjar.weixin.cp.util.crypto.WxCpCryptUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author DB
 * @createTime 2023/10/12 15:17
 * @description 企业微信认证回调接口
 */
@Api(tags = "企业微信消息接收controller")
@RestController
@RequestMapping("/wxCp/portal/{agentId}")
@Deprecated
public class WxCpPortalController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private OamWxCpService oamWxCpService;

    @GetMapping(produces = "text/plain;charset=utf-8")
    public String authGet(@PathVariable
    Integer agentId, @RequestParam(name = "msg_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) {
        this.logger.info("\n接收到来自微信服务器的认证消息：signature = [{}], timestamp = [{}], nonce = [{}], echostr = [{}]",
            signature,
            timestamp,
            nonce,
            echostr);
        if (StringUtils.isAnyBlank(signature, timestamp, nonce, echostr)) {
            throw new IllegalArgumentException("请求参数非法，请核实!");
        }
        final WxCpService wxCpService = WxCpConfiguration.getCpService(agentId);
        if (wxCpService == null) {
            throw new IllegalArgumentException(String.format("未找到对应agentId=[%d]的配置，请核实！", agentId));
        }
        if (wxCpService.checkSignature(signature, timestamp, nonce, echostr)) {
            return new WxCpCryptUtil(wxCpService.getWxCpConfigStorage()).decrypt(echostr);
        }
        return "非法请求";
    }

    @PostMapping(produces = "application/xml; charset=UTF-8")
    public String post(@PathVariable
    Integer agentId, @RequestBody
    String requestBody, @RequestParam("msg_signature")
    String signature, @RequestParam("timestamp")
    String timestamp, @RequestParam("nonce")
    String nonce) {
        this.logger.info("\n接收微信请求：[signature=[{}], timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ",
            signature,
            timestamp,
            nonce,
            requestBody);

        final WxCpService wxCpService = WxCpConfiguration.getCpService(agentId);
        WxCpXmlMessage inMessage = WxCpXmlMessage
            .fromEncryptedXml(requestBody, wxCpService.getWxCpConfigStorage(), timestamp, nonce, signature);
        this.logger.debug("\n消息解密后内容为：\n{} ", JsonUtils.toJson(inMessage));
        WxCpXmlOutMessage outMessage = this.route(agentId, inMessage);
        if (outMessage == null) {
            return "";
        }
        String out = outMessage.toEncryptedXml(wxCpService.getWxCpConfigStorage());
        this.logger.debug("\n组装回复信息：{}", out);
        return out;
    }

    private WxCpXmlOutMessage route(Integer agentId, WxCpXmlMessage message) {
        try {
            return WxCpConfiguration.getRouters().get(agentId).route(message);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 企微的o2认证可查询用户敏感信息
     * @author DB
     * @since 2023/11/17 14:42
     * @param agentId 企业微信服务应用id
     * @param code 授权码
     * @param state 信息 注册
     */
    @GetMapping(produces = "text/plain;charset=utf-8", value = "/registerCode")
    public void registerCode(@PathVariable
    Integer agentId, @RequestParam("code")
    String code, @RequestParam("state")
    String state) {
        oamWxCpService.registerCode(agentId, code);
    }

}
