package org.dromara.member.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.member.domain.AppVersion;
import org.dromara.member.domain.bo.AppVersionBo;
import org.dromara.member.domain.vo.AppVersionVo;
import org.dromara.member.exception.VersionException;
import org.dromara.member.mapper.AppVersionMapper;
import org.dromara.member.service.AppVersionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;

/**
 * App版本信息Service业务层处理
 *
 * @author pengles
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class AppVersionServiceImpl extends ServiceImpl<AppVersionMapper, AppVersion> implements AppVersionService {

    private final AppVersionMapper baseMapper;

    /**
     * 查询App版本信息
     */
    @Override
    public AppVersionVo queryById(Long versionId) {
        return baseMapper.selectVoById(versionId);
    }

    /**
     * 查询App版本信息列表
     */
    @Override
    public TableDataInfo<AppVersionVo> queryPageList(AppVersionBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<AppVersion> lqw = buildQueryWrapper(bo);
        Page<AppVersionVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询App版本信息列表
     */
    @Override
    public List<AppVersionVo> queryList(AppVersionBo bo) {
        LambdaQueryWrapper<AppVersion> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<AppVersion> buildQueryWrapper(AppVersionBo bo) {
        LambdaQueryWrapper<AppVersion> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getVersionCode() != null, AppVersion::getVersionCode, bo.getVersionCode());
        lqw.like(StringUtils.isNotBlank(bo.getVersionName()), AppVersion::getVersionName, bo.getVersionName());
        lqw.eq(StringUtils.isNotBlank(bo.getPlatform()), AppVersion::getPlatform, bo.getPlatform());
        lqw.eq(StringUtils.isNotBlank(bo.getIsForce()), AppVersion::getIsForce, bo.getIsForce());
        lqw.orderByDesc(AppVersion::getVersionCode);
        return lqw;
    }

    /**
     * 新增App版本信息
     */
    @Override
    public Boolean insertByBo(AppVersionBo bo) {
        AppVersion add = BeanUtil.toBean(bo, AppVersion.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setVersionId(add.getVersionId());
        }
        return flag;
    }

    /**
     * 修改App版本信息
     */
    @Override
    public Boolean updateByBo(AppVersionBo bo) {
        AppVersion update = BeanUtil.toBean(bo, AppVersion.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(AppVersion entity) {
        // 校验版本号唯一性
        if (entity.getVersionCode() != null && StringUtils.isNotBlank(entity.getPlatform())) {
            LambdaQueryWrapper<AppVersion> lqw = Wrappers.lambdaQuery();
            lqw.eq(AppVersion::getVersionCode, entity.getVersionCode());
            lqw.eq(AppVersion::getPlatform, entity.getPlatform());
            if (entity.getVersionId() != null) {
                lqw.ne(AppVersion::getVersionId, entity.getVersionId());
            }

            long count = baseMapper.selectCount(lqw);
            if (count > 0) {
                throw new RuntimeException("该平台下版本号已存在");
            }
        }
    }

    /**
     * 批量删除App版本信息
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 检查版本更新
     */
    @Override
    public AppVersionVo checkUpdate(String platform, Integer currentVersionCode) {
        if (StringUtils.isBlank(platform)) {
            throw VersionException.unsupportedPlatform(platform);
        }
        if (currentVersionCode == null || currentVersionCode <= 0) {
            throw VersionException.invalidVersionCode(currentVersionCode);
        }

        LambdaQueryWrapper<AppVersion> lqw = Wrappers.lambdaQuery();
        lqw.eq(AppVersion::getPlatform, platform);
        lqw.gt(AppVersion::getVersionCode, currentVersionCode);
        lqw.orderByDesc(AppVersion::getVersionCode);
        lqw.last("LIMIT 1");

        return baseMapper.selectVoOne(lqw);
    }

    /**
     * 获取指定平台的最新版本
     */
    @Override
    public AppVersionVo getLatestVersion(String platform) {
        if (StringUtils.isBlank(platform)) {
            throw VersionException.unsupportedPlatform(platform);
        }

        LambdaQueryWrapper<AppVersion> lqw = Wrappers.lambdaQuery();
        lqw.eq(AppVersion::getPlatform, platform);
        lqw.orderByDesc(AppVersion::getVersionCode);
        lqw.last("LIMIT 1");

        AppVersionVo result = baseMapper.selectVoOne(lqw);
        if (result == null) {
            throw VersionException.versionNotFound("平台 " + platform + " 暂无可用版本");
        }

        return result;
    }

    /**
     * 检查版本号是否唯一
     */
    @Override
    public Boolean checkVersionCodeUnique(AppVersionBo bo) {
        if (bo.getVersionCode() == null || bo.getVersionCode() <= 0) {
            throw VersionException.invalidVersionCode(bo.getVersionCode());
        }
        if (StringUtils.isBlank(bo.getPlatform())) {
            throw VersionException.unsupportedPlatform(bo.getPlatform());
        }

        LambdaQueryWrapper<AppVersion> lqw = Wrappers.lambdaQuery();
        lqw.eq(AppVersion::getVersionCode, bo.getVersionCode());
        lqw.eq(AppVersion::getPlatform, bo.getPlatform());
        if (bo.getVersionId() != null) {
            lqw.ne(AppVersion::getVersionId, bo.getVersionId());
        }

        boolean isUnique = baseMapper.selectCount(lqw) == 0;
        if (!isUnique) {
            throw VersionException.versionCodeDuplicate(bo.getVersionCode());
        }
        return true;
    }

    /**
     * 获取版本历史列表
     */
    @Override
    public List<AppVersionVo> getVersionHistory(String platform, Integer limit) {
        if (StringUtils.isBlank(platform)) {
            return List.of();
        }

        if (limit == null || limit <= 0) {
            limit = 10; // 默认返回10个版本
        }

        LambdaQueryWrapper<AppVersion> lqw = Wrappers.lambdaQuery();
        lqw.eq(AppVersion::getPlatform, platform);
        lqw.orderByDesc(AppVersion::getVersionCode);
        lqw.last("LIMIT " + limit);

        return baseMapper.selectVoList(lqw);
    }

    /**
     * 检查是否需要强制更新
     */
    @Override
    public Boolean checkForceUpdate(String platform, Integer currentVersionCode) {
        if (StringUtils.isBlank(platform)) {
            throw VersionException.unsupportedPlatform(platform);
        }
        if (currentVersionCode == null || currentVersionCode <= 0) {
            throw VersionException.invalidVersionCode(currentVersionCode);
        }

        LambdaQueryWrapper<AppVersion> lqw = Wrappers.lambdaQuery();
        lqw.eq(AppVersion::getPlatform, platform);
        lqw.gt(AppVersion::getVersionCode, currentVersionCode);
        lqw.eq(AppVersion::getIsForce, "1");

        return baseMapper.selectCount(lqw) > 0;
    }

    /**
     * 获取版本更新信息
     */
    @Override
    public AppVersionVo getUpdateInfo(String platform, Integer currentVersionCode) {
        AppVersionVo latestVersion = checkUpdate(platform, currentVersionCode);
        if (latestVersion == null) {
            return null;
        }

        // 检查是否有强制更新版本
        Boolean forceUpdate = checkForceUpdate(platform, currentVersionCode);
        if (forceUpdate) {
            // 如果有强制更新，返回最新的强制更新版本
            LambdaQueryWrapper<AppVersion> lqw = Wrappers.lambdaQuery();
            lqw.eq(AppVersion::getPlatform, platform);
            lqw.gt(AppVersion::getVersionCode, currentVersionCode);
            lqw.eq(AppVersion::getIsForce, "1");
            lqw.orderByDesc(AppVersion::getVersionCode);
            lqw.last("LIMIT 1");

            AppVersionVo forceVersion = baseMapper.selectVoOne(lqw);
            return forceVersion != null ? forceVersion : latestVersion;
        }

        return latestVersion;
    }

    /**
     * 批量发布版本
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean batchPublish(List<Long> versionIds) {
        if (ObjectUtil.isEmpty(versionIds)) {
            return false;
        }

        // 这里可以添加发布逻辑，比如更新状态等
        log.info("批量发布版本: {}", versionIds);
        return true;
    }

    /**
     * 撤回版本
     */
    @Override
    public Boolean withdrawVersion(Long versionId) {
        if (versionId == null) {
            return false;
        }

        // 这里可以添加撤回逻辑，比如更新状态等
        log.info("撤回版本: {}", versionId);
        return true;
    }

}