package com.dxhy.admin.sys.service.impl;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dxhy.admin.sys.dao.SysDictdetaDao;
import com.dxhy.admin.sys.entity.SysDictdetaEntity;
import com.dxhy.admin.sys.service.SysDictdetaService;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.constant.RedisConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.util.redis.RedisUtils;
import com.dxhy.common.utils.Aops;
import com.dxhy.common.utils.PageUtils;
import com.dxhy.common.utils.Query;

import lombok.extern.slf4j.Slf4j;

/**
 * @author jiaohongyang
 */
@Service("sysDictdetaService")
@Slf4j
public class SysDictdetaServiceImpl extends ServiceImpl<SysDictdetaDao, SysDictdetaEntity>
    implements SysDictdetaService {

    @Resource
    private RedisUtils redisUtils;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        String dicttypecode = (String)params.get("dicttypecode");
        String dicttypeid = (String)params.get("dicttypeid");
        IPage<SysDictdetaEntity> page = this.page(new Query<SysDictdetaEntity>().getPage(params),
            new QueryWrapper<SysDictdetaEntity>()
                .like(StringUtils.isNotBlank(dicttypecode), "dicttypecode", dicttypecode)
                .eq(StringUtils.isNotBlank(dicttypeid), "dicttype", dicttypeid));

        return new PageUtils(page);
    }

    @Override
    public Long queryDictDetaId(Long id) {
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        return baseMapper.queryDictDetaId(id);
    }

    @Override
    public Integer queryDictDetaCode(String dicttypecode, String dictcode, Long dictDetaId) {
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        return Math.toIntExact(baseMapper.selectCount(new QueryWrapper<SysDictdetaEntity>().eq("dicttypecode", dicttypecode)
                .eq("dictcode", dictcode).ne(dictDetaId != null, "dictid", dictDetaId)));
    }

    @Override
    public List<SysDictdetaEntity> saveRedis(SysDictdetaEntity dect) {
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        List<SysDictdetaEntity> detaList = null;
        try {
            // 保存用户信息到redis
            detaList = baseMapper.selectList(
                new QueryWrapper<SysDictdetaEntity>().eq("dicttypecode", dect.getDicttypecode()).orderByAsc("sortno"));
            redisUtils.set(RedisConstant.KEY_DICT + dect.getDicttypecode(), detaList, -1);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return detaList;
    }

    @Override
    public void deleteRedis(Long[] ids) {
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        // 删除redis
        if (ids != null) {
            SysDictdetaEntity detaEntity = baseMapper.selectById(ids[0]);
            // 删除数据存储到redis中
            this.deleteDictIds(Arrays.asList(ids));
            // 重新保存redis值
            List<SysDictdetaEntity> detaList = baseMapper
                .selectList(new QueryWrapper<SysDictdetaEntity>().eq("dicttypecode", detaEntity.getDicttypecode()));
            if (detaList.size() > 0) {
                redisUtils.set(RedisConstant.KEY_DICT + detaEntity.getDicttypecode(), detaList, -1);
            }
        }

    }

    @Override
    public SysDictdetaEntity queryDiceDeta(Long id) {
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        return baseMapper.selectById(id);
    }

    @Override
    public void saveDictDeta(SysDictdetaEntity dict) {
        DynamicContextHolder.push(DbConstant.BASICS_WRITE);
        Aops.getSelf(this).insertDict(dict);
    }

    @Transactional(rollbackFor = Exception.class)
    public void insertDict(SysDictdetaEntity dict) {
        baseMapper.insert(dict);
    }

    @Override
    public void updateDictDeta(SysDictdetaEntity dict) {
        DynamicContextHolder.push(DbConstant.BASICS_WRITE);
        Aops.getSelf(this).updateDict(dict);
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateDict(SysDictdetaEntity dict) {
        baseMapper.updateById(dict);
    }

    @Override
    public void deleteDictIds(List<Long> ids) {
        DynamicContextHolder.push(DbConstant.BASICS_WRITE);
        Aops.getSelf(this).deleteDict(ids);
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteDict(List<Long> ids) {
        baseMapper.deleteBatchIds(ids);
    }

    @Override
    public boolean refreshCache() {
        try {
            // 获取数据字典明细信息
            Map<String, List<SysDictdetaEntity>> map = null;

            List<SysDictdetaEntity> queryDictDeta = baseMapper.queryDictDeta();
            if (queryDictDeta != null && queryDictDeta.size() > 0) {
                map = new HashMap<>(queryDictDeta.size());
                for (SysDictdetaEntity sysDictdetaEntity : queryDictDeta) {
                    List<SysDictdetaEntity> sysDictdetaEntities = this.saveRedis(sysDictdetaEntity);
                    if (sysDictdetaEntities != null && sysDictdetaEntities.size() > 0) {
                        map.put(RedisConstant.KEY_DICT + sysDictdetaEntity.getDicttypecode(), sysDictdetaEntities);
                    }
                }
            }
            //
            if (map != null) {
                redisUtils.set(RedisConstant.DICT, map, -1);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }
}
