package com.ktg.iscs.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ktg.common.core.redis.RedisCache;
import com.ktg.common.utils.StringUtils;
import com.ktg.common.utils.bean.BeanUtils;
import com.ktg.iscs.domain.IsSystemAttribute;
import com.ktg.iscs.domain.vo.mail.MailVO;
import com.ktg.iscs.mapper.IsSystemAttributeMapper;
import com.ktg.iscs.service.IIsSystemAttributeService;
import com.ktg.system.domain.vo.IsSystemAttributeVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

import static com.ktg.common.constant.Constants.SYS_ATTR;

/**
 * 基础数据Service业务层处理
 *
 * @author cgj
 * @date 2025-03-11
 */
@Service
public class IsSystemAttributeServiceImpl extends ServiceImpl<IsSystemAttributeMapper, IsSystemAttribute> implements IIsSystemAttributeService {

    @Autowired
    private IsSystemAttributeMapper isSystemAttributeMapper;
    @Autowired
    private RedisCache redisCache;

    @Override
    public Page<IsSystemAttribute> getIsSystemAttributePage(Page<IsSystemAttribute> page, IsSystemAttribute isSystemAttribute) {
        Page<IsSystemAttribute> result = page(page, Wrappers.<IsSystemAttribute>lambdaQuery()
                .like(StringUtils.isNotBlank(isSystemAttribute.getSysAttrName()), IsSystemAttribute::getSysAttrName, isSystemAttribute.getSysAttrName())
                .like(StringUtils.isNotBlank(isSystemAttribute.getSysAttrKey()), IsSystemAttribute::getSysAttrKey, isSystemAttribute.getSysAttrKey())
                .like(StringUtils.isNotBlank(isSystemAttribute.getSysAttrValue()), IsSystemAttribute::getSysAttrValue, isSystemAttribute.getSysAttrValue())
                .orderByDesc(IsSystemAttribute::getSysAttrId));
        return result;
    }

    @Override
    public IsSystemAttribute getIsSystemAttributeByKey(String sysAttrKey) {
        Assert.notBlank(sysAttrKey, "请传入key");
        IsSystemAttributeVO cacheObject = redisCache.getCacheObject(SYS_ATTR + sysAttrKey);
        if (cacheObject != null) {
            return BeanUtils.toBean(cacheObject, IsSystemAttribute.class);
        } else {
            IsSystemAttribute one = getOne(Wrappers.<IsSystemAttribute>lambdaQuery()
                    .eq(IsSystemAttribute::getSysAttrKey, sysAttrKey));
            if (one != null) {
                redisCache.setCacheObject(SYS_ATTR + sysAttrKey, BeanUtils.toBean(one, IsSystemAttributeVO.class));
                return one;
            } else {
                Assert.isTrue(false, "该配置参数不存在！");
            }
        }
        return null;
    }

    @Override
    public MailVO getMailVo() {
        ArrayList<String> strings = new ArrayList<>();
        strings.add("info.mail.hostip");
        strings.add("info.mail.from");
        strings.add("info.mail.port");
        strings.add("info.mail.auth");
        strings.add("info.mail.name");
        strings.add("info.mail.company");
        List<IsSystemAttribute> list = list(Wrappers.<IsSystemAttribute>lambdaQuery()
                .in(IsSystemAttribute::getSysAttrKey, strings));
        // 邮箱服务地址
        MailVO mailVO = new MailVO();
        try {
            mailVO.setHostIp(list.stream().filter(o -> "info.mail.hostip".equals(o.getSysAttrKey())).limit(1).collect(Collectors.toList()).get(0).getSysAttrValue());
            mailVO.setFromMail(list.stream().filter(o -> "info.mail.from".equals(o.getSysAttrKey())).limit(1).collect(Collectors.toList()).get(0).getSysAttrValue());
            mailVO.setPort(list.stream().filter(o -> "info.mail.port".equals(o.getSysAttrKey())).limit(1).collect(Collectors.toList()).get(0).getSysAttrValue());
            mailVO.setAuth(list.stream().filter(o -> "info.mail.auth".equals(o.getSysAttrKey())).limit(1).collect(Collectors.toList()).get(0).getSysAttrValue());
            mailVO.setName(list.stream().filter(o -> "info.mail.name".equals(o.getSysAttrKey())).limit(1).collect(Collectors.toList()).get(0).getSysAttrValue());
            mailVO.setCompany(list.stream().filter(o -> "info.mail.company".equals(o.getSysAttrKey())).limit(1).collect(Collectors.toList()).get(0).getSysAttrValue());

        } catch (Exception e) {
            Assert.isTrue(false, "邮箱参数缺失，请检查！");
        }
        return mailVO;
    }

