package com.emoon.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.emoon.common.core.constant.CacheNames;
import com.emoon.common.core.exception.exception.ServiceException;
import com.emoon.common.core.utils.MapstructUtils;
import com.emoon.common.core.utils.ObjectUtils;
import com.emoon.common.core.utils.StringUtils;
import com.emoon.common.json.utils.JsonUtils;
import com.emoon.common.mybatis.core.page.PageQuery;
import com.emoon.common.mybatis.core.page.TableDataInfo;
import com.emoon.common.oss.constant.OssConstant;
import com.emoon.common.redis.utils.CacheUtils;
import com.emoon.common.redis.utils.RedisUtils;
import com.emoon.system.domain.SysOssConfigDo;
import com.emoon.system.domain.bo.SysOssConfigBo;
import com.emoon.system.domain.vo.SysOssConfigVo;
import com.emoon.system.mapper.SysOssConfigMapper;
import com.emoon.system.service.ISysOssConfigService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 对象存储配置Service业务层处理
 *
 * @author wangkang
 * @author 孤舟烟雨
 * @date 2021-08-13
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class SysOssConfigServiceImpl implements ISysOssConfigService {

    private final SysOssConfigMapper baseMapper;

    /**
     * 项目启动时，初始化参数到缓存，加载配置类
     */
    @Override
    public void init() {
        List<SysOssConfigDo> list = baseMapper.selectList();
        // 加载OSS初始化配置
        for (SysOssConfigDo config : list) {
            String configKey = config.getConfigKey();
            if ("0".equals(config.getStatus())) {
                RedisUtils.setCacheObject(OssConstant.DEFAULT_CONFIG_KEY, configKey);
            }
            CacheUtils.put(CacheNames.SYS_OSS_CONFIG, config.getConfigKey(), JsonUtils.toJsonString(config));
        }
    }

    @Override
    public SysOssConfigVo queryById(Long ossConfigId) {
        return baseMapper.selectVoById(ossConfigId);
    }

    @Override
    public TableDataInfo<SysOssConfigVo> queryPageList(SysOssConfigBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysOssConfigDo> lqw = buildQueryWrapper(bo);
        Page<SysOssConfigVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }


    private LambdaQueryWrapper<SysOssConfigDo> buildQueryWrapper(SysOssConfigBo bo) {
        LambdaQueryWrapper<SysOssConfigDo> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getConfigKey()), SysOssConfigDo::getConfigKey, bo.getConfigKey());
        lqw.like(StringUtils.isNotBlank(bo.getBucketName()), SysOssConfigDo::getBucketName, bo.getBucketName());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), SysOssConfigDo::getStatus, bo.getStatus());
        lqw.orderByAsc(SysOssConfigDo::getOssConfigId);
        return lqw;
    }

    @Override
    public Boolean insertByBo(SysOssConfigBo bo) {
        SysOssConfigDo config = MapstructUtils.convert(bo, SysOssConfigDo.class);
        validEntityBeforeSave(config);
        boolean flag = baseMapper.insert(config) > 0;
        if (flag) {
            // 从数据库查询完整的数据做缓存
            config = baseMapper.selectById(config.getOssConfigId());
            CacheUtils.put(CacheNames.SYS_OSS_CONFIG, config.getConfigKey(), JsonUtils.toJsonString(config));
        }
        return flag;
    }

    @Override
    public Boolean updateByBo(SysOssConfigBo bo) {
        SysOssConfigDo config = MapstructUtils.convert(bo, SysOssConfigDo.class);
        validEntityBeforeSave(config);
        LambdaUpdateWrapper<SysOssConfigDo> luw = new LambdaUpdateWrapper<>();
        luw.set(ObjectUtil.isNull(config.getPrefix()), SysOssConfigDo::getPrefix, "");
        luw.set(ObjectUtil.isNull(config.getRegion()), SysOssConfigDo::getRegion, "");
        luw.set(ObjectUtil.isNull(config.getExt1()), SysOssConfigDo::getExt1, "");
        luw.set(ObjectUtil.isNull(config.getRemark()), SysOssConfigDo::getRemark, "");
        luw.eq(SysOssConfigDo::getOssConfigId, config.getOssConfigId());
        boolean flag = baseMapper.update(config, luw) > 0;
        if (flag) {
            // 从数据库查询完整的数据做缓存
            config = baseMapper.selectById(config.getOssConfigId());
            CacheUtils.put(CacheNames.SYS_OSS_CONFIG, config.getConfigKey(), JsonUtils.toJsonString(config));
        }
        return flag;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysOssConfigDo entity) {
        if (StringUtils.isNotEmpty(entity.getConfigKey())
            && !checkConfigKeyUnique(entity)) {
            throw new ServiceException("操作配置'" + entity.getConfigKey() + "'失败, 配置key已存在!");
        }
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            if (CollUtil.containsAny(ids, OssConstant.SYSTEM_DATA_IDS)) {
                throw new ServiceException("系统内置, 不可删除!");
            }
        }
        List<SysOssConfigDo> list = CollUtil.newArrayList();
        for (Long configId : ids) {
            SysOssConfigDo config = baseMapper.selectById(configId);
            list.add(config);
        }
        boolean flag = baseMapper.deleteByIds(ids) > 0;
        if (flag) {
            list.forEach(sysOssConfigDo ->
                CacheUtils.evict(CacheNames.SYS_OSS_CONFIG, sysOssConfigDo.getConfigKey()));
        }
        return flag;
    }

    /**
     * 判断configKey是否唯一
     */
    private boolean checkConfigKeyUnique(SysOssConfigDo sysOssConfigDo) {
        long ossConfigId = ObjectUtils.notNull(sysOssConfigDo.getOssConfigId(), -1L);
        SysOssConfigDo info = baseMapper.selectOne(new LambdaQueryWrapper<SysOssConfigDo>()
            .select(SysOssConfigDo::getOssConfigId, SysOssConfigDo::getConfigKey)
            .eq(SysOssConfigDo::getConfigKey, sysOssConfigDo.getConfigKey()));
        if (ObjectUtil.isNotNull(info) && info.getOssConfigId() != ossConfigId) {
            return false;
        }
        return true;
    }

    /**
     * 启用禁用状态
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateOssConfigStatus(SysOssConfigBo bo) {
        SysOssConfigDo sysOssConfigDo = MapstructUtils.convert(bo, SysOssConfigDo.class);
        int row = baseMapper.update(null, new LambdaUpdateWrapper<SysOssConfigDo>()
            .set(SysOssConfigDo::getStatus, "1"));
        row += baseMapper.updateById(sysOssConfigDo);
        if (row > 0) {
            RedisUtils.setCacheObject(OssConstant.DEFAULT_CONFIG_KEY, sysOssConfigDo.getConfigKey());
        }
        return row;
    }

}
