package cn.qinys.platform.upms.api.service.impl;

import cn.qinys.platform.base.exceptions.BizException;
import cn.qinys.platform.base.utils.RedisUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.qinys.platform.entity.upms.Dictionary;
import cn.qinys.platform.entity.upms.DictionaryOption;
import cn.qinys.platform.upms.api.mapper.DictionaryMapper;
import cn.qinys.platform.upms.api.mapper.DictionaryOptionMapper;
import cn.qinys.platform.upms.api.req.*;
import cn.qinys.platform.upms.api.service.IDictionaryService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import cn.qinys.platform.base.redis.RedisKeyEnum;

import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Description:
 *
 * @author tanlie
 * Date: 2024/2/26 18:31
 */
@Service
public class DictionaryServiceImpl implements IDictionaryService {
    @Resource
    RedisUtils redisUtils;
    @Resource
    DictionaryMapper dictionaryMapper;
    @Resource
    DictionaryOptionMapper dictionaryOptionMapper;


    @Override
    public Map<Object, Object> getDictionaries() {
        String key = RedisKeyEnum.DICTIONARY.getCode();
        if (redisUtils.exists(key)) {
            return redisUtils.hGetAll(key);
        }
        // 字典查询
        QueryWrapper<Dictionary> wrapper = new QueryWrapper<>();
        List<Dictionary> dictionaries = dictionaryMapper.selectList(wrapper);
        dictionaries.forEach(dictionary -> {
            List<DictionaryOption> dictionaryOptions = dictionaryOptionMapper.selectByDictId(dictionary.getId());
            if (dictionaryOptions.isEmpty()) {
                redisUtils.hDel(RedisKeyEnum.DICTIONARY.getCode(), dictionary.getDictNameEn());
                return;
            }
            List<Map<String, Object>> dictList = dictionaryOptions.stream()
                    .sorted(Comparator.comparing(DictionaryOption::getOrd))
                    .map(dictionaryOption -> {
                        Map<String, Object> dict = new HashMap<>(4);
                        dict.put("label", dictionaryOption.getDictLabel());
                        dict.put("value", dictionaryOption.getDictValue());
                        return dict;
                    }).collect(Collectors.toList());
            redisUtils.hPut(key, dictionary.getDictNameEn(), dictList);
        });
        return redisUtils.hGetAll(key);
    }

    @Override
    public Page<Dictionary> getDictionaryPage(DictionariesPageReq req) {
        Page<Dictionary> page = new Page<>(req.getCurrent(), req.getSize());
        QueryWrapper<Dictionary> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.hasLength(req.getDictNameCn()), "dict_name_cn", req.getDictNameCn());
        wrapper.like(StringUtils.hasLength(req.getDictNameEn()), "dict_name_en", req.getDictNameEn());
        wrapper.orderByDesc("id");
        return dictionaryMapper.selectDictionaryPage(page, wrapper);
    }

    @Override
    public void createDictionary(DictionaryCreateReq req) {
        QueryWrapper<Dictionary> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_name_cn", req.getDictNameCn());
        wrapper.last("LIMIT 1");
        Dictionary cnExist = dictionaryMapper.selectOne(wrapper);
        if (cnExist != null) {
            throw new BizException("字典中文名已存在");
        }
        QueryWrapper<Dictionary> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("dict_name_en", req.getDictNameCn());
        wrapper2.last("LIMIT 1");
        Dictionary enExist = dictionaryMapper.selectOne(wrapper);
        if (enExist != null) {
            throw new BizException("字典英文名已存在");
        }
        Dictionary dictionary = new Dictionary();
        dictionary.setDictNameEn(req.getDictNameEn());
        dictionary.setDictNameCn(req.getDictNameCn());
        dictionary.setRemark(req.getRemark());
        dictionary.setCreateTime(LocalDateTime.now());
        dictionaryMapper.insert(dictionary);
    }

    @Override
    public void updateDictionary(DictionaryUpdateReq req) {
        QueryWrapper<Dictionary> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_name_cn", req.getDictNameCn());
        wrapper.last("LIMIT 1");
        Dictionary cnExist = dictionaryMapper.selectOne(wrapper);
        if (cnExist != null && !cnExist.getId().equalsIgnoreCase(req.getId())) {
            throw new BizException("字典中文名已存在");
        }
        QueryWrapper<Dictionary> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("dict_name_en", req.getDictNameCn());
        wrapper2.last("LIMIT 1");
        Dictionary enExist = dictionaryMapper.selectOne(wrapper);
        if (enExist != null && enExist.getId().equalsIgnoreCase(req.getId())) {
            throw new BizException("字典英文名已存在");
        }
        // 更新操作
        UpdateWrapper<Dictionary> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", req.getId());
        Dictionary dictionary = new Dictionary();
        dictionary.setDictNameEn(req.getDictNameEn());
        dictionary.setDictNameCn(req.getDictNameCn());
        dictionary.setRemark(req.getRemark());
        dictionaryMapper.update(dictionary, updateWrapper);
    }

    @Override
    public void refreshDictionary() {
        String key = RedisKeyEnum.DICTIONARY.getCode();
        redisUtils.delete(key);
    }

    @Override
    public void removeDictionary(DictionaryRemoveReq req) {
        for (String id : req.getIds()) {
            dictionaryMapper.deleteById(id);
            dictionaryOptionMapper.deleteByDictId(id);
        }
    }

    @Override
    public List<DictionaryOption> getOptionList(DictionaryOptionListReq req) {
        QueryWrapper<DictionaryOption> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_id", req.getDictId());
        wrapper.like(StringUtils.hasLength(req.getDictLabel()), "dict_label", req.getDictLabel());
        wrapper.orderByAsc("ord");
        return dictionaryOptionMapper.selectList(wrapper);
    }

    @Override
    public void optionCreate(DictionaryOptionCreateReq req) {
        QueryWrapper<DictionaryOption> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_id", req.getDictId());
        wrapper.eq("dict_label", req.getDictLabel());
        wrapper.last("LIMIT 1");
        DictionaryOption labelExist = dictionaryOptionMapper.selectOne(wrapper);
        if (labelExist != null) {
            throw new BizException("字典选项标签已存在");
        }
        DictionaryOption option = new DictionaryOption();
        option.setDictId(req.getDictId());
        option.setDictLabel(req.getDictLabel());
        option.setDictValue(req.getDictValue());
        option.setOrd(req.getOrd());
        dictionaryOptionMapper.insert(option);
    }

    @Override
    public void optionUpdate(DictionaryOptionUpdateReq req) {
        QueryWrapper<DictionaryOption> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_id", req.getDictId());
        wrapper.eq("dict_label", req.getDictLabel());
        wrapper.last("LIMIT 1");
        DictionaryOption labelExist = dictionaryOptionMapper.selectOne(wrapper);
        if (labelExist != null && !labelExist.getId().equalsIgnoreCase(req.getId())) {
            throw new BizException("字典选项标签已存在");
        }

        UpdateWrapper<DictionaryOption> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", req.getId());
        DictionaryOption option = new DictionaryOption();
        option.setDictId(req.getDictId());
        option.setDictLabel(req.getDictLabel());
        option.setDictValue(req.getDictValue());
        option.setOrd(req.getOrd());
        dictionaryOptionMapper.update(option, updateWrapper);
    }

    @Override
    public void optionRemove(DictionaryOptionRemoveReq req) {
        dictionaryOptionMapper.deleteBatchIds(req.getIds());
    }
}
