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.FeiShuURLConfig;

import com.qy.worksheetsystem.service.FeishuAuthorizeService;
import com.qy.worksheetsystem.service.PersonService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import java.util.Map;

/**飞书
 * description: FeishuAuthorizeServiceImpl <br>
 * date: 2024/11/18 18:07 <br>
 * author: lhbj <br>
 * version: 1.0 <br>
 */
@Slf4j
@Service
public class FeishuAuthorizeServiceImpl implements FeishuAuthorizeService {
    @Resource
    PersonService personService;
    /**
     * 报工小程序
     */
    @Value("${feishu.AppID}")
    private String AppID;
    /**
     * 报工小程序
     */
    @Value("${feishu.AppSecret}")
    private String AppSecret;


    /**
     * 构造网页授权链接
     *
     * @param redirect_uri
     * @param state
     * @return
     */
    public String authorize(String redirect_uri, String state) {
        try {
            redirect_uri = URLEncoder.encode(redirect_uri, "UTF-8");
            StringBuilder url = new StringBuilder(FeiShuURLConfig.authorize_URL);
            url.append("&redirect_uri=" + redirect_uri);
            url.append("&client_id=" + AppID);
            url.append("&state=" + state);
            return url.toString();
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage() + "redirect_uri编码异常：" + redirect_uri);
        }
        return "";
    }
    /**
     * 获取access_token
     * 成功
     * @return {
     *     "code": 0,
     *     "access_token": "eyJhbGciOiJFUzI1NiIs**********X6wrZHYKDxJkWwhdkrYg",
     *     "expires_in": 7200, // 非固定值，请务必根据响应体中返回的实际值来确定 access_token 的有效期
     *     "refresh_token": "eyJhbGciOiJFUzI1NiIs**********XXOYOZz1mfgIYHwM8ZJA",
     *     "refresh_token_expires_in": 604800, // 非固定值，请务必根据响应体中返回的实际值来确定 refresh_token 的有效期
     *     "scope": "auth:user.id:read offline_access task:task:read user_profile",
     *     "token_type": "Bearer"
     * }
     * 失败
     * {
     *     "code": 20050,
     *     "error": "server_error",
     *     "error_description": "An unexpected server error occurred. Please retry your request."
     * }
     */
    public String getUserAccessToken(String redirect_uri,String code)  {
        Map<String,String> param = Maps.newHashMap();
        param.put("grant_type","authorization_code");
        param.put("client_id",AppID);
        param.put("client_secret", AppSecret);
        param.put("code",code);
        param.put("redirect_uri",redirect_uri);
        HttpResponse res = HttpUtil.createPost(FeiShuURLConfig.getUser_access_token_URL)
                .header("Content-Type","application/json; charset=utf-8")
                .body(JSONUtil.toJsonStr(param)).execute();
        if (res.isOk()){
            JSONObject object = JSONUtil.parseObj(res.body());
            String access_token = object.getStr("access_token");
            return access_token;
        }else {
            log.error(this.getClass().toString()+".getUserAccessToken:"+res.body());
        }
        return "";
    }

    public Map<String,String> getUserInfo(String redirect_uri,String code)  {
        String access_token = this.getUserAccessToken(redirect_uri,code);
        Map<String, String> userMap = this.getUserInfo(access_token);
        String feishuid = userMap.get("user_id");
        Map<String, String> personMap = personService.getPersonByFeiShuId(feishuid);
        personMap.putAll(userMap);
        return personMap;
    }

    public Map<String, String> getUserInfo(String access_token) {
        Map<String, String> map = Maps.newHashMap();
        try {
            String Authorization = "Bearer " + access_token;
            HttpResponse res = HttpUtil.createGet(FeiShuURLConfig.getUser_info_URL)
                    .header("Authorization", Authorization).execute();
            if (res.isOk()) {
                JSONObject object = JSONUtil.parseObj(res.body());
                Integer code = object.getInt("code");
                if (!(code > 0)) {
                    JSONObject data = object.getJSONObject("data");
                    map.put("name", data.getStr("name"));
                    map.put("en_name", data.getStr("en_name"));
                    map.put("avatar_url", data.getStr("avatar_url"));
                    map.put("avatar_thumb", data.getStr("avatar_thumb"));
                    map.put("avatar_middle", data.getStr("avatar_middle"));
                    map.put("avatar_big", data.getStr("avatar_big"));
                    map.put("open_id", data.getStr("open_id"));
                    map.put("union_id", data.getStr("union_id"));
                    map.put("email", data.getStr("email"));
                    map.put("enterprise_email", data.getStr("enterprise_email"));
                    map.put("user_id", data.getStr("user_id"));
                    map.put("mobile", data.getStr("mobile"));
                    map.put("tenant_key", data.getStr("tenant_key"));
                    map.put("employee_no", data.getStr("employee_no"));
                }
            } else {
                log.error(this.getClass().toString() + ".getUserAccessToken:" + res.body());
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return map;
    }
}
