package com.ssm.manage.service.impl;

import com.ssm.manage.entity.StoreWechat;
import com.ssm.manage.query.AlarmParamsDTO;
import com.ssm.manage.service.PushMessageService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
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 org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

@Service
@Slf4j
public class PushMessageServiceImpl implements PushMessageService {

    // 开发者密码(AppSecret)
    private static String AppSecret = "9ed5097e93b5a0e909dbe2b347d068ac";
    // 开发者ID(AppID)
    private static String AppId = "wx3c108aae98b1433c";
    // 消息模板ID
    private static String TemplateId = "LGNr1hdreDtKcmgN6-950KOQ_DLl-odczwqNMMPlkpY";


    @Override
    public void pushMessage(AlarmParamsDTO alarmParamsDTO, Long id, StoreWechat storeWechat) {
        //1，配置
        WxMpInMemoryConfigStorage wxStorage = new WxMpInMemoryConfigStorage();
        if (null!=storeWechat){
            wxStorage.setAppId(storeWechat.getAppid());
            wxStorage.setSecret(storeWechat.getAppEcret());
        }else {
            wxStorage.setAppId(AppId);
            wxStorage.setSecret(AppSecret);
        }
        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(wxStorage);
        List<WxMpTemplateData> wxMpTemplateData = Arrays.asList(
                new WxMpTemplateData("first",alarmParamsDTO.getFirst(),"#000000"),
                new WxMpTemplateData("keyword1",alarmParamsDTO.getKeyword1(),"#000080"),
                new WxMpTemplateData("keyword2",alarmParamsDTO.getKeyword2(),"#0000FF"),
                new WxMpTemplateData("keyword3",alarmParamsDTO.getKeyword3(),"#FFD700"),
                new WxMpTemplateData("remark",alarmParamsDTO.getRemark(),"#00FF00")
        );
        WxMpTemplateMessage.MiniProgram miniProgram = new WxMpTemplateMessage.MiniProgram();
        miniProgram.setAppid("wx094b8c7fb88ba28d");
        miniProgram.setPagePath("pages/consumer/components/share?couponId="+id);
        miniProgram.setUsePath(false);
//        miniProgram.setPagePath("pages/consumer/components/share?couponId="+id);
        //2,推送消息
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .toUser(alarmParamsDTO.getOpenId())
                .templateId(TemplateId)
                .data(wxMpTemplateData)
//                .url("pages/consumer/components/share")
                .miniProgram(miniProgram)
                .build()
                ;
        try {
            wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
        } catch (Exception e) {
            System.out.println("推送失败：" + e.getMessage());
            e.printStackTrace();
        }
    }
}
