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.WxMaTemplateMessage;
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.WxAppinfo;
import com.iformall.domain.po.WxTemplateMsg;
import com.iformall.domain.po.msg.BaseMsg;
import com.iformall.domain.po.msg.SmartAppMsg;
import com.iformall.mapper.WxTemplateMsgMapper;
import com.iformall.service.WxAppinfoService;
import com.iformall.service.msg.MsgSendService;
import com.iformall.service.wechat.FmOpenService;
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.ArrayList;
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 boolean isFmOpen;
    @Autowired
    private WxTemplateMsgMapper wxTemplateMsgMapper;
    @Autowired
    private WxAppinfoService wxAppinfoService;

    @Autowired
    private FmOpenService openService;

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

        WxMaService wxMaService = null;
        if(isFmOpen) {
            wxMaService = openService.getWxOpenComponentService().getWxMaServiceByAppid(smartAppMsg.getAppId());
        } else {
            WxAppinfo appInfo = wxAppinfoService.getByAppId(smartAppMsg.getAppId());
            wxMaService = MaUtil.getWeappService(appInfo);
        }

        //查询信息模板
        WxTemplateMsg msgQ = new WxTemplateMsg();
        msgQ.setTenantId(smartAppMsg.getTenantId());
        msgQ.setType(smartAppMsg.getTemplateType());
        List<WxTemplateMsg> list = wxTemplateMsgMapper.selectList(new QueryWrapper(msgQ));
        if (list.size() > 0) {
            msg = list.get(0);
        }
        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");
        String emphasis = customParam.getString("emphasis");

        // build template data list
        List<WxMaTemplateData> dataTempList = new ArrayList<>();
        List<String> dataList = smartAppMsg.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);
        }
        templateMessage = WxMaTemplateMessage.builder()
                .toUser(smartAppMsg.getTo())
                .formId(smartAppMsg.getFormId())  // 微信支付的formId是prepayId
                .page(smartAppMsg.getGotopage())
                .data(dataTempList)
                .templateId(msg.getTemplateId())
                .emphasisKeyword(emphasis)
                .build();
        wxMaService.getMsgService().sendTemplateMsg(templateMessage);
    }
}
