package com.ruoyi.platform.service.impl;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.web.domain.GenericsAjaxResult;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.platform.domain.*;
import com.ruoyi.platform.mapper.*;
import com.ruoyi.platform.service.ImageVersionService;
import com.ruoyi.system.api.constant.Constant;
import com.ruoyi.system.api.model.LoginUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

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

/**
 * (ImageVersion)表服务实现类
 *
 * @author Xidaray
 * @since 2024-03-05 15:00:02
 */
@Service("imageVersionService")
public class ImageVersionServiceImpl implements ImageVersionService {
    @Resource
    private ImageVersionDao imageVersionDao;
    @Resource
    private AssetWorkflowDao assetWorkflowDao;
    @Resource
    private RayDao rayDao;
    @Resource
    private ActiveLearnDao activeLearnDao;
    @Resource
    private DevEnvironmentDao devEnvironmentDao;
    @Resource
    private ServiceDao serviceDao;
    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public ImageVersion queryById(Integer id) {
        return this.imageVersionDao.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param imageVersion 筛选条件
     * @param pageRequest  分页对象
     * @return 查询结果
     */
    @Override
    public Page<ImageVersion> queryByPage(ImageVersion imageVersion, PageRequest pageRequest) {
        long total = this.imageVersionDao.count(imageVersion);
        return new PageImpl<>(this.imageVersionDao.queryAllByLimit(imageVersion, pageRequest), pageRequest, total);
    }

    @Override
    public List<ImageVersion> queryByImageId(Integer imageId) {
        return imageVersionDao.queryByImageId(imageId);
    }

    @Override
    public GenericsAjaxResult<String> removeById(Integer id) throws Exception {
        ImageVersion imageVersion = this.imageVersionDao.queryById(id);
        ImageVersion query = new ImageVersion();
        query.setImageId(imageVersion.getImageId());
        long count = this.imageVersionDao.count(query);
        if (count == 1) {
            return GenericsAjaxResult.error("当前镜像只有一个版本，不能删除该版本");
        }

        if (imageVersion == null) {
            return GenericsAjaxResult.error("该版本下模型文件信息不存在");
        }

        List<AssetWorkflow> assetWorkflow = assetWorkflowDao.getAssetWorkflow(Long.valueOf(imageVersion.getImageId()), Constant.Asset_Type_Image, imageVersion.getTagName());
        if (assetWorkflow != null && !assetWorkflow.isEmpty()) {
            String workflows = String.join(",", assetWorkflow.stream().map(AssetWorkflow::getWorkflowName).collect(Collectors.toSet()));
            return GenericsAjaxResult.error("该镜像版本被流水线：" + workflows + "使用，不能删除，请先删除流水线");
        }

        HashMap<String, String> map = new HashMap<>();
        map.put("version", String.valueOf(id));
        List<Ray> rayList = rayDao.queryByImageId(JSON.toJSONString(map));
        if (rayList != null && !rayList.isEmpty()) {
            String rays = String.join(",", rayList.stream().map(Ray::getName).collect(Collectors.toSet()));
            return GenericsAjaxResult.error("该镜像版本被超参数自动寻优：" + rays + "使用，不能删除，请先删除超参数自动寻优");
        }

        List<ActiveLearn> activeLearnList = activeLearnDao.queryByImageId(JSON.toJSONString(map));
        if (activeLearnList != null && !activeLearnList.isEmpty()) {
            String activeLearns = String.join(",", activeLearnList.stream().map(ActiveLearn::getName).collect(Collectors.toSet()));
            return GenericsAjaxResult.error("该镜像版本被主动学习：" + activeLearns + "使用，不能删除，请先删除主动学习");
        }

        List<DevEnvironment> devEnvironmentList = devEnvironmentDao.queryByImageId(JSON.toJSONString(map));
        if (devEnvironmentList != null && !devEnvironmentList.isEmpty()) {
            String devEnvironments = String.join(",", devEnvironmentList.stream().map(DevEnvironment::getName).collect(Collectors.toSet()));
            throw new Exception("该镜像版本被开发环境：" + devEnvironments + "使用，不能删除，请先删除开发环境");
        }

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

        //判断权限，只有admin和创建者本身可以删除该数据集
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String username = loginUser.getUsername();
        String createdBy = imageVersion.getCreateBy();
        if (!(StringUtils.equals(username, "admin") || StringUtils.equals(username, createdBy))) {
            return GenericsAjaxResult.error("无权限删除该版本下模型信息");
        }

        imageVersion.setState(Constant.State_invalid);
        return this.imageVersionDao.update(imageVersion) > 0 ? GenericsAjaxResult.success("删除成功") : GenericsAjaxResult.error("删除失败");

    }

    /**
     * 新增数据
     *
     * @param imageVersion 实例对象
     * @return 实例对象
     */
    @Override
    public ImageVersion insert(ImageVersion imageVersion) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        imageVersion.setCreateBy(loginUser.getUsername());
        imageVersion.setUpdateBy(loginUser.getUsername());
        imageVersion.setUpdateTime(new Date());
        imageVersion.setCreateTime(new Date());
        imageVersion.setState(1);
        this.imageVersionDao.insert(imageVersion);
        return imageVersion;
    }

    /**
     * 修改数据
     *
     * @param imageVersion 实例对象
     * @return 实例对象
     */
    @Override
    public ImageVersion update(ImageVersion imageVersion) {
        int currentState = imageVersion.getState();
        if (currentState == 0) {
            throw new RuntimeException("镜像版本已被删除，无法更新");
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        imageVersion.setUpdateBy(loginUser.getUsername());
        imageVersion.setUpdateTime(new Date());
        this.imageVersionDao.update(imageVersion);
        return this.queryById(imageVersion.getId());

    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.imageVersionDao.deleteById(id) > 0;
    }
}
