package org.dromara.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.constant.CacheNames;
import org.dromara.common.core.constant.TenantConstants;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StreamUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.oss.constant.OssConstant;
import org.dromara.common.redis.utils.CacheUtils;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.common.tenant.core.TenantEntity;
import org.dromara.common.tenant.helper.TenantHelper;
import org.dromara.system.domain.SysOssConfig;
import org.dromara.system.domain.SysSmsConfig;
import org.dromara.system.domain.bo.SysSmsConfigBo;
import org.dromara.system.domain.vo.SysSmsConfigVo;
import org.dromara.system.mapper.SysSmsConfigMapper;
import org.dromara.system.service.ISysSmsConfigService;
import org.springframework.stereotype.Service;

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

/**
 * 病例短信配置Service业务层处理
 *
 * @author wuzhigang
 * @date 2023-12-19
 */
@RequiredArgsConstructor
@Service
public class SysSmsConfigServiceImpl implements ISysSmsConfigService {

    private final SysSmsConfigMapper baseMapper;

    /**
     * 查询病例短信配置
     */
    @Override
    public SysSmsConfigVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询病例短信配置列表
     */
    @Override
    public TableDataInfo<SysSmsConfigVo> queryPageList(SysSmsConfigBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysSmsConfig> lqw = buildQueryWrapper(bo);
        Page<SysSmsConfigVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询病例短信配置列表
     */
    @Override
    public List<SysSmsConfigVo> queryList(SysSmsConfigBo bo) {
        LambdaQueryWrapper<SysSmsConfig> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysSmsConfig> buildQueryWrapper(SysSmsConfigBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysSmsConfig> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getSmsName()), SysSmsConfig::getSmsName, bo.getSmsName());
        lqw.eq(StringUtils.isNotBlank(bo.getSmsCode()), SysSmsConfig::getSmsCode, bo.getSmsCode());
        lqw.eq(StringUtils.isNotBlank(bo.getSmsContent()), SysSmsConfig::getSmsContent, bo.getSmsContent());
        lqw.eq(StringUtils.isNotBlank(bo.getSmsRecipient()), SysSmsConfig::getSmsRecipient, bo.getSmsRecipient());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), SysSmsConfig::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增病例短信配置
     */
    @Override
    public Boolean insertByBo(SysSmsConfigBo bo) {
        SysSmsConfig add = MapstructUtils.convert(bo, SysSmsConfig.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改病例短信配置
     */
    @Override
    public Boolean updateByBo(SysSmsConfigBo bo) {
        SysSmsConfig update = MapstructUtils.convert(bo, SysSmsConfig.class);
        validEntityBeforeSave(update);
        boolean flag =  baseMapper.updateById(update) > 0;
        if (flag) {
            // 从数据库查询SMS配置数据做缓存
            SysSmsConfig config = baseMapper.selectById(bo.getId());
            CacheUtils.put(CacheNames.SYS_SMS_CONFIG, config.getSmsCode(), JsonUtils.toJsonString(config));
        }

        return flag;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysSmsConfig entity) {
        //TODO 做一些数据校验,如唯一约束
    }

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

    /**
     * 项目启动时，初始化SMS短信参数到缓存，加载配置类
     */
    @Override
    public void initSmsConfig() {

        // 获取所有租户SMS配置
        List<SysSmsConfig> list = TenantHelper.ignore(() ->
            baseMapper.selectList(
                new LambdaQueryWrapper<SysSmsConfig>().orderByAsc(TenantEntity::getTenantId))
        );
        // 根据租户ID分组
        Map<String, List<SysSmsConfig>> map = StreamUtils.groupByKey(list, SysSmsConfig::getTenantId);
        // 添加缓存
        try {
            for (String tenantId : map.keySet()) {
                // 动态切换租户
                TenantHelper.setDynamic(tenantId);
                // 加载SMS初始化配置
                for (SysSmsConfig config : map.get(tenantId)) {
                    CacheUtils.put(CacheNames.SYS_SMS_CONFIG, config.getSmsCode(), JsonUtils.toJsonString(config));
                }
            }
        } finally {
            // 清除动态租户
            TenantHelper.clearDynamic();
        }

    }
}
