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.model.MessageResult;
import com.qy.worksheetsystem.model.MessageResultV2;
import com.qy.worksheetsystem.service.PersonService;
import com.qy.worksheetsystem.service.YunzhijiaService;
import com.qy.worksheetsystem.util.HutoolCacheUtils;
import com.qy.worksheetsystem.util.JWTUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

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("accessToken");
                        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;
    }

    @Override
    public Map<String, Object> getUserInfo(String ticket) {
        return this.getUserInfo(this.getAccessToken(),ticket);
    }

    /**获取用户信息
     * @description:
     * @author: lhbj
     * @date: 2024/12/2 19:51
     * @param: null
     * @return:JSONObject
     * {
     *     "errorCode": 0,
     *     "data": {
     *         "appid": "500041933",
     *         "eid": "10603457",
     *         "username": "周小迪",
     *         "userid": "5a41af0ae4b0820e92cd9868",
     *         "jobNo":"12312",
     *         "networkid": "58df7e16e4b053f44063edca",
     *         "deviceId": "15900000000",
     *         "openid": "5a41b292e4b058cf3d0cf314",
     *         "ticket": null
     *     },
     *     "success": true,
     *     "error": null
     * }
     * 参数说明：
     *
     * 字段	类型	说明
     * appid	String	轻应用id
     * eid	String	团队id
     * username	String	用户姓名
     * userid	String	云之家用户id
     * jobNo	String	工号
     * networkid	String	工作圈id
     * deviceId	String	设备id
     * openid	String	团队用户id
     * ticket	String	云之家APP会传递ticket参数给轻应用（把ticket参数追加到轻应用对应的url中）
     *
     **/
    @Override
    public Map<String, Object> getUserInfo(String accessToken, String ticket) {
        Map<String,Object> result = Maps.newHashMap();
        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);
                        result.put("username",data.get("username"));
                        result.put("jobNo",data.get("jobNo"));
                        result.put("userid",data.get("userid"));
                        result.put("openid",data.get("openid"));
                        result.put("deviceId",data.get("deviceId"));
                        result.put("ticket",data.get("ticket"));
                        result.putAll(stringMap);
                        String token = JWTUtil.createToken((String) data.get("jobNo"), (String) data.get("userid"));
                        result.put("token", token);
                        result.put("expire", (JWTUtil.EXPIRE_TIME));
                        return result;
                    }else {

                    }
                }
                throw new SecurityException("获取用户信息失败：" + res.body());
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return Collections.emptyMap();
    }


}
