package im.zksy.yjmqserver.system.controller;

import im.zksy.yjmqserver.common.shiro.ShiroActionProperties;
import im.zksy.yjmqserver.common.util.ResultBean;
import im.zksy.yjmqserver.system.model.DeptTree;
import im.zksy.yjmqserver.system.service.DeptTreeService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.List;

@Controller
@RequestMapping("/depttree")
public class DeptTreeController {

    @Resource
    private DeptTreeService deptTreeService;

    @Resource
    private ShiroActionProperties shiroActionProperties;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @GetMapping("/index")
    public String index() {
        return "dept/dept-list";
    }

    @GetMapping("/list")
    @ResponseBody
    public ResultBean getList(@RequestParam(required = false) String parentId) {
        List<DeptTree> deptList = deptTreeService.selectByParentId(parentId);
        return ResultBean.success(deptList);
    }

    @GetMapping("/tree/root")
    @ResponseBody
    public ResultBean treeAndRoot() {
        return ResultBean.success(deptTreeService.selectAllDeptTreeAndRoot());
    }

    @GetMapping("/tree")
    @ResponseBody
    public ResultBean tree() {

        return ResultBean.success(deptTreeService.selectAllDeptTree("0")
        );
    }

    @GetMapping
    public String add() {
        return "dept/dept-add";
    }


    @DeleteMapping("/{deptId}")
    @ResponseBody
    public ResultBean delete(@PathVariable("deptId") String deptId) {
        deptTreeService.deleteCascadeByID(deptId);
        return ResultBean.success();
    }

    @PutMapping
    @ResponseBody
    public ResultBean update(DeptTree dept) {
        dept.setModifyTime(dept.getCreateTime());
        deptTreeService.updateByPrimaryKey(dept);
        return ResultBean.success();
    }

    @GetMapping("/{deptId}")
    public String update(@PathVariable("deptId") String deptId, Model model) {
        DeptTree dept = deptTreeService.selectByPrimaryKey(deptId);
        model.addAttribute("dept", dept);
        return "dept/dept-add";
    }

    @PostMapping("/swap")
    @ResponseBody
    public ResultBean swapSort(Integer currentId, Integer swapId) {
        deptTreeService.swapSort(currentId, swapId);
        return ResultBean.success();
    }

    @GetMapping("/listByUsername")
    @ResponseBody
    public ResultBean listByUsername(@RequestParam(required = false) String parentId,String username) {
        if (null!=username && shiroActionProperties.getSuperAdminUsername().equals(username)) {
            parentId = "-1";
        }
        List<DeptTree> deptList = deptTreeService.selectAllDeptTree(parentId);
        return ResultBean.success(deptList);
    }



}
