package com.purui.prims.headless.server.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.purui.prims.common.util.BeanMapper;
import com.purui.prims.common.util.ContextUtils;
import com.purui.prims.headless.api.pojo.response.MetricResp;
import com.purui.prims.headless.server.persistence.dataobject.MetricVersionDO;
import com.purui.prims.headless.server.persistence.mapper.MetricVersionDOMapper;
import com.purui.prims.headless.server.pojo.MetricVersion;
import com.purui.prims.headless.server.service.MetricService;
import com.purui.prims.headless.server.service.MetricVersionService;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 指标版本服务实现类
 *
 * @author charlie
 * @since 2024-07-22
 */
@Service
public class MetricVersionServiceImpl extends ServiceImpl<MetricVersionDOMapper, MetricVersionDO> implements MetricVersionService {

    @Override
    public List<MetricVersion> queryMetricVersion(Long metricId) {
        List<MetricVersionDO> metricVersionDOList = queryVersion(metricId);
        if (metricVersionDOList != null && !metricVersionDOList.isEmpty()) {
            return metricVersionDOList.stream().map(this::convert).collect(Collectors.toList());
        }
        return null;
    }

    @Override
    public MetricVersion getLastVersion(Long metricId) {
        List<MetricVersionDO> metricVersionDOList = queryVersion(metricId);
        if (metricVersionDOList != null && !metricVersionDOList.isEmpty()) {
            MetricVersionDO metricVersionDO = metricVersionDOList.stream().findFirst().get();
            return convert(metricVersionDO);
        }
        return null;
    }

    private List<MetricVersionDO> queryVersion(Long metricId) {
        QueryWrapper<MetricVersionDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(MetricVersionDO::getMetricId, metricId);
        queryWrapper.lambda().orderByDesc(MetricVersionDO::getId);
        return this.list(queryWrapper);
    }

    @Override
    public boolean createNewVersion(Long metricId) {
        MetricVersionDO metricVersion = queryVersion(metricId).stream().findFirst().orElse(null);
        String currentVersion = "1.0.0";
        if (metricVersion != null) {
            currentVersion = metricVersion.getVersionNo();
            // 更新旧版本状态为已发布
            metricVersion.setStatus(true);
            this.updateById(metricVersion);
        }
        // 创建新版本
        currentVersion = generateNextVersion(currentVersion);
        return createNewVersion(metricId, currentVersion);
    }

    @Override
    public boolean createNewVersion(Long metricId, String versionNo) {
        MetricService metricService = ContextUtils.getBean(MetricService.class);
        if (metricService == null) {
            return false;
        }
        MetricResp metricResp = metricService.getMetric(metricId);
        MetricVersionDO metricVersionDO = new MetricVersionDO();
        metricVersionDO.setMetricId(metricId);
        metricVersionDO.setStatus(false);
        metricVersionDO.setDefaultConfig(JSON.toJSONString(metricResp));
        metricVersionDO.setVersionNo(versionNo);
        metricVersionDO.setVersion(Integer.parseInt(versionNo.replace(".", "")));
        if (this.save(metricVersionDO)) {
            return true;
        }
        return false;
    }

    // 恢复上一个版本（需要提醒当前版本数据将丢失）
    @Override
    public boolean restorePreviousVersion(Long metricId) {
        List<MetricVersionDO> versionList = queryVersion(metricId);
        if (versionList.size() > 0) {
            // 删除现有版本，并修改上一个版本状态为未发布
            removeById(versionList.get(0).getId());
            if (versionList.size() > 1) {
                MetricVersionDO metricVersionDO = versionList.get(1);
                metricVersionDO.setStatus(false);
                return this.updateById(metricVersionDO);
            }
        }
        return false;
    }

    // 更新版本数据（每次保存时自动调用，或手动保存）
    @Override
    public boolean updateVersionData(Long metricId) {
        MetricVersionDO metricVersionDO = queryVersion(metricId).stream().findFirst().orElse(null);
        if (metricVersionDO != null) {
            MetricService metricService = ContextUtils.getBean(MetricService.class);
            if (metricService == null) {
                return false;
            }
            MetricResp metricResp = metricService.getMetric(metricId);
            metricVersionDO.setDefaultConfig(JSON.toJSONString(metricResp));
            return this.updateById(metricVersionDO);
        }
        return false;
    }

    // 生成新版本号
    private String generateNextVersion(String currentMaxVersion) {
        // 解析当前最大版本号
        String[] parts = currentMaxVersion.split("\\.");
        int[] versionParts = new int[parts.length];
        for (int i = 0; i < parts.length; i++) {
            versionParts[i] = Integer.parseInt(parts[i]);
        }

        // 递增版本号并处理进位
        int index = versionParts.length - 1;
        versionParts[index]++;

        while (index > 0 && versionParts[index] >= 10) {
            versionParts[index] = 0;
            index--;
            versionParts[index]++;
        }

        // 构建新的版本号
        return String.join(".", Arrays.stream(versionParts).mapToObj(String::valueOf).toArray(String[]::new));
    }

    private MetricVersion convert(MetricVersionDO metricVersionDO) {
        MetricVersion metricVersion = new MetricVersion();
        BeanMapper.mapper(metricVersionDO, metricVersion);
        return metricVersion;
    }
}
