package com.yami.shop.sys.controller;

import com.yami.shop.bean.model.SysDictType;
import com.yami.shop.common.util.R;
import com.yami.shop.service.ISysDictTypeService;
import lombok.RequiredArgsConstructor;

import lombok.extern.java.Log;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * 数据字典信息
 *
 * @author Lion Li
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/dict/type")
public class SysDictTypeController{

    private final ISysDictTypeService dictTypeService;

    /**
     * 查询字典类型列表
     */
    @GetMapping("/list")
    public R<List<SysDictType>> list(SysDictType dictType) {
        return R.SUCCESS(dictTypeService.selectDictTypeList(dictType));
    }

    /**
     * 查询字典类型详细
     *
     * @param dictId 字典ID
     */
    @GetMapping(value = "/{dictId}")
    public R<SysDictType> getInfo(@PathVariable Long dictId) {
        return R.SUCCESS(dictTypeService.selectDictTypeById(dictId));
    }

    /**
     * 新增字典类型
     */
    @PostMapping
    public R<Void> add(@Validated @RequestBody SysDictType dict) {
        if (!dictTypeService.checkDictTypeUnique(dict)) {
            return R.FAIL("新增字典'" + dict.getDictName() + "'失败，字典类型已存在");
        }
        dictTypeService.insertDictType(dict);
        return R.SUCCESS();
    }

    /**
     * 修改字典类型
     */
    @PutMapping
    public R<Void> edit(@Validated @RequestBody SysDictType dict) {
        if (dict.getDictId()==1){
            return R.FAIL("修改字典人员属性失败，字典类型人员属性不允许修改");
        }
        if (!dictTypeService.checkDictTypeUnique(dict)) {
            return R.FAIL("修改字典'" + dict.getDictName() + "'失败，字典类型已存在");
        }
        dictTypeService.updateDictType(dict);
        return R.SUCCESS();
    }

    /**
     * 删除字典类型
     *
     * @param dictIds 字典ID串
     */
    @DeleteMapping("/{dictIds}")
    public R<Void> remove(@PathVariable Long[] dictIds) {
        if (dictIds != null && Arrays.asList(dictIds).contains(1L)){
            return R.FAIL("修改字典人员属性失败，字典类型人员属性不允许删除");
        }
        dictTypeService.deleteDictTypeByIds(dictIds);
        return R.SUCCESS();
    }


    /**
     * 获取字典选择框列表
     */
    @GetMapping("/optionselect")
    public R<List<SysDictType>> optionselect() {
        List<SysDictType> dictTypes = dictTypeService.selectDictTypeAll();
        return R.SUCCESS(dictTypes);
    }
}
