package com.iformall.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaTemplateMessage;
import com.iformall.common.ErrorCode;
import com.iformall.domain.po.*;
import com.iformall.exception.MallinkException;
import com.iformall.mapper.WxTemplateMsgMapper;
import com.iformall.service.MsgSendService;
import com.iformall.service.WxAppinfoService;
import com.iformall.utils.MaUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

/**
 * 发送微信小程序消息
 * @author luozukai
 * @date 2019/3/7 16:03
 */
@Service
public class SendSmartAppMsgServiceImpl implements MsgSendService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private WxTemplateMsgMapper wxTemplateMsgMapper;
    @Autowired
    private WxAppinfoService wxAppinfoService;

    @Override
    public void send(BaseMsg baseMsg) throws Exception{
        SmartAppMsg smartAppMsg = (SmartAppMsg)baseMsg;
        WxTemplateMsg msg = null;
        WxMaTemplateMessage templateMessage;

        WxAppinfo appInfo = wxAppinfoService.getByAppId(smartAppMsg.getAppId());
        WxMaService wxMaService = MaUtil.getWeappService(appInfo);

        //查询信息模板
        WxTemplateMsg msgQ = new WxTemplateMsg();
        msgQ.setTenantId(smartAppMsg.getTenantId());
        msgQ.setType(smartAppMsg.getTemplateType());
        List<WxTemplateMsg> list = wxTemplateMsgMapper.select(msgQ);
        if (list.size() > 0) {
            msg = list.get(0);
        }
        if (msg == null) {
            logger.error("找不到模板Id");
            throw new MallinkException(ErrorCode.TEMPLATE_NOT_FOUND);
        }
        /**
         * 核销失败
         * 商品名称 {{keyword1.DATA}}
         * 核销时间 {{keyword2.DATA}}
         * 失败原因 {{keyword3.DATA}}
         * 备注    {{keyword4.DATA}}
         */
        templateMessage = WxMaTemplateMessage.builder()
                .toUser(smartAppMsg.getTo())
                .formId(smartAppMsg.getFrom())  // 微信支付的formId是prepayId
                .page(smartAppMsg.getGotopage())
                .data(smartAppMsg.getTemplateDataList())
                .templateId(msg.getTemplateId())
                .emphasisKeyword(smartAppMsg.getEmphasisKeyword())
                .build();
        wxMaService.getMsgService().sendTemplateMsg(templateMessage);
    }
}
