package com.iformall.service.msg.impl;

import com.iformall.common.ErrorCode;
import com.iformall.domain.po.*;
import com.iformall.domain.po.msg.BaseMsg;
import com.iformall.domain.po.msg.MpAppMsg;
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 SendMpMsgServiceImpl 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{
        MpAppMsg mpAppMsg = (MpAppMsg)baseMsg;
        WxTemplateMsg msg = null;

        WxMpService wxMpService = openService.getWxOpenComponentService().getWxMpServiceByAppid(mpAppMsg.getAppId());

        // 查询信息模板
        WxTemplateMsg msgQ = new WxTemplateMsg();
        msgQ.setTenantId(mpAppMsg.getTenantId());
        msgQ.setType(mpAppMsg.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);
        }

        WxMpTemplateMessage.MiniProgram miniprogram = new WxMpTemplateMessage.MiniProgram();
        miniprogram.setAppid(mpAppMsg.getMiniAppId());
        miniprogram.setPagePath(mpAppMsg.getMiniPagePath());

        WxMpTemplateMessage mpTemplateMessage = WxMpTemplateMessage.builder()
                .toUser(mpAppMsg.getTo())
                .templateId(msg.getTemplateId())
                .miniProgram(miniprogram)
                .data(mpAppMsg.getTemplateDataList())
                .build();
        String retStr = wxMpService.getTemplateMsgService().sendTemplateMsg(mpTemplateMessage);
        logger.info(retStr);
    }
}
