package com.jeequan.jeepay.pay.ctrl.wxmp;

import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.interfaces.wxmp.IWxMpTemplateMsgService;
import com.jeequan.jeepay.core.model.DBWxMpConfig;
import com.jeequan.jeepay.core.model.wx.wxmp.WxUserInfo;
import com.jeequan.jeepay.pay.ctrl.CommonController;
import com.jeequan.jeepay.service.impl.MchWxmpUserService;
import com.jeequan.jeepay.service.impl.SysConfigService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

/**
* 接收微信服务器消息
*
* @author zx
* @site https://www.jeepay.vip
* @date 2021/10/15 9:37
*/
@Controller
@RequestMapping("/api/wxmpCallback/msg")
public class WxmpServerController extends CommonController {

    @Autowired private SysConfigService sysConfigService;
    @Autowired private MchWxmpUserService mchWxmpUserService;
    @Autowired private IWxMpTemplateMsgService wxMpMessageService;

    /** 微信授权回调回的页面（保存商户接收消息用户）*/
    @RequestMapping("/wxAuthRedirect/{mchNo}/{sysUserId}")
    public String wxAuthRedirect(@PathVariable("mchNo") String mchNo, @PathVariable("sysUserId") Long sysUserId){

        try {

            String code = getValStringRequired("code");

            DBWxMpConfig wxMpConfig = sysConfigService.getDBWxMpConfig();
            if (wxMpConfig == null) {
                throw new BizException("未正确配置微信公众号消息配置项");
            }

            WxUserInfo wxUserInfo = wxMpMessageService.code2WxUserInfo(code, wxMpConfig);

            // 初始化数据
            mchWxmpUserService.saveOrUpdateRecord(mchNo, sysUserId, wxMpConfig.getWxAppId(), wxUserInfo.getOpenid(), wxUserInfo.getNickname());

            request.setAttribute("wxmpQrUrl", wxMpConfig.getWxmpUrl());

        }catch (BizException e) {
            request.setAttribute("errMsg", e.getMessage());
            logger.error("wxAuthRedirect系统异常：", e);
        }catch (Exception e) {
            request.setAttribute("errMsg", StringUtils.defaultIfBlank(e.getMessage(), "系统异常"));
            logger.error("wxAuthRedirect系统异常：", e);
        }

        return "mchauth/index";
    }


}
