package com.ruoyi.platform.service.impl;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.platform.domain.ActiveLearn;
import com.ruoyi.platform.mapper.*;
import com.ruoyi.system.api.constant.Constant;
import com.ruoyi.platform.domain.AssetWorkflow;
import com.ruoyi.platform.domain.CodeConfig;
import com.ruoyi.platform.service.CodeConfigService;
import com.ruoyi.system.api.model.LoginUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import com.ruoyi.platform.domain.Ray;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service("codeConfigService")
public class CodeConfigServiceImpl implements CodeConfigService {

    @Resource
    private CodeConfigDao codeConfigDao;
    @Resource
    private AssetWorkflowDao assetWorkflowDao;
    @Resource
    private RayDao rayDao;
    @Resource
    private ActiveLearnDao activeLearnDao;
    @Resource
    private ServiceDao serviceDao;

    @Override
    public Page<CodeConfig> queryByPage(CodeConfig codeConfig, PageRequest pageRequest) {
        long total = this.codeConfigDao.count(codeConfig);
        List<CodeConfig> codeConfigList = this.codeConfigDao.queryAllByLimit(codeConfig, pageRequest);

        return new PageImpl<>(codeConfigList, pageRequest, total);
    }

    @Override
    public CodeConfig queryById(Long id) throws Exception {
        CodeConfig codeConfig = this.codeConfigDao.queryById(id);
        if (codeConfig == null) {
            throw new Exception("未查询到代码配置");
        } else {
            return this.codeConfigDao.queryById(id);
        }
    }

    @Override
    public CodeConfig insert(CodeConfig codeConfig) {
        Long id = this.codeConfigDao.queryByCodeRepoName(codeConfig.getCodeRepoName());
        if (id != null) {
            throw new IllegalStateException("代码仓库名称已存在");
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        codeConfig.setCreateBy(loginUser.getUsername());
        codeConfig.setUpdateBy(loginUser.getUsername());
        codeConfig.setCreateTime(new Date());
        codeConfig.setUpdateTime(new Date());
        this.codeConfigDao.insert(codeConfig);
        return codeConfig;
    }

    @Override
    public CodeConfig update(CodeConfig codeConfig) {
        Long id = this.codeConfigDao.queryByCodeRepoName(codeConfig.getCodeRepoName());
        if (id != null && !id.equals(codeConfig.getId())) {
            throw new IllegalStateException("代码仓库名称已存在");
        }

        LoginUser loginUser = SecurityUtils.getLoginUser();
        codeConfig.setUpdateBy(loginUser.getUsername());

        if (codeConfig.getIsPublic()) {
            codeConfig.setVerifyMode(null);
            codeConfig.setGitUserName(null);
            codeConfig.setGitPassword(null);
            codeConfig.setSshKey(null);
        }
        this.codeConfigDao.update(codeConfig);
        return this.codeConfigDao.queryById(codeConfig.getId());
    }

    @Override
    public String removeById(Long id) throws Exception {
        CodeConfig codeConfig = this.codeConfigDao.queryById(id);
        if (codeConfig == null) {
            return "代码配置不存在";
        }

        List<AssetWorkflow> assetWorkflow = assetWorkflowDao.getAssetWorkflow(id, Constant.Asset_Type_Code, null);
        if (assetWorkflow != null && !assetWorkflow.isEmpty()) {
            String workflows = String.join(",", assetWorkflow.stream().map(AssetWorkflow::getWorkflowName).collect(Collectors.toSet()));
            throw new Exception("该代码配置被流水线：" + workflows + "使用，不能删除，请先删除流水线");
        }

        HashMap<String, String> map = new HashMap<>();
        map.put("id", String.valueOf(codeConfig.getId()));
        List<Ray> rayList = rayDao.queryByCodeConfig(JSON.toJSONString(map));
        if (rayList != null && !rayList.isEmpty()) {
            String rays = String.join(",", rayList.stream().map(Ray::getName).collect(Collectors.toSet()));
            throw new Exception("该代码配置被超参数自动寻优：" + rays + "使用，不能删除，请先删除超参数自动寻优");
        }

        List<ActiveLearn> activeLearnList = activeLearnDao.queryByCodeConfig(JSON.toJSONString(map));
        if (activeLearnList != null && !activeLearnList.isEmpty()) {
            String activeLearns = String.join(",", activeLearnList.stream().map(ActiveLearn::getName).collect(Collectors.toSet()));
            throw new Exception("该代码配置被主动学习：" + activeLearns + "使用，不能删除，请先删除主动学习");
        }

        List<String> serviceVersionList = serviceDao.queryByCodeConfig(JSON.toJSONString(map));
        if (serviceVersionList != null && !serviceVersionList.isEmpty()) {
            String serviceVersions = String.join(",", serviceVersionList.stream().collect(Collectors.toSet()));
            throw new Exception("该代码配置被服务版本：" + serviceVersions + "使用，不能删除，请先删除服务版本");
        }

        LoginUser loginUser = SecurityUtils.getLoginUser();
        String username = loginUser.getUsername();
        String createBy = codeConfig.getCreateBy();
        if (!(StringUtils.equals(username, "admin") || StringUtils.equals(username, createBy))) {
            throw new Exception("无权限删除该代码配置");
        }
        codeConfig.setState(Constant.State_invalid);
        return this.codeConfigDao.update(codeConfig) > 0 ? "删除成功" : "删除失败";
    }
}
