package com.qy.worksheetsystem.service.impl;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.google.common.collect.Maps;
import com.qy.worksheetsystem.config.YunzhijiaURLConfig;
import com.qy.worksheetsystem.service.PersonService;
import com.qy.worksheetsystem.service.YunzhijiaService;
import com.qy.worksheetsystem.util.HutoolCacheUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Map;

/**
 * @BelongsProject: workSheetSystem
 * @BelongsPackage: com.qy.worksheetsystem.service.impl
 * @Author: lhbj
 * @CreateTime: 2024-12-02  18:13
 * @Description: TODO
 * @Version: 1.0
 */
@Slf4j
@Service
public class YunzhijiaServiceImpl implements YunzhijiaService {
    @Resource
    PersonService personService;
    /**
     * 报工小程序
     */
    @Value("${yunzhijia.AppID}")
    private String AppID;
    /**
     * 报工小程序
     */
    @Value("${yunzhijia.AppSecret}")
    private String AppSecret;

    /**获取token
     * @description:
     * @author: lhbj
     * @date: 2024/12/2 19:51
     * @param: null
     * @return:String
     **/
    @Override
    public String getAccessToken() {
        String access_token="";
        try {
            String key = AppID + AppSecret;
            //从缓存中取
            access_token = (String) HutoolCacheUtils.get(key);
            if (StringUtils.isBlank(access_token)) {
                Map<String, Object> param = Maps.newHashMap();
                param.put("appId", AppID);
                param.put("secret", AppSecret);
                param.put("timestamp", System.currentTimeMillis());
                param.put("scope", "app");
                HttpResponse res = HttpUtil.createPost(YunzhijiaURLConfig.getAccessToken)
                        .header("Content-Type", "application/json; charset=utf-8")
                        .body(JSONUtil.toJsonStr(param)).execute();
                if (res.isOk()) {
                    JSONObject object = JSONUtil.parseObj(res.body());
                    Boolean success = object.getBool("success", false);
                    if (success) {
                        JSONObject data =object.getJSONObject("data");
                        access_token = data.getStr("access_token");
                        Integer expireIn = data.getInt("expireIn");
                        //缓存access_token
                        HutoolCacheUtils.put(key,access_token,expireIn);
                        return access_token;
                    }
                }
                throw new SecurityException("获取AccessToken失败：" + res.body());
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return access_token;
    }

    /**获取用户信息
     * @description:
     * @author: lhbj
     * @date: 2024/12/2 19:51
     * @param: null
     * @return:JSONObject
     **/
    @Override
    public Map<String, Object> getUserInfo(String accessToken, String ticket) {
        try {
                String url = YunzhijiaURLConfig.acquirecontext.concat("accessToken");
                Map<String, Object> param = Maps.newHashMap();
                param.put("appId", AppID);
                param.put("ticket", ticket);
                HttpResponse res = HttpUtil.createPost(url)
                        .header("Content-Type", "application/json; charset=utf-8")
                        .body(JSONUtil.toJsonStr(param)).execute();
                if (res.isOk()) {
                    JSONObject object = JSONUtil.parseObj(res.body());
                    Boolean success = object.getBool("success", false);
                    if (success) {
                        JSONObject data =object.getJSONObject("data");
                        String userid =data.getStr("userid");
                        Map<String,String> stringMap = personService.getPersonByUserId(userid);
                        data.putAll(stringMap);
                        return data;
                    }
                }
                throw new SecurityException("获取用户信息失败：" + res.body());
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return Collections.emptyMap();
    }
}
