package com.iformall.service.msg.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaUniformMessage;
import com.iformall.common.ErrorCode;
import com.iformall.domain.po.msg.AppUniformMsg;
import com.iformall.domain.po.msg.BaseMsg;
import com.iformall.domain.po.msg.MpAppMsg;
import com.iformall.domain.po.WxTemplateMsg;
import com.iformall.exception.MallinkException;
import com.iformall.mapper.WxTemplateMsgMapper;
import com.iformall.service.msg.MsgSendService;
import com.iformall.service.wechat.FmOpenService;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 发送微信小程序-统一消息
 * @author Stormeye
 * @date 2019/4/9 13:51
 */
@Service
public class SendWeappUniformMsgServiceImpl implements MsgSendService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private WxTemplateMsgMapper wxTemplateMsgMapper;

    @Autowired
    private FmOpenService openService;

    @Override
    public void send(BaseMsg baseMsg) throws Exception{
        AppUniformMsg appUniformMsg = (AppUniformMsg)baseMsg;
        WxTemplateMsg msg = null;

        WxMaService wxMaService = openService.getWxOpenComponentService().getWxMaServiceByAppid(appUniformMsg.getAppId());

        // 查询信息模板
        WxTemplateMsg msgQ = new WxTemplateMsg();
        msgQ.setTenantId(appUniformMsg.getTenantId());
        msgQ.setType(appUniformMsg.getTemplateType());
        try {
            msg = wxTemplateMsgMapper.selectOne(msgQ);
        } catch (Exception e) {
            logger.error("公众号消息模板错误: " + e.getMessage());
        }
        if (msg == null) {
            logger.error("找不到模板Id");
            throw new MallinkException(ErrorCode.TEMPLATE_NOT_FOUND);
        }

        WxMaUniformMessage.MiniProgram miniprogram = new WxMaUniformMessage.MiniProgram();
        miniprogram.setAppid(appUniformMsg.getAppId());
        miniprogram.setPagePath(appUniformMsg.getPagePath());

        WxMaUniformMessage uniformMessage = WxMaUniformMessage.builder()
                .isMpTemplateMsg(true)
                .toUser(appUniformMsg.getTo())
                .appid(appUniformMsg.getMpAppId())
                .templateId(msg.getTemplateId())
                .url(appUniformMsg.getUrl())
                .miniProgram(miniprogram)
                .formId(appUniformMsg.getFormId())
                .data(appUniformMsg.getTemplateDataList())
                .build();
        wxMaService.getMsgService().sendUniformMsg(uniformMessage);
    }
}
