package com.kxs.system.biz.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kxs.common.core.constant.enums.ErrorTypeEnum;
import com.kxs.system.biz.mapper.SysDictItemMapper;
import com.kxs.system.biz.service.SysDictItemService;
import com.kxs.system.biz.service.SysDictService;
import com.kxs.common.core.constant.CacheConstants;
import com.kxs.common.core.constant.enums.DictTypeEnum;
import com.kxs.common.core.util.R;
import com.kxs.system.api.model.SysDict;
import com.kxs.system.api.model.SysDictItem;
import lombok.AllArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;

/**
 * 字典项
 *
 * @author 秃顶的码农
 * @date 2023/03/19
 */
@Service
@AllArgsConstructor
public class SysDictItemServiceImpl extends ServiceImpl<SysDictItemMapper, SysDictItem> implements SysDictItemService {

	private final SysDictService dictService;

	/**
	 * 删除字典项
	 * @param id 字典项ID
	 * @return
	 */
	@Override
	@CacheEvict(value = CacheConstants.DICT_DETAILS, allEntries = true)
	public R removeDictItem(Long id) {
		// 根据ID查询字典ID
		SysDictItem dictItem = this.getById(id);
		SysDict dict = dictService.getById(dictItem.getDictId());
		// 系统内置
		if (DictTypeEnum.SYSTEM.getType().equals(dict.getSystemFlag())) {
			return R.failed(ErrorTypeEnum.SYS_DICT_DELETE_SYSTEM);
		}
		return R.ok(this.removeById(id));
	}

	/**
	 * 更新字典项
	 * @param item 字典项
	 * @return
	 */
	@Override
	@CacheEvict(value = CacheConstants.DICT_DETAILS, key = "#item.dictType")
	public R updateDictItem(SysDictItem item) {
		// 查询字典
		SysDict dict = dictService.getById(item.getDictId());
		// 系统内置
		if (DictTypeEnum.SYSTEM.getType().equals(dict.getSystemFlag())) {
			return R.failed(ErrorTypeEnum.SYS_DICT_UPDATE_SYSTEM);
		}
		return R.ok(this.updateById(item));
	}

}
