package com.inspect.system.controller;

import com.inspect.base.core.utils.StringUtils;
import com.inspect.base.core.web.controller.BaseController;
import com.inspect.base.core.web.domain.AjaxResult;
import com.inspect.common.log.annotation.Log;
import com.inspect.common.log.enums.BizType;
import com.inspect.common.security.annotation.RequiresPermissions;
import com.inspect.common.security.utils.SecurityUtils;
import com.inspect.system.base.domain.SysDept;
import com.inspect.system.service.ISysDeptService;

import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang3.ArrayUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping({"/dept"})
public class SysDeptController extends BaseController {
    private final ISysDeptService deptService;

    public SysDeptController(ISysDeptService deptService) {
        this.deptService = deptService;
    }

    @RequiresPermissions({"system:dept:list"})
    @GetMapping({"/list"})
    public AjaxResult list(SysDept dept) {
        List<SysDept> sysDeptList = this.deptService.selectDeptList(dept);
        return AjaxResult.success(sysDeptList);
    }

    @RequiresPermissions({"system:dept:list"})
    @GetMapping({"/list/exclude/{deptId}"})
    public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId) {
        List<SysDept> sysDeptList = this.deptService.selectDeptList(new SysDept());
        Iterator<SysDept> it = sysDeptList.iterator();
        while (true) {
            SysDept d;
            do {
                if (!it.hasNext()) {
                    return AjaxResult.success(sysDeptList);
                }

                d = it.next();
            } while ((long) d.getDeptId().intValue() != deptId && !ArrayUtils.contains(StringUtils.split(d.getAncestors(), StringUtils.COMMA), deptId + ""));

            it.remove();
        }
    }

    @RequiresPermissions({"system:dept:query"})
    @GetMapping({"/{deptId}"})
    public AjaxResult getInfo(@PathVariable Long deptId) {
        this.deptService.checkDeptDataScope(deptId);
        return AjaxResult.success(this.deptService.selectDeptById(deptId));
    }

    @GetMapping({"/treeselect"})
    public AjaxResult treeSelect(SysDept dept) {
        List<SysDept> sysDeptList = this.deptService.selectDeptList(dept);
        return AjaxResult.success(this.deptService.buildDeptTreeSelect(sysDeptList));
    }

    @GetMapping({"/roleDeptTreeselect/{roleId}"})
    public AjaxResult roleDeptTreeSelect(@PathVariable("roleId") Long roleId) {
        List<SysDept> sysDeptList = this.deptService.selectDeptList(new SysDept());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", this.deptService.selectDeptListByRoleId(roleId));
        ajax.put("depts", this.deptService.buildDeptTreeSelect(sysDeptList));
        return ajax;
    }

    @RequiresPermissions({"system:dept:add"})
    @Log(
            title = "部门管理",
            businessType = BizType.INSERT
    )
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysDept dept) {
        if ("1".equals(this.deptService.checkDeptNameUnique(dept))) {
            return AjaxResult.error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        } else {
            dept.setCreateBy(SecurityUtils.getUsername());
            return this.toAjax(this.deptService.insertDept(dept));
        }
    }

    @RequiresPermissions({"system:dept:edit"})
    @Log(
            title = "部门管理",
            businessType = BizType.UPDATE
    )
    @PostMapping({"/edit"})
    public AjaxResult edit(@Validated @RequestBody SysDept dept) {
        Long deptId = dept.getDeptId();
        this.deptService.checkDeptDataScope(deptId);
        if ("1".equals(this.deptService.checkDeptNameUnique(dept))) {
            return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        } else if (dept.getParentId().equals(deptId)) {
            return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        } else if (StringUtils.equals("1", dept.getStatus()) && this.deptService.selectNormalChildrenDeptById(deptId) > 0) {
            return AjaxResult.error("该部门包含未停用的子部门！");
        } else {
            dept.setUpdateBy(SecurityUtils.getUsername());
            return this.toAjax(this.deptService.updateDept(dept));
        }
    }

    @RequiresPermissions({"system:dept:remove"})
    @Log(
            title = "部门管理",
            businessType = BizType.DELETE
    )
    @PostMapping({"/remove/{deptId}"})
    public AjaxResult remove(@PathVariable Long deptId) {
        if (this.deptService.hasChildByDeptId(deptId)) {
            return AjaxResult.error("存在下级部门,不允许删除");
        } else if (this.deptService.checkDeptExistUser(deptId)) {
            return AjaxResult.error("部门存在用户,不允许删除");
        } else {
            this.deptService.checkDeptDataScope(deptId);
            return this.toAjax(this.deptService.deleteDeptById(deptId));
        }
    }
}
