package com.huiju.estateagents.common;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import com.huiju.estateagents.entity.TaMiniapp;
import com.huiju.estateagents.service.IMiniAppService;
import com.huiju.estateagents.third.entity.TaMpInfo;
import com.huiju.estateagents.third.service.ITaMpInfoService;
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.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class WxUtils {
    // 小程序
    private ConcurrentHashMap<String, WxMaService> serives = new ConcurrentHashMap();

    // 公众号
    private WxMpService mpServices = new WxMpServiceImpl();

    @Autowired
    IMiniAppService iMiniAppService;

    @Autowired
    ITaMpInfoService iTaMpInfoService;

    public WxMaService getMiniApp(String appid) {
        return serives.get(appid);
    }

    public WxMpService getMpService() { return mpServices; }
    public WxMpService getMpService(Integer orgId) {
        TaMpInfo mpInfo = iTaMpInfoService.getByOrgId(orgId);
        return mpServices.switchoverTo(mpInfo.getAppid());
    }

    @PostConstruct
    public void init() {

        // 初始化小程序
        List<TaMiniapp> taMiniappList = iMiniAppService.getAllAvaliableMiniapps();
        if (null == taMiniappList) {
            return;
        }

        for (TaMiniapp taMiniapp : taMiniappList) {
            WxMaService service = newService(taMiniapp);
            serives.put(taMiniapp.getMiniappId(), service);
        }

        // 初始化公众号
        try {
            List<TaMpInfo> mpInfoList = iTaMpInfoService.getAllAvaliable();
            if (null != mpInfoList && mpInfoList.size() > 0) {
                Map<String, WxMpConfigStorage> configStorages = new HashMap<>();
                for (TaMpInfo mpInfo: mpInfoList) {
                    WxMpDefaultConfigImpl wxMpDefaultConfig = new WxMpDefaultConfigImpl();
                    wxMpDefaultConfig.setAppId(mpInfo.getAppid());
                    wxMpDefaultConfig.setSecret(mpInfo.getSecret());
                    wxMpDefaultConfig.setToken(mpInfo.getToken());
                    wxMpDefaultConfig.setAesKey(mpInfo.getAesKey());
                    configStorages.put(mpInfo.getAppid(), wxMpDefaultConfig);
                }
                mpServices.setMultiConfigStorages(configStorages);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    public WxMaService newService(TaMiniapp taMiniapp, boolean ...changeServices) {
        WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
        config.setAppid(taMiniapp.getMiniappId());
        config.setSecret(taMiniapp.getSecret());
        config.setToken(taMiniapp.getToken());
        config.setAesKey(taMiniapp.getAesKey());
        config.setMsgDataFormat("JSON");

        WxMaService service = new WxMaServiceImpl();
        service.setWxMaConfig(config);

        if (changeServices.length > 0 && changeServices[0]) {
            serives.remove(taMiniapp.getMiniappId());
            serives.put(taMiniapp.getMiniappId(), service);
        }

        return service;
    }

    public static String sendTemplateMessage(WxMpService mpService, String toUser, String templateId, String url, List<WxMpTemplateData> datas) throws WxErrorException {
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .toUser(toUser)
                .templateId(templateId)
                .url(url)
                .build();

        for (WxMpTemplateData data: datas) {
            templateMessage.addData(data);
        }

        // return msgId
        return mpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
    }
}
