package com.huiju.estateagents.controller;

import com.huiju.estateagents.base.BaseController;
import com.huiju.estateagents.common.CommConstant;
import com.huiju.estateagents.common.WxUtils;
import com.huiju.estateagents.entity.TaMiniapp;
import com.huiju.estateagents.redpack.entity.TaMpPerson;
import com.huiju.estateagents.redpack.service.ITaMpPersonService;
import com.huiju.estateagents.service.IMiniAppService;
import com.huiju.estateagents.third.entity.TaMpInfo;
import com.huiju.estateagents.third.service.ITaMpInfoService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpKefuService;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/api/mp/portal/{appid}")
public class WxPortalController extends BaseController {

    @Autowired
    ITaMpInfoService iTaMpInfoService;

    @Autowired
    ITaMpPersonService iTaMpPersonService;

    @Autowired
    private IMiniAppService iMiniAppService;

    @Autowired
    WxUtils wxUtils;

    @Value("${wx.miniapp.index}")
    String miniAppIndex;

    /**
     * 微信公众号接入
     * @param appid
     * @param signature
     * @param timestamp
     * @param nonce
     * @param echostr
     * @return
     */
    @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) {
        return echostr;
    }

    @PostMapping(produces = "application/xml; charset=UTF-8")
    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("\n接收微信请求：[openid=[{}], [signature=[{}], encType=[{}], msgSignature=[{}],"
                        + " timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ",
                openid, signature, encType, msgSignature, timestamp, nonce, requestBody);

        WxMpService mpService = wxUtils.getMpService().switchoverTo(appid);
        if (null == mpService) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }

        if (!mpService.checkSignature(timestamp, nonce, signature)) {
            throw new IllegalArgumentException("非法请求，可能属于伪造的请求！");
        }

        // 对应表数据
        TaMpInfo mpInfo = iTaMpInfoService.getById(appid);

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

        // 关注公众号
        if (inMessage.getMsgType().equals(WxConsts.XmlMsgType.EVENT) && inMessage.getEvent().equals(WxConsts.EventType.SUBSCRIBE)) {
            // 新增人员
            TaMpPerson taMpPerson = new TaMpPerson();
            taMpPerson.setAppid(appid);
            taMpPerson.setMpOpenid(openid);
            taMpPerson.setOrgId(mpInfo.getOrgId());
            taMpPerson.setCreateDate(LocalDateTime.now());
            taMpPerson.setStatus(CommConstant.STATUS_NORMAL);
            TaMpPerson person = iTaMpPersonService.newPerson(taMpPerson);

            // 发送客服消息
            sendMiniAppKefuMessage(mpService, encType, mpInfo, inMessage, person);
        }

        return "";
    }

    private void sendMiniAppKefuMessage(WxMpService mpService, String encType, TaMpInfo mpInfo, WxMpXmlMessage message, TaMpPerson person) {

        TaMiniapp taMiniapp = iMiniAppService.getAppByOrg(mpInfo.getOrgId());

        WxMpKefuMessage kefuMessage = WxMpKefuMessage.MINIPROGRAMPAGE().appId(taMiniapp.getMiniappId())
                .title(taMiniapp.getName() + "欢迎您!")
                .pagePath(miniAppIndex + "?mpOpenId=" + message.getOpenId())
                .thumbMediaId(mpInfo.getMiniappMedia())
                .build();

        try {
            mpService.getKefuService().sendKefuMessage(kefuMessage);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
    }
}
