package com.artfess.sysConfig.persistence.manager.impl;

import com.artfess.base.cache.CacheManager;
import com.artfess.base.cache.ICache;
import com.artfess.base.cache.setting.CacheSetting;
import com.artfess.base.constants.CacheKeyConst;
import com.artfess.base.context.BaseContext;
import com.artfess.base.manager.impl.BaseManagerImpl;

import com.artfess.base.util.JsonUtil;
import com.artfess.sysConfig.enums.BaseInfoStatus;
import com.artfess.sysConfig.persistence.dao.SysDictionaryCascadeDao;
import com.artfess.sysConfig.persistence.dao.SysDictionaryDao;
import com.artfess.sysConfig.persistence.dao.SysDictionaryDetailDao;
import com.artfess.sysConfig.persistence.manager.SysDictionaryDetailManager;
import com.artfess.sysConfig.persistence.manager.SysDictionaryManager;
import com.artfess.sysConfig.persistence.model.SysDictionary;
import com.artfess.sysConfig.persistence.model.SysDictionaryCascade;
import com.artfess.sysConfig.persistence.model.SysDictionaryDetail;
import com.artfess.sysConfig.persistence.param.DictModel;
import com.artfess.sysConfig.vo.DictionaryDetailVo;
import com.artfess.uc.api.impl.util.ContextUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.jsonwebtoken.lang.Collections;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Program: edp
 * @Date: 2021/3/2
 * @Author: ZQF
 * @Description: 系统字典详情
 */
@Service
public class SysDictionaryDetailManagerImpl extends BaseManagerImpl<SysDictionaryDetailDao, SysDictionaryDetail> implements SysDictionaryDetailManager {

    @Resource
    SysDictionaryDetailDao sysDictionaryDetailDao;

    @Resource
    SysDictionaryCascadeDao sysDictionaryCascadeDao;

    @Resource
    SysDictionaryManager sysDictionaryManager;

    @Resource
    SysDictionaryDao sysDictionaryDao;

    @Resource
    BaseContext baseContext;

    @Resource
    CacheManager cacheManager;
    private static final CacheSetting cacheSetting = CacheSetting.buildDefault("字典缓存");

    @Override
    @Transactional
    public void deleteDictionaryDetails(String ids) {
        Assert.hasText(ids, "ids不能为空");
        ICache cache = cacheManager.getCache("", cacheSetting);
        List<String> idsList = Arrays.asList(ids.split(","));
        List<SysDictionaryDetail> list = this.sysDictionaryDetailDao.selectBatchIds(idsList);
        if (list != null && list.size() > 0) {
            String dictionaryId = "";
            for (SysDictionaryDetail sysDictionaryDetail : list) {
                dictionaryId = sysDictionaryDetail.getDictionaryId();
                Assert.isTrue(BaseInfoStatus.isDraft(sysDictionaryDetail.getFlag().intValue()), String.format("%s状态不为“草稿”状态,不能删除。", new Object[]{sysDictionaryDetail.getName()}));
                // 修改被删除的字典项的下级级联关系
                UpdateWrapper<SysDictionaryCascade> wrapper = new UpdateWrapper<>();
                wrapper.eq("DETAIL_ID_", sysDictionaryDetail.getId());
                wrapper.or(wq -> wq.eq("LOWER_DETAIL_ID_", sysDictionaryDetail.getId()));
                sysDictionaryCascadeDao.delete(wrapper);
            }
            //删除字典
            this.sysDictionaryDetailDao.deleteBatchIds(idsList);

            //更新缓存
            SysDictionary dictionaryEntity = sysDictionaryDao.selectById(dictionaryId);
            QueryWrapper<SysDictionaryDetail> queryWrapper = new QueryWrapper<>();
            queryWrapper.like("DICTIONARY_ID_", dictionaryEntity.getId());
            queryWrapper.eq("FLAG_", 1);
            List<SysDictionaryDetail> detailEntityList = this.sysDictionaryDetailDao.selectList(queryWrapper);
            String key = CacheKeyConst.SYS_DICTIONARY_KEY + ":" + dictionaryEntity.getCode().toUpperCase() + ":";
            if (dictionaryEntity.getKindId() != 1 && StringUtils.isNotEmpty(dictionaryEntity.getTenantId())) {
                key = key + dictionaryEntity.getTenantId().toUpperCase();
            }
            //  缓存操作
//            redisUtil.del(key);
//            redisUtil.set(key, JSONObject.toJSONString(detailEntityList));
//            redisUtil.delLike(CacheKeyConst.SYS_DICT_ALL + ":");
            cache.delLike(CacheKeyConst.SYS_DICT_ALL + ":");

        }
    }

    @Override
    @Transactional
    public void updateDictionariesDetailsStatus(String ids, Integer status) {
        Assert.hasText(ids, "id不能为空");
        ICache cache = cacheManager.getCache("", cacheSetting);
        List<String> idsList = Arrays.asList(ids.split(","));
        this.sysDictionaryDetailDao.updateDictionariesDetailsStatus(idsList, status);
        //更新缓存
        String id = idsList.get(0);
        SysDictionaryDetail sysDictionaryDetail = this.sysDictionaryDetailDao.selectById(id);
        SysDictionary sysDictionary = sysDictionaryDao.selectById(sysDictionaryDetail.getDictionaryId());
        QueryWrapper<SysDictionaryDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("DICTIONARY_ID_", sysDictionary.getId());
        queryWrapper.eq("FLAG_", 1);
        List<SysDictionaryDetail> detailEntityList = this.sysDictionaryDetailDao.selectList(queryWrapper);
        String key = CacheKeyConst.SYS_DICTIONARY_KEY + ":" + sysDictionary.getCode().toUpperCase() + ":";
        if (sysDictionary.getKindId() != 1 && StringUtils.isNotEmpty(sysDictionary.getTenantId())) {
            key = key + sysDictionary.getTenantId().toUpperCase();
        }
        //  缓存操作
//        redisUtil.del(key);
//        redisUtil.set(key, JSONObject.toJSONString(detailEntityList));
//        redisUtil.delLike(CacheKeyConst.SYS_DICT_ALL + ":");
        cache.delLike(CacheKeyConst.SYS_DICT_ALL + ":");
    }

