package com.enterprise.manage.modules.system.controller;

import com.enterprise.manage.common.constant.ControllerConstant;
import com.enterprise.manage.core.annotation.Log;
import com.enterprise.manage.common.base.BaseController;
import com.enterprise.manage.common.constant.emuns.OperationType;
import com.enterprise.manage.common.web.response.Result;
import com.enterprise.manage.common.web.response.module.ResultTable;
import com.github.pagehelper.PageInfo;
import com.enterprise.manage.modules.system.domain.po.Dict;
import com.enterprise.manage.modules.system.service.IDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * system dictionary controller
 *
 * @author PeiZhi Guo
 * 2021-05-13 14:26
 */
@RestController
@RequestMapping(ControllerConstant.SYSTEM + "dict/v1")
public class DictController extends BaseController {

    private final IDictService dictService;

    @Autowired
    public DictController(IDictService dictService) {
        this.dictService = dictService;
    }

    @GetMapping
    @PreAuthorize("hasPermission('','sys:dict:main')")
    public ResultTable main(Dict dict) {
        return treeTable(dictService.list(dict));
    }

    @GetMapping("{id}")
    @PreAuthorize("hasPermission('','sys:dict:main')")
    public Result main(@PathVariable Long id) {
        return success(dictService.queryById(id));
    }

    @PostMapping
    @PreAuthorize("hasPermission('','sys:dict:add')")
    @Log(operationType = OperationType.INSERT , title = "字典管理")
    public Result save(Dict dict) {
        dict.insertConfigure();
        return Result.decide(dictService.save(dict));
    }

    @PutMapping
    @PreAuthorize("hasPermission('','sys:dict:edit')")
    @Log(operationType = OperationType.UPDATE , title = "字典管理")
    public Result edit(Dict dict) {
        dict.updateConfigure();
        return Result.decide(dictService.update(dict));
    }

    @DeleteMapping
    @PreAuthorize("hasPermission('','sys:dict:del')")
    @Log(operationType = OperationType.DELETE , title = "字典管理")
    public Result batchRemove(String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        for (String id : idList) {
            dictService.delete(Long.valueOf(id));
        }
        return Result.success();
    }
}
