package com.cool.bang.modules.system.controller;

import com.cool.bang.common.constant.ControllerConstant;
import com.cool.bang.core.annotation.Log;
import com.cool.bang.common.base.BaseController;
import com.cool.bang.common.constant.enums.OperationType;
import com.cool.bang.common.web.request.PageDomain;
import com.cool.bang.common.web.response.Result;
import com.cool.bang.common.web.response.module.ResultTable;
import com.cool.bang.modules.system.domain.po.Dict;
import com.github.pagehelper.PageInfo;
import com.cool.bang.modules.system.domain.po.DictItem;
import com.cool.bang.modules.system.service.IDictItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

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

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

    private IDictItemService dictItemService;

    @Autowired
    public DictItemController(IDictItemService dictItemService) {
        this.dictItemService = dictItemService;
    }

    @GetMapping
    @PreAuthorize("hasPermission('','sys:dict:main')")
    public ResultTable list(PageDomain pageDomain, DictItem param) {
        PageInfo<DictItem> itemPage = dictItemService.page(pageDomain, param);
        return pageTable(itemPage.getList(), itemPage.getTotal());
    }

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

    @GetMapping("type/{type}")
    @PreAuthorize("hasPermission('','sys:dict:main')")
    public Result getType(@PathVariable String type) {
        return success(dictItemService.queryDictByType(type));
    }

    @PostMapping
    @PreAuthorize("hasPermission('','sys:dict:add')")
    public Result save(DictItem item) {
        item.insertConfigure();
        return decide(dictItemService.save(item));
    }

    @PutMapping
    @PreAuthorize("hasPermission('','sys:dict:edit')")
    public Result edit(DictItem item) {
        item.updateConfigure();
        return decide(dictItemService.update(item));
    }

    @DeleteMapping
    @PreAuthorize("hasPermission('','sys:dict:del')")
    public Result batchRemove(String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        for (String id : idList) {
            dictItemService.deleteById(Long.valueOf(id));
        }
        return Result.success();
    }
}
