package com.iformall.service.msg.impl;

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.BaseMsg;
import com.iformall.domain.po.msg.MpAppMsg;
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.WxMpTemplateData;
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;

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

/**
 * 发送微信公众号模板消息
 * @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(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<WxMpTemplateData> dataTempList = new ArrayList<>();
        List<String> dataList = mpAppMsg.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));
            WxMpTemplateData templateData = new WxMpTemplateData(key, value);
            dataTempList.add(templateData);
        }

        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(dataTempList)
                .build();
        String retStr = wxMpService.getTemplateMsgService().sendTemplateMsg(mpTemplateMessage);
        logger.info(retStr);
    }
}
