package com.iformall.service.msg.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaTemplateData;
import cn.binarywang.wx.miniapp.bean.WxMaUniformMessage;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.iformall.domain.po.WxTemplateMsg;
import com.iformall.domain.po.msg.AppUniformMsg;
import com.iformall.domain.po.msg.BaseMsg;
import com.iformall.mapper.WxTemplateMsgMapper;
import com.iformall.service.msg.MsgSendService;
import com.iformall.service.wechat.FmOpenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 发送微信小程序-统一消息
 * @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(new QueryWrapper(msgQ));
        } catch (Exception e) {
            logger.error("公众号消息模板错误: " + e.getMessage());
        }
        if (msg == null) {
            logger.error("找不到模板Id");
            //throw new MallinkException(ErrorCode.TEMPLATE_NOT_FOUND);
            return;
        }
        JSONObject customParam = JSON.parseObject(msg.getCustomParam());
        String url = customParam.getString("url");

        // build template data list
        List<WxMaTemplateData> dataTempList = new ArrayList<>();
        List<String> dataList = appUniformMsg.getDataList();
        JSONArray indexArr = customParam.getJSONArray("index");
        for(int i=0;i<indexArr.size();i++) {
            String key = indexArr.getString(i);
            String value = customParam.getString(key);
            value = value.replace("{"+key+"}", dataList.get(i));
            WxMaTemplateData templateData = new WxMaTemplateData(key, value);
            dataTempList.add(templateData);
        }

        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(url)
                .miniProgram(miniprogram)
                .formId(appUniformMsg.getFormId())
                .data(dataTempList)
                .build();
        wxMaService.getMsgService().sendUniformMsg(uniformMessage);
    }
}
