package com.ruoyi.platform.service.impl;

import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.platform.annotations.CheckDuplicate;
import com.ruoyi.platform.domain.Dataset;
import com.ruoyi.platform.domain.ModelDependency;
import com.ruoyi.platform.domain.Models;
import com.ruoyi.platform.domain.ModelsVersion;
import com.ruoyi.platform.mapper.ModelsDao;
import com.ruoyi.platform.mapper.ModelsVersionDao;
import com.ruoyi.platform.service.ModelDependencyService;
import com.ruoyi.platform.service.ModelsVersionService;
import com.ruoyi.system.api.model.LoginUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
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.io.IOException;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (ModelsVersion)表服务实现类
 *
 * @author Xidaray
 * @since 2024-01-05 09:02:42
 */
@Service("modelsVersionService")
public class ModelsVersionServiceImpl implements ModelsVersionService {
    @Resource
    private ModelsVersionDao modelsVersionDao;

    @Resource
    private ModelsDao modelsDao;
    @Resource
    @Lazy
    private ModelDependencyService modelDependencyService;


    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public ModelsVersion queryById(Integer id) {
        return this.modelsVersionDao.queryById(id);
    }

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

    /**
     * 新增数据
     *
     * @param modelsVersion 实例对象
     * @return 实例对象
     */
    @Override
    public ModelsVersion insert(ModelsVersion modelsVersion) throws Exception {
        //插入预备，此时不需要判断版本重复
        LoginUser loginUser = SecurityUtils.getLoginUser();
        modelsVersion.setCreateBy(loginUser.getUsername());
        modelsVersion.setUpdateBy(loginUser.getUsername());
        modelsVersion.setUpdateTime(new Date());
        modelsVersion.setCreateTime(new Date());
        modelsVersion.setState(1);
        this.modelsVersionDao.insert(modelsVersion);
        insertModelsDependency(modelsVersion);
        return modelsVersion;
    }

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




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

    @Override
    public String removeById(Integer id) {
        ModelsVersion modelsVersion = this.modelsVersionDao.queryById(id);
        if (modelsVersion == null){
            return "该版本下模型文件信息不存在";
        }

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

        modelsVersion.setState(0);
        return this.modelsVersionDao.update(modelsVersion)>0?"删除成功":"删除失败";
    }
    
    @Override
    public List<ModelsVersion> queryByModelsId(Integer modelsId){
        return modelsVersionDao.queryByModelsId(modelsId);
    }


    /**
     * 复制模型版本
     *
     * @param oldModelsVersion 待更新的模型版本
     * @return 新的模型版本记录
     */
    public ModelsVersion duplicateModelsVersion(ModelsVersion oldModelsVersion) throws Exception {
        ModelsVersion newModelsVersion = new ModelsVersion();
        newModelsVersion.setModelsId(oldModelsVersion.getModelsId());
        newModelsVersion.setVersion(oldModelsVersion.getVersion());
        newModelsVersion.setStatus(oldModelsVersion.getStatus());
        return this.insert(newModelsVersion);
    }

    public ModelsVersion queryByModelsVersion(ModelsVersion modelsVersion){

        return this.modelsVersionDao.queryByModelsVersion(modelsVersion);
    }



    /**
     * 根据版本id和version查询
     *
     * @param modelsId 模型的id
     * @param version 模型版本号
     * @return 新的模型版本记录列表
     */
    @Override
    public Map<String,Object> queryByModelsIdAndVersion(Integer modelsId, String version) {
        Map<String,Object> response = new HashMap<>();

        List<ModelsVersion> modelsVersionList = this.modelsVersionDao.queryAllByModelsVersion(modelsId, version);
        modelsVersionList.stream()
                .filter(modelsVersion -> modelsVersion.getUrl() != null && !modelsVersion.getUrl().isEmpty())
                .findFirst()
                .ifPresent(modelsVersion -> {
                    String path = modelsVersion.getUrl();
                    response.put("path", path);
                });

        response.put("content", modelsVersionList);
        return response;

    }

    @Override
    public Map<Integer, String> deleteModelsVersion(Integer modelsId, String version) throws Exception {
        Map<Integer, String> results = new HashMap<Integer,String>();
        // 根据模型ID和版本查询所有模型版本
        List<ModelsVersion> versions = this.modelsVersionDao.queryAllByModelsVersion(modelsId, version);
        //逻辑删除列表中的数据项
        for(ModelsVersion modelsVersion:versions){
            String result = this.removeById(modelsVersion.getId());
            results.put(modelsVersion.getId(), result);
        }
        // 删除依赖关系
        ModelDependency modelDependency = new ModelDependency();
        modelDependency.setCurrentModelId(modelsId);
        modelDependency.setVersion(version);
        modelDependency.setState(1);
        List<ModelDependency> modelDependencyList = modelDependencyService.queryByModelDependency(modelDependency);
        if (modelDependencyList.size()>0){
            ModelDependency modelDependency1 = modelDependencyList.get(0);
            modelDependencyService.removeById(modelDependency1.getId());
        }
        return results;
    }

    @Override
    public String addModelVersions(List<ModelsVersion> modelsVersions) throws Exception {
        try {
            // 遍历传入的 modelsVersions 列表
            for(ModelsVersion modelsVersion : modelsVersions) {
                insertPrepare(modelsVersion);
            }
            this.modelsVersionDao.insertBatch(modelsVersions);
            insertModelsDependency(modelsVersions.get(0));
            return "新增模型版本成功";
        } catch (Exception e) {
            // 如果出现异常，返回异常消息
            throw new Exception("新增模型版本失败: " + e.getMessage()) ;
        }
    }

    @Override
    public void checkDeclaredVersion(ModelsVersion insert) throws Exception {
        ModelsVersion modelsVersion = modelsVersionDao.queryByModelsVersion(insert);
        if (modelsVersion != null) {
            Field[] fields = ModelsVersion.class.getDeclaredFields();
            for (Field field : fields) {
                if (field.isAnnotationPresent(CheckDuplicate.class)) {
                    CheckDuplicate annotation = field.getAnnotation(CheckDuplicate.class);
                    throw new Exception(field.getName() + annotation.message());
                }
            }
        }
    }

    private void insertPrepare(ModelsVersion modelsVersion) throws Exception {
        checkDeclaredVersion(modelsVersion);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        modelsVersion.setCreateBy(loginUser.getUsername());
        modelsVersion.setUpdateBy(loginUser.getUsername());
        modelsVersion.setUpdateTime(new Date());
        modelsVersion.setCreateTime(new Date());
        modelsVersion.setState(1);
        //插入时需要更新对应的模型更新时间
        Integer modelsId = modelsVersion.getModelsId();
        Models models = this.modelsDao.queryById(modelsId);
        models.setUpdateTime(new Date());
        this.modelsDao.update(models);

    }

    //新增模型依赖关系
    private void insertModelsDependency(ModelsVersion modelsVersion) throws Exception {
        ModelDependency modelDependency = new ModelDependency();
        modelDependency.setCurrentModelId(modelsVersion.getModelsId());
        modelDependency.setVersion(modelsVersion.getVersion());
        modelDependency.setState(2);
        List<ModelDependency> modelDependencyList = modelDependencyService.queryByModelDependency(modelDependency);
        if (modelDependencyList != null && modelDependencyList.size()>0){
            //查到2，说明是之前流水线推送的，你就直接该状态生效就完了
            ModelDependency modelDependency1 = modelDependencyList.get(0);
            modelDependency1.setState(1);
            modelDependencyService.update(modelDependency1);

        }else {
            modelDependency.setState(1);
            modelDependencyService.insert(modelDependency);
        }
    }

}
