package com.keyware.shandan.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.keyware.shandan.common.entity.Result;
import com.keyware.shandan.common.service.BaseServiceImpl;
import com.keyware.shandan.system.entity.SysDict;
import com.keyware.shandan.system.entity.SysDictType;
import com.keyware.shandan.system.mapper.SysDictMapper;
import com.keyware.shandan.system.service.SysDictService;
import com.keyware.shandan.system.utils.DictUtil;
import com.keyware.shandan.system.utils.StringUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.Serializable;

/**
 * <p>
 * 系统数据字典表 服务实现类
 * </p>
 *
 * @author GuoXin
 * @since 2021-11-17
 */
@Service
public class SysDictServiceImpl extends BaseServiceImpl<SysDictMapper, SysDict, String> implements SysDictService {
    @Override
    public Result<SysDict> updateOrSave(SysDict entity) throws Exception {
        SysDict old = getById(entity.getId());
        if(old == null || !entity.getDictName().equals(old.getDictName())){
            SysDict existDict = getDictByTypeAndName(entity.getTypeId(), entity.getDictName());
            if(existDict != null){
                return Result.of(null, false, "字典名称已存在");
            }
        }
        entity.setDictCode(entity.getDictValue());
        // entity.setDictValue(entity.getDictName());
        boolean ok = super.saveOrUpdate(entity);
        if(ok){
            DictUtil.putDict(entity);
        }
        return Result.of(ok ? entity : null, ok);
    }

    private SysDict getDictByTypeAndName(String typeId, String dictName) {
        QueryWrapper<SysDict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("TYPE_ID", typeId).eq("DICT_NAME", dictName);
        return getOne(queryWrapper);
    }

    @Override
    public Result<Boolean> deleteById(String id) {
        boolean ok = super.removeById(id);
        if(ok){
            DictUtil.removeDict(id);
        }
        return Result.of(ok, ok);
    }
}
