package com.ruoyi.platform.service.impl;

import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.platform.domain.DevEnvironment;
import com.ruoyi.platform.domain.PodStatus;
import com.ruoyi.platform.mapper.DevEnvironmentDao;
import com.ruoyi.platform.service.DevEnvironmentService;
import com.ruoyi.platform.service.JupyterService;
import com.ruoyi.platform.service.ResourceOccupyService;
import com.ruoyi.platform.utils.JacksonUtil;
import com.ruoyi.platform.vo.DevEnvironmentVo;
import com.ruoyi.platform.vo.PodStatusVo;
import com.ruoyi.system.api.constant.Constant;
import com.ruoyi.system.api.model.LoginUser;
import org.apache.commons.lang3.StringUtils;
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 org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * (DevEnvironment)表服务实现类
 *
 * @author Xidaray
 * @since 2024-06-03 15:17:37
 */
@Service("devEnvironmentService")
public class DevEnvironmentServiceImpl implements DevEnvironmentService {
    @Resource
    private DevEnvironmentDao devEnvironmentDao;

    @Resource
    @Lazy
    private JupyterService jupyterService;
    @Resource
    private ResourceOccupyService resourceOccupyService;

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

    /**
     * 分页查询
     *
     * @param devEnvironment 筛选条件
     * @param pageRequest    分页对象
     * @return 查询结果
     */
    @Override
    public Page<DevEnvironment> queryByPage(DevEnvironment devEnvironment, PageRequest pageRequest) {
        long total = this.devEnvironmentDao.count(devEnvironment);
        List<DevEnvironment> devEnvironmentList = this.devEnvironmentDao.queryAllByLimit(devEnvironment, pageRequest);

        //查询每个开发环境的pod状态,注意：只有pod为非终止态时才去调状态接口
        devEnvironmentList.forEach(devEnv -> {
            try {
                if (!devEnv.getStatus().equals(PodStatus.Terminated.getName()) &&
                        !devEnv.getStatus().equals(PodStatus.Failed.getName())) {
                    PodStatusVo podStatusVo = this.jupyterService.getJupyterStatus(devEnv);
                    if (!devEnv.getStatus().equals(podStatusVo.getStatus())) {
                        devEnv.setStatus(podStatusVo.getStatus());
                        devEnv.setUrl(podStatusVo.getUrl());
                        this.devEnvironmentDao.update(devEnv);
                    } else {
                        devEnv.setUrl(podStatusVo.getUrl());
                    }
                }
            } catch (Exception e) {
                devEnv.setStatus(PodStatus.Unknown.getName());
            }
        });

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

    /**
     * 新增数据
     *
     * @param devEnvironmentVo 实例对象
     * @return 实例对象
     */
    @Override
    public DevEnvironment insert(DevEnvironmentVo devEnvironmentVo) throws Exception {
        DevEnvironment devByName = devEnvironmentDao.getByName(devEnvironmentVo.getName());
        if (devByName != null) {
            throw new RuntimeException("开发环境名称已存在");
        }
        //插入预备，此时不需要判断版本重复
        DevEnvironment devEnvironment = new DevEnvironment();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        devEnvironment.setName(devEnvironmentVo.getName());
        //状态先设为未知
        devEnvironment.setStatus(Constant.Unknown);
        devEnvironment.setComputingResource(devEnvironmentVo.getComputingResource());
        devEnvironment.setComputingResourceId(devEnvironmentVo.getComputingResourceId());
        devEnvironment.setStandard(devEnvironmentVo.getStandard());
        devEnvironment.setEnvVariable(devEnvironmentVo.getEnvVariable());
        devEnvironment.setImage(JacksonUtil.toJSONString(devEnvironmentVo.getImage()));
        if (devEnvironmentVo.getDataset() != null) {
            devEnvironment.setDataset(JacksonUtil.toJSONString(devEnvironmentVo.getDataset()));
        }
        if (devEnvironmentVo.getModel() != null) {
            devEnvironment.setModel(JacksonUtil.toJSONString(devEnvironmentVo.getModel()));
        }
        devEnvironment.setCreateBy(loginUser.getUsername());
        devEnvironment.setUpdateBy(loginUser.getUsername());
        devEnvironment.setUpdateTime(new Date());
        devEnvironment.setCreateTime(new Date());
        devEnvironment.setState(Constant.State_valid);
        this.devEnvironmentDao.insert(devEnvironment);
        return devEnvironment;
    }

    /**
     * 修改数据
     *
     * @param devEnvironment 实例对象
     * @return 实例对象
     */
    @Override
    public DevEnvironment update(DevEnvironment devEnvironment) throws Exception {
        DevEnvironment devByName = devEnvironmentDao.getByName(devEnvironment.getName());
        if (devByName != null && !devByName.getId().equals(devEnvironment.getId())) {
            throw new RuntimeException("开发环境名称已存在");
        }
        devEnvironment.setUpdateBy(devEnvironment.getCreateBy());
        devEnvironment.setUpdateTime(new Date());
        this.devEnvironmentDao.update(devEnvironment);
        return this.queryById(devEnvironment.getId());
    }

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

    @Override
    @Transactional
    public String removeById(Integer id) throws Exception {
        DevEnvironment devEnvironment = this.devEnvironmentDao.queryById(id);
        if (devEnvironment == null) {
            throw new RuntimeException("开发环境信息不存在");
        }

        //判断权限，只有admin和创建者本身可以删除该数据集
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String username = loginUser.getUsername();
        String createdBy = devEnvironment.getCreateBy();
        if (!(StringUtils.equals(username, "admin") || StringUtils.equals(username, createdBy))) {
            throw new RuntimeException("无权限删除该开发环境");
        }

        jupyterService.stopJupyterService(id);
        devEnvironment.setState(Constant.State_invalid);
        resourceOccupyService.deleteTaskState(Constant.TaskType_Dev, Long.valueOf(id), null);
        return this.devEnvironmentDao.update(devEnvironment) > 0 ? "删除成功" : "删除失败";
    }
}
