package com.ruoyi.platform.service.impl;

import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.platform.service.GitService;
import com.ruoyi.platform.utils.JacksonUtil;
import com.ruoyi.platform.utils.JsonUtils;
import com.ruoyi.platform.utils.NewHttpUtils;
import com.ruoyi.platform.vo.GitProjectVo;
import com.ruoyi.system.api.model.LoginUser;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
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 javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.ruoyi.common.security.utils.SecurityUtils.decrypt;

@Service
public class GitServiceImpl implements GitService {

    @Value("${spring.redis.host}")
    private String redisHost;
    @Value("${spring.redis.port}")
    private Integer redisPort;
    @Value("${git.endpoint}")
    String gitendpoint;
    @Resource
    private NewHttpUtils httpUtils;
    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.sendPost(gitendpoint + "/oauth/token", null, JsonUtils.mapToJson(params));
            // 解析响应JSON
            if (StringUtils.isEmpty(req)) {
                throw new RuntimeException("gitlink用户信息出错");
            }
            // 将响应的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(gitendpoint + "/api/users/get_user_info.json", null, accessToken);
            if (StringUtils.isEmpty(userReq)) {
                throw new RuntimeException("gitlink用户信息出错");
            }
            LoginUser loginUser = SecurityUtils.getLoginUser();
            String ci4sUsername = loginUser.getUsername();
            // 将access_token存入Redis
            Jedis jedis = new Jedis(redisHost, redisPort);
            jedis.set(ci4sUsername + "_gitToken", accessToken);
            jedis.set(ci4sUsername + "_gitUserInfo", userReq);
            return accessToken;
        } catch (Exception e) {
            throw new RuntimeException("gitlink用户信息出错");
        }
    }

    public String checkoutToken() {
        Jedis jedis = new Jedis(redisHost, redisPort);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String ci4sUsername = loginUser.getUsername();
        String token = jedis.get(ci4sUsername + "_gitToken");
        String gitLinkUsername = loginUser.getSysUser().getGitLinkUsername();
        String gitLinkPassword = decrypt(loginUser.getSysUser().getGitLinkPassword());

        if (StringUtils.isEmpty(token)) {
            login(gitLinkUsername, gitLinkPassword);
            token = jedis.get(ci4sUsername + "_gitToken");
        } else {
            try {
                Map userInfo = getUserInfo(token);
                if (userInfo == null || (userInfo.get("status") != null && 401 == (Integer) userInfo.get("status"))) {
                    login(gitLinkUsername, gitLinkPassword);
                    token = jedis.get(ci4sUsername + "_gitToken");
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        }
        return token;
    }

    @Override
    public Map createProject(String token, GitProjectVo gitProjectVo) throws Exception {
        String userReq = httpUtils.sendPostWithToken(gitendpoint + "/api/projects.json", null, token, JsonUtils.objectToJson(gitProjectVo));
        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, null, token, JsonUtils.objectToJson(resMap));
        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(gitendpoint + "/api/v1/project_topics.json", null, token, JsonUtils.objectToJson(resMap));
    }

    @Override
    public List<Map<String, Object>> getBrancheList(String token, String owner, String projectName) throws Exception {
        String req = httpUtils.sendGetWithToken(gitendpoint + "/api/v1/" + owner + "/" + projectName + "/branches/all.json", null, token);
        // 解析响应JSON
        if (StringUtils.isEmpty(req)) {
            throw new RuntimeException("终止响应内容为空。");
        }
        // 将响应的JSON字符串转换为List<Map>对象
        List<Map<String, Object>> mapList = JacksonUtil.parseJSONStr2MapList(req);
        return mapList;
    }

    @Override
    public void deleteProject(String token, String owner, String projectName) throws Exception {
        httpUtils.sendDeleteWithToken(gitendpoint + "/api/" + owner + "/" + projectName + ".json", null, token);
    }

    @Override
    public void deleteBranch(String token, String owner, String projectName, String branchName, String localPath) throws Exception {
        try (Git git = Git.open(new File(localPath))) {
            git.checkout().setName("master").call();
            git.branchDelete().setBranchNames(branchName).setForce(true).call();
        } catch (IOException | GitAPIException e) {
            log.error("Exception occurred while creating local branch based on master", e);
        }
        httpUtils.sendDeleteWithToken(gitendpoint + "/api/v1/" + owner + "/" + projectName + "/branches/" + branchName + ".json", null, token);
    }

    @Override
    public Map getUserInfo(String token) throws Exception {
        String userReq = httpUtils.sendGetWithToken(gitendpoint + "/api/users/get_user_info.json", null, token);
        if (StringUtils.isEmpty(userReq)) {
            return null;
        }
        Map<String, Object> runResMap = JsonUtils.jsonToMap(userReq);
        return runResMap;
    }

    @Override
    public Map getProjectDetail(String owner, String identifier, String token) throws IOException {
        String userReq = httpUtils.sendGetWithToken(gitendpoint + "/api/" + owner + "/" + identifier + "/detail.json", null, token);
        if (StringUtils.isEmpty(userReq)) {
            return null;
        }
        Map<String, Object> runResMap = JsonUtils.jsonToMap(userReq);
        return runResMap;
    }
}