    @Override
    public Boolean insertIsSystemAttribute(IsSystemAttribute isSystemAttribute) {
        Assert.notBlank(isSystemAttribute.getSysAttrKey(), "键名不可为空");
        Assert.notBlank(isSystemAttribute.getSysAttrValue(), "键值不可为空");
        // 1.判断键名不可重复
        List<IsSystemAttribute> list = list(Wrappers.<IsSystemAttribute>lambdaQuery()
                .eq(IsSystemAttribute::getSysAttrKey, isSystemAttribute.getSysAttrKey()));
        Assert.isTrue(list.isEmpty(), "当前键名已存在！");
        save(isSystemAttribute);
        // 2.开始缓存
        String key = SYS_ATTR + isSystemAttribute.getSysAttrKey();
        redisCache.setCacheObject(key, BeanUtils.toBean(isSystemAttribute, IsSystemAttributeVO.class));
        return true;
    }

    @Override
    public Boolean updateIsSystemAttribute(IsSystemAttribute isSystemAttribute) {
        Assert.notNull(isSystemAttribute.getSysAttrId(), "主键id不可为空！");
        Assert.notBlank(isSystemAttribute.getSysAttrKey(), "键名不可为空");
        Assert.notBlank(isSystemAttribute.getSysAttrValue(), "键值不可为空");
        // 1.判断键名不可重复
        List<IsSystemAttribute> list = list(Wrappers.<IsSystemAttribute>lambdaQuery()
                .eq(IsSystemAttribute::getSysAttrKey, isSystemAttribute.getSysAttrKey())
                .ne(IsSystemAttribute::getSysAttrId, isSystemAttribute.getSysAttrId()));
        Assert.isTrue(list.isEmpty(), "当前键名已存在！");
        // 2.1因为不知道会不会改键名，所以不管怎么样都把之前的缓存删掉重新插
        IsSystemAttribute byId = getById(isSystemAttribute.getSysAttrId());
        redisCache.deleteObject(SYS_ATTR + byId.getSysAttrKey());
        // 2.开始缓存
        String key = SYS_ATTR + isSystemAttribute.getSysAttrKey();
        redisCache.setCacheObject(key, BeanUtils.toBean(isSystemAttribute, IsSystemAttributeVO.class));
        return updateById(isSystemAttribute);
    }

    @Override
    public Boolean deleteIsSystemAttributeByIds(String ids) {
        Assert.notBlank(ids, "请选择需要删除的数据!");
        Long[] longIds = Convert.toLongArray(ids);
        List<Long> idList = Arrays.asList(longIds);
        // 开始清理缓存
        List<IsSystemAttribute> isSystemAttributes = listByIds(idList);
        for (IsSystemAttribute isSystemAttribute : isSystemAttributes) {
            redisCache.deleteObject(SYS_ATTR + isSystemAttribute.getSysAttrKey());
        }
        return removeBatchByIds(idList);
    }

    @Override
    public Boolean refreshAttrCache() {
        // 开始删除
        redisCache.deleteObject(SYS_ATTR);
        // 查询所有的数据库数据
        List<IsSystemAttribute> list = list();
        // 开始缓存
        if (!list.isEmpty()) {
            for (IsSystemAttribute isSystemAttribute : list) {
                redisCache.setCacheObject(SYS_ATTR + isSystemAttribute.getSysAttrKey(), BeanUtils.toBean(isSystemAttribute, IsSystemAttributeVO.class));
            }
        }
        return true;
    }

}
