package com.ruoyi.platform.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.platform.service.GitService;
import com.ruoyi.platform.utils.HttpUtils;
import com.ruoyi.platform.utils.JsonUtils;
import com.ruoyi.platform.vo.GitProjectVo;
import com.ruoyi.system.api.model.LoginUser;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.util.HashMap;
import java.util.Map;

@Service
public class GitServiceImpl implements GitService {

    @Value("${spring.redis.host}")
    private String redisHost;

    private static final Logger log = LoggerFactory.getLogger(GitServiceImpl.class);

    @Override
    public String login(String username, String password) {
        // 构建请求参数
        Map<String, Object> params = new HashMap<>();
        params.put("grant_type", "password");
        params.put("username", username);
        params.put("password", password);
        params.put("client_id", "jEdGwrIJixCUIJM9vj2MwA6zmoTVhUdXxiSAaaCiXwA");
        params.put("client_secret", "L3wBKTNnRo-wPen7bxR3F1myCvtVDgpWa6MnpfyWeJE");
        try {
            // 发送POST请求
            String req = HttpUtils.sendPostRequest("https://www.gitlink.org.cn/oauth/token",null, JsonUtils.mapToJson(params));
            // 解析响应JSON
            if (StringUtils.isEmpty(req)) {
                throw new RuntimeException("终止响应内容为空。");
            }
            // 将响应的JSON字符串转换为Map对象
            Map<String, Object> runResMap = JsonUtils.jsonToMap(req);
            // 提取access_token
            // 提取access_token
            String accessToken = (String) runResMap.get("access_token");

            //通过access_token获取用户信息
            String userReq = HttpUtils.sendGetWithToken("https://www.gitlink.org.cn/api/users/get_user_info.json",null, accessToken);
            if (StringUtils.isEmpty(userReq)) {
                throw new RuntimeException("终止响应内容为空。");
            }
            LoginUser loginUser = SecurityUtils.getLoginUser();
            String ci4sUsername = loginUser.getUsername();
            // 将access_token存入Redis
            Jedis jedis = new Jedis(redisHost);
            jedis.set(ci4sUsername+"_gitToken", accessToken);
            jedis.set(ci4sUsername+"_gitUserInfo", userReq);
            return accessToken;
        } catch (Exception e) {
            log.error("登录GitLink失败。", e);
            return null;
        }
    }

    @Override
    public Map createProject(String token, GitProjectVo gitProjectVo) throws Exception {
        String userReq = HttpUtils.sendPostWithToken("https://www.gitlink.org.cn/api/projects.json",JsonUtils.objectToJson(gitProjectVo),token);
        return JsonUtils.jsonToMap(userReq);
    }

    @Override
    public void createBranch(String token,String owner, String projectName, String branchName, String oldBranchName) throws Exception {
        //https://www.gitlink.org.cn/api/v1/fanshuai/testdssa8755/branches.json
//        {
//            "new_branch_name": "SsS",
//                "old_branch_name": "master"
//        }
        String createBranchUrl = "https://www.gitlink.org.cn/api/v1/"+ owner + "/" + projectName + "/branches.json";
        Map<String, Object> resMap = new HashMap<>();
        resMap.put("new_branch_name", branchName);
        resMap.put("old_branch_name", oldBranchName);
        String req = HttpUtils.sendPostWithToken(createBranchUrl,JsonUtils.objectToJson(resMap),token);
        System.out.println(req);
    }

    @Override
    public void createTopic(String token, Integer id, String topicName) throws Exception {
        // https://www.gitlink.org.cn/api/v1/project_topics.json
        Map<String, Object> resMap = new HashMap<>();
        resMap.put("project_id", id);
        resMap.put("name", topicName);
        String req = HttpUtils.sendPostWithToken("https://www.gitlink.org.cn/api/v1/project_topics.json",JsonUtils.objectToJson(resMap),token);
        System.out.println(req);
    }
}
