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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

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

    @Autowired
    IMiniAppService iMiniAppService;

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

    @PostConstruct
    public void init() {
        System.out.println("-------------PostConstruct----------------");

        List<TaMiniapp> taMiniappList = iMiniAppService.getAllAvaliableMiniapps();
        if (null == taMiniappList) {
            return;
        }

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

    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;
    }
}