    @Override
    @Transactional
    public void updateDictionariesDetailsSequence(HashMap<String, Integer> map) {
        this.updateSequence(map);
    }

    @Override
    public List<DictModel> queryDictModelItemsByCode(String code, String tenantId) {
        return this.sysDictionaryDetailDao.queryDictModelItemsByCode(code, "");
    }

    @Override
    public List<SysDictionaryDetail> queryDictItemsByCode(String code, String tenantId) {
        return this.sysDictionaryDetailDao.queryDictItemsByCode(code, tenantId);
    }

    @Override
    public Integer getNextDetailSequence(Map<String, Object> criteriaMap) {
        return this.getNextSequence(criteriaMap);
    }

    @Override
    public void saveDictDetailLowerDetails(String detailId, String lowerDictId, String lowerDetailIds) {
        Assert.hasText(detailId, "被关联的字典项ID不能为空");
        Assert.hasText(lowerDictId, "关联的字典id不能为空");
        Assert.hasText(lowerDetailIds, "关联的字典项ID不能为空");
        ICache cache = cacheManager.getCache("", cacheSetting);
        List<String> ids = Arrays.asList(lowerDetailIds.split(","));
        if(ids!=null && ids.size()>0){
            UpdateWrapper<SysDictionaryCascade> updateWrapper =  new UpdateWrapper<>();
            updateWrapper.eq("DETAIL_ID_", detailId).in("LOWER_DETAIL_ID_",ids );
            this.sysDictionaryCascadeDao.delete(updateWrapper);
            for(String lowerDetailId:ids){
                SysDictionaryCascade dictionaryCascade=new SysDictionaryCascade();
                dictionaryCascade.setDetailId(detailId);
                dictionaryCascade.setLowerDicId(lowerDictId);
                dictionaryCascade.setLowerDetailId(lowerDetailId);
                this.sysDictionaryCascadeDao.insert(dictionaryCascade);
            }
            //  放入 Redis 缓存
//            redisUtil.delLike(CacheKeyConst.SYS_DICT_ALL+":");
            cache.delLike(CacheKeyConst.SYS_DICT_ALL+":");
        }
    }

    @Override
    public void delLowerDetails(String detailId, String lowerDetailIds) {
        Assert.hasText(detailId, "被关联的字典项ID不能为空");
        Assert.hasText(lowerDetailIds, "关联的字典项ID不能为空");
        ICache cache = cacheManager.getCache("", cacheSetting);
        List<String> ids = Arrays.asList(lowerDetailIds.split(","));
        if(ids!=null && ids.size()>0){
            UpdateWrapper<SysDictionaryCascade> updateWrapper =  new UpdateWrapper<>();
            updateWrapper.eq("DETAIL_ID_", detailId).in("LOWER_DETAIL_ID_",ids );
            this.sysDictionaryCascadeDao.delete(updateWrapper);
            // 删除 Redis 缓存
//            redisUtil.delLike(CacheKeyConst.SYS_DICT_ALL+":");
            cache.delLike(CacheKeyConst.SYS_DICT_ALL+":");
        }
    }

    @Override
    public List<SysDictionaryDetail> querySysDictionaryDetail(SysDictionaryDetail sysDictionaryDetail) {
        QueryWrapper<SysDictionaryDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(sysDictionaryDetail.getDictionaryId()), "DICTIONARY_ID_", sysDictionaryDetail.getDictionaryId());
        queryWrapper.eq(StringUtils.isNotBlank(sysDictionaryDetail.getName()), "NAME_", sysDictionaryDetail.getName());
        queryWrapper.eq(Objects.nonNull(sysDictionaryDetail.getFlag()), "FLAG_", sysDictionaryDetail.getFlag());
        return this.sysDictionaryDetailDao.selectList(queryWrapper);
    }

    @Override
    public String getTextByValue(String code, String val) throws Exception {
        Assert.hasText(code, "字典编码不能为空");
        Assert.hasText(val, "字典项值不能为空");
        ICache cache = cacheManager.getCache("", cacheSetting);
        String tenantId = baseContext.getCurrentTenantId();
        Map<String, List<LinkedHashMap<String,Object>>> res = null;
        if (cache.get(CacheKeyConst.SYS_DICT_ALL + ":" + tenantId) != null) {
            res = JsonUtil.toMap(cache.get(CacheKeyConst.SYS_DICT_ALL + ":" + tenantId).toString());
            List<LinkedHashMap<String,Object>> list = res.get(code);
            for(LinkedHashMap<String,Object> vo : list){
                if(vo.get("value").toString().trim().equals(val.trim())){
                    return vo.get("name").toString();
                }
            }
        }else{
            List<DictModel> dicList = sysDictionaryManager.queryDictListItemsByCode(code);
            if (Collections.isEmpty(dicList)) {
                return "";
            }
            for (DictModel ele : dicList) {
                if (ele.getValue().equals(val)) {
                    return ele.getName();
                }
            }
        }
        return "";
    }

}
