package com.njzscloud.dispose.sys.dict.controller;

import cn.hutool.core.collection.CollUtil;
import com.njzscloud.common.core.ienum.DictManager;
import com.njzscloud.common.core.utils.R;
import com.njzscloud.common.mp.support.PageParam;
import com.njzscloud.common.mp.support.PageResult;
import com.njzscloud.dispose.sys.dict.pojo.entity.DictEntity;
import com.njzscloud.dispose.sys.dict.pojo.result.ObtainDictDataResult;
import com.njzscloud.dispose.sys.dict.service.DictService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 字典表
 */
@Slf4j
@RestController
@RequestMapping("/dict")
@RequiredArgsConstructor
public class DictController {

    private final DictService dictService;
    private final DictManager dictManager;

    /**
     * 新增
     */
    @PostMapping("/add")
    public R<?> add(@RequestBody DictEntity dictEntity) {
        dictService.add(dictEntity);
        dictManager.remove(dictEntity.getDictKey());
        return R.success();
    }

    /**
     * 修改
     */
    @PostMapping("/modify")
    public R<?> modify(@RequestBody DictEntity dictEntity) {
        dictService.modify(dictEntity);
        dictManager.remove(dictEntity.getDictKey());
        return R.success();
    }

    /**
     * 删除
     */
    @PostMapping("/del")
    public R<?> del(@RequestBody List<Long> ids) {
        List<String> keys = dictService.del(ids);
        if (CollUtil.isNotEmpty(keys)) {
            for (String key : keys) {
                dictManager.remove(key);
            }
        }
        return R.success();
    }

    /**
     * 详情
     */
    @GetMapping("/detail")
    public R<DictEntity> detail(@RequestParam("id") Long id) {
        return R.success(dictService.detail(id));
    }

    /**
     * 分页查询
     */
    @GetMapping("/paging")
    public R<PageResult<DictEntity>> paging(PageParam pageParam, DictEntity dictEntity) {
        return R.success(dictService.paging(pageParam, dictEntity));
    }


    /**
     * 获取字典数据
     */
    @GetMapping("/dict_data")
    public R<List<ObtainDictDataResult>> obtainDictData(@RequestParam("dictKey") String dictKey,
                                                        @RequestParam(value = "txt", required = false) String txt) {
        return R.success(dictService.obtainDictData(dictKey, txt));
    }

}
