package com.liquidnet.service.sweet.service.impl;

import com.liquidnet.service.base.ResponseDto;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 公众号模版消息 服务实现类
 * </p>
 *
 * @author liquidnet
 * @since 2021-07-27
 */
@Service
public class SweetTemplateServiceImpl {

    @Value("${liquidnet.wechat.zhengzai.service.appid}")
    private String appid;
    @Value("${liquidnet.wechat.zhengzai.service.secret}")
    private String secret;

    public ResponseDto send(String openId, String templateId) {
        // 发送模板消息接口
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                // 接收者openid
                .toUser(openId)
                // 模板id
                .templateId(templateId)
                // 模板跳转链接
                .url("http://www.baidu.com")
                .build();
        // 添加模板数据
        templateMessage.addData(new WxMpTemplateData("first", "您好", "#FF00FF"))
                .addData(new WxMpTemplateData("keyword1", "这是个测试", "#A9A9A9"))
                .addData(new WxMpTemplateData("keyword2", "这又是个测试", "#FF00FF"))
                .addData(new WxMpTemplateData("remark", "这还是个测试", "#000000"));
        String msgId = null;
        try {
            // 发送模板消息
            WxMpConfigStorage wxMpConfig = wxMpConfig(appid, secret);
            WxMpService wxMpService = wxMpService(wxMpConfig);
            msgId = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        System.out.println(msgId);
        return ResponseDto.success();
    }

    public void sendMsg()
    {
        String openId = "";
        String templateId = "";
        send(openId, templateId);
    }

    private WxMpConfigStorage wxMpConfig(String appId, String appSecret) {
        WxMpDefaultConfigImpl config = new WxMpDefaultConfigImpl();
        config.setAppId(appId);
        config.setSecret(appSecret);
        return config;
    }

    private WxMpService wxMpService(WxMpConfigStorage mpConfig) {
        WxMpService service = new WxMpServiceImpl();
        service.setWxMpConfigStorage(mpConfig);
        return service;
    }
}
