package com.fengqi.wechat.controller.base;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fengqi.wechat.remote.ManageClient;
import com.fengqi.wechat.remote.WechatClient;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public abstract class AbstractMenuController {

    @Autowired
    protected ManageClient manageClient;
    @Autowired
    protected WechatClient wechatClient;
    @Autowired
    protected StringRedisTemplate stringRedisTemplate;

    private final String menuUrl="https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";


    protected abstract String getAccessTokenRedisKey();

    protected abstract String getAppId();

    protected abstract String getSecret();

    protected abstract Integer getType();


    @PostMapping("/wechat_menu")
    public Object setMenu() throws Exception {
        String access_token = getToken();
        String url = menuUrl.replace("ACCESS_TOKEN",access_token);

        JSONObject json = JSONUtil.parseObj(manageClient.getMenuList(getType())
                .replace("children","sub_button")
                .replace("data","button")
                .replace("sname","name")
                .replace("skey","key"));

        //发送请求 更改菜单栏 请求
        return doPostStr(url,JSONUtil.toJsonStr(json));
    }

    //获取永久素材
    @PostMapping(value = "/getMaterial")
    public Map<String,Object> getMaterial(){
        String access_token = getToken();
        return wechatClient.getMaterial(access_token);
    }




    protected String getToken() {
        String token = stringRedisTemplate.opsForValue().get(getAccessTokenRedisKey());
        if(StrUtil.isBlank(token)) {
            System.out.println(getAppId());
            System.out.println(getSecret());
            Map<String, Object> client_credential = wechatClient.getToken("client_credential", getAppId(), getSecret());
            System.out.println(client_credential);
            String access_token = client_credential.get("access_token").toString();
            System.out.println(access_token);
            stringRedisTemplate.opsForValue().set(getAccessTokenRedisKey(),access_token,110, TimeUnit.MINUTES);
            return access_token;
        }else{
            return token;
        }
    }

    protected static JSONObject doPostStr(String url, String outStr) throws IOException {
        HttpClient client = HttpClientBuilder.create().build();//获取DefaultHttpClient请求
        HttpPost httpPost = new HttpPost(url);//HttpPost将使用Get方式发送请求URL
        JSONObject jsonObject = null;
        httpPost.setEntity(new StringEntity(outStr,"UTF-8"));//使用setEntity方法，将我们传进来的参数放入请求中
        HttpResponse response = client.execute(httpPost);//使用HttpResponse接收client执行httpost的结果
        String result = EntityUtils.toString(response.getEntity(),"UTF-8");//HttpEntity转为字符串类型
        jsonObject = JSONUtil.parseObj(result);//字符串类型转为JSON类型
        return jsonObject;
    }
}
