package com.ruoyi.platform.service.impl;

import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.platform.domain.*;
import com.ruoyi.platform.mapper.*;
import com.ruoyi.platform.service.*;
import com.ruoyi.platform.utils.JacksonUtil;
import com.ruoyi.platform.utils.JsonUtils;
import com.ruoyi.platform.utils.NewHttpUtils;
import com.ruoyi.platform.vo.ModelsVo;
import com.ruoyi.platform.vo.NewDatasetVo;
import com.ruoyi.system.api.constant.Constant;
import com.ruoyi.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("WorkspaceService")
public class WorkspaceServiceImpl implements WorkspaceService {

    @Resource
    private WorkflowDao workflowDao;
    @Resource
    private ExperimentDao experimentDao;
    @Resource
    private ExperimentInsDao experimentInsDao;
    @Resource
    private ExperimentInsService experimentInsService;
    @Resource
    private ImageDao imageDao;
    @Resource
    private ComponentDao componentDao;
    @Resource
    private GitService gitService;
    @Resource
    private NewDatasetService newDatasetService;
    @Resource
    private ModelsService modelsService;
    @Resource
    private NewHttpUtils httpUtils;

    @Value("${git.endpoint}")
    String gitendpoint;
    @Value("${spring.redis.host}")
    private String redisHost;
    @Value("${spring.redis.port}")
    private Integer redisPort;

    @Override
    public Map<String, Object> getOverview() {
        Map<String, Object> resMap = new HashMap<String, Object>();

        // 获取流水线数量
        Long workflowCount = workflowDao.workflowCount();
        resMap.put("workflowCount", workflowCount);

        // 获取运行中实验实例数量
        List<ExperimentIns> experimentInsList = experimentInsService.queryByExperimentIsNotTerminated();
        if (experimentInsList != null && !experimentInsList.isEmpty()) {
            Integer experimentInsCount = experimentInsList.size();
            resMap.put("runningExperimentInsCount", experimentInsCount);
        } else {
            resMap.put("runningExperimentInsCount", 0);
        }
        //得到最近的三条实例记录,放进返回map
        List<ExperimentIns> latestExperimentInsList = experimentInsDao.getLatestInsList();
        if (latestExperimentInsList != null && !latestExperimentInsList.isEmpty()) {
            for (ExperimentIns experimentIns : latestExperimentInsList) {
                Integer experimentId = experimentIns.getExperimentId();
                Experiment experiment = this.experimentDao.queryById(experimentId);
                //拿到对应的流水线id
                Long correspondingWorkflowId = experiment.getWorkflowId();
                experimentIns.setWorkflowId(correspondingWorkflowId);
            }
            resMap.put("latestExperimentInsList", latestExperimentInsList);
        }
        Map<String, Long> statusMap = experimentInsService.countByStatus();
        resMap.put("experimentInsStatus", statusMap);
        return resMap;
    }

    @Override
    public Map<String, Integer> getAssetCount(Boolean isPublic) throws Exception {
        Map<String, Integer> assetCountMap = new HashMap<>();
        String token = gitService.checkoutToken();
        int availableRange = isPublic ? Constant.Image_Type_Pub : Constant.Image_Type_Pri;
        String datasetUrl;
        String modelUrl;
        if (isPublic) {
            // 数据集
            datasetUrl = gitendpoint + "/api/projects.json?sort_direction=updated_on&sort_by=desc&category_id=" + Constant.Git_Category_Id;
            // 模型
            modelUrl = gitendpoint + "/api/projects.json?sort_direction=updated_on&sort_by=desc&category_id=" + Constant.Git_Category_Id;
        } else {
            Jedis jedis = new Jedis(redisHost, redisPort);
            LoginUser loginUser = SecurityUtils.getLoginUser();
            String ci4sUsername = loginUser.getUsername();
            String userReq = jedis.get(ci4sUsername + "_gitUserInfo");
            Map<String, Object> userInfo = JsonUtils.jsonToMap(userReq);

            datasetUrl = gitendpoint + "/api/users/" + userInfo.get("login") + "/projects.json?category=manage";
            modelUrl = gitendpoint + "/api/users/" + userInfo.get("login") + "/projects.json?category=manage";
        }

        String req = httpUtils.sendGetWithToken(datasetUrl, null, token);
        Map<String, Object> stringObjectMap = JacksonUtil.parseJSONStr2Map(req);
        List<Map<String, Object>> projects = (List<Map<String, Object>>) stringObjectMap.get("projects");
        List<NewDatasetVo> collect1 = newDatasetService.convert(projects, Constant.Topic_Dataset, null, null);
        assetCountMap.put("dataset", collect1.size());

        req = httpUtils.sendGetWithToken(modelUrl, null, token);
        stringObjectMap = JacksonUtil.parseJSONStr2Map(req);
        projects = (List<Map<String, Object>>) stringObjectMap.get("projects");
        List<ModelsVo> collect2 = modelsService.convert(projects, Constant.Topic_model, null, null);
        assetCountMap.put("model", collect2.size());

        // 镜像
        Image image = new Image();
        if (isPublic) {
            image.setImageType(Constant.Image_Type_Pub);
         }else {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            image.setCreateBy(loginUser.getUsername());
            image.setImageType(Constant.Image_Type_Pri);
        }
        Integer imageCount = (int) this.imageDao.count(image);
        assetCountMap.put("image", imageCount);
        //统计组件数量
        Component component = new Component();
        component.setAvailableRange(availableRange);
        Integer componentCount = (int) this.componentDao.count(component);
        assetCountMap.put("component", componentCount);
        //统计流水线数量
        Workflow workflow = new Workflow();
        Integer workflowCount = (int) this.workflowDao.count(workflow);
        assetCountMap.put("workflow", workflowCount);

        return assetCountMap;
    }
}
