package com.keyware.shandan.system.controller;

import com.keyware.shandan.common.controller.BaseController;
import com.keyware.shandan.common.entity.Result;
import com.keyware.shandan.common.util.StringUtils;
import com.keyware.shandan.system.entity.SysDict;
import com.keyware.shandan.system.entity.SysDictType;
import com.keyware.shandan.system.service.SysDictService;
import com.keyware.shandan.system.service.SysDictTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.Arrays;

/**
 * <p>
 * 系统数据字典表 前端控制器
 * </p>
 *
 * @author GuoXin
 * @since 2021-11-17
 */
@RestController
@RequestMapping("/sys/dict")
public class SysDictController extends BaseController<SysDictService, SysDict, String> {


    @Autowired
    private SysDictService dictService;
    @Autowired
    private SysDictTypeService dictTypeService;

    /**
     * 跳转模块首页
     *
     * @param view 视图
     * @return 视图
     */
    @GetMapping("/")
    public ModelAndView view(ModelAndView view) {
        view.setViewName("sys/dict/dict");
        return view;
    }

    /**
     * 跳转编辑页
     *
     * @param view 视图
     * @param id   ID
     * @return 视图
     */
    @GetMapping("/edit")
    public ModelAndView editView(ModelAndView view, String id, String type) {
        view.setViewName("sys/dict/dictEdit");
        SysDict dict = null;
        if (StringUtils.hasText(id)) {
            dict = dictService.getById(id);
        }
        if(dict == null){
            dict = new SysDict();
            SysDictType dictType = dictTypeService.getById(type);
            dict.setTypeId(dictType.getId());
            dict.setType(dictType);
        }
        view.addObject("dict", dict);
        return view;
    }

    @DeleteMapping("/delete")
    public Result<Object> deleteByIds(String ids) {
        if (StringUtils.isBlank(ids)) {
            return Result.of(null, false, "参数不能为空");
        }
        dictService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.of(true);
    }
}
