package com.ebts.web.controller.system;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.ebts.common.core.entity.Result;
import com.ebts.common.core.entity.TreeSelect;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ebts.common.annotation.Log;
import com.ebts.common.constant.UserConstants;
import com.ebts.common.core.controller.BaseController;
import com.ebts.common.core.entity.entity.Dept;
import com.ebts.common.enums.BusinessType;
import com.ebts.common.utils.SecurityUtils;
import com.ebts.common.utils.StringUtils;
import com.ebts.system.service.DeptService;

/**
 * 部门信息
 *
 * @author binlin
 */
@RestController
@RequestMapping("/system/dept")
public class DeptController extends BaseController {
    @Autowired
    private DeptService deptService;

    /**
     * 获取部门列表
     */
    @PreAuthorize("@ebts.hasPermi('system:dept:list')")
    @GetMapping("/list")
    public Result<List<Dept>> list(Dept dept) {
        List<Dept> deptList = deptService.selectDeptList(dept);
        return Result.ok(deptList);

    }

    /**
     * 查询部门列表（排除节点）
     */
    @PreAuthorize("@ebts.hasPermi('system:dept:list')")
    @GetMapping("/list/exclude/{deptId}")
    public Result<List<Dept>> excludeChild(@PathVariable(value = "deptId", required = false) Long deptId) {
        List<Dept> deptList = deptService.selectDeptList(new Dept());
        Iterator<Dept> it = deptList.iterator();
        while (it.hasNext()) {
            Dept d = (Dept) it.next();
            if (d.getDeptId().intValue() == deptId
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + "")) {
                it.remove();
            }
        }
        return Result.ok(deptList);

    }

    /**
     * 根据部门编号获取详细信息
     */
    @PreAuthorize("@ebts.hasPermi('system:dept:query')")
    @GetMapping(value = "/{deptId}")
    public Result<Dept> getInfo(@PathVariable Long deptId) {
        return Result.ok(deptService.selectDeptById(deptId));
    }

    /**
     * 获取部门下拉树列表
     */
    @GetMapping("/treeselect")
    public Result<List<TreeSelect>> treeselect(Dept dept) {
        List<Dept> deptList = deptService.selectDeptList(dept);
        return Result.ok(deptService.buildDeptTreeSelect(deptList));
    }

    /**
     * 加载对应角色部门列表树
     */
    @GetMapping(value = "/roleDeptTreeselect/{roleId}")
    public Result<Map<String, Object>> roleDeptTreeselect(@PathVariable("roleId") Long roleId) {
        List<Dept> deptList = deptService.selectDeptList(new Dept());
        Map<String, Object> result = new HashMap<>();
        result.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
        result.put("deptList", deptService.buildDeptTreeSelect(deptList));
        return Result.ok(result);
    }

    /**
     * 新增部门
     */
    @PreAuthorize("@ebts.hasPermi('system:dept:add')")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping
    public Result<Integer> add(@Validated @RequestBody Dept dept) {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
            return Result.error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        dept.setCreateBy(SecurityUtils.getUserId());
        return toResult(deptService.insertDept(dept));
    }

    /**
     * 修改部门
     */
    @PreAuthorize("@ebts.hasPermi('system:dept:edit')")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public Result<Integer> edit(@Validated @RequestBody Dept dept) {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
            return Result.error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        } else if (dept.getParentId().equals(dept.getDeptId())) {
            return Result.error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        } else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus())
                && deptService.selectNormalChildrenDeptById(dept.getDeptId()) > 0) {
            return Result.error("该部门包含未停用的子部门！");
        }
        dept.setUpdateBy(SecurityUtils.getUserId());
        return toResult(deptService.updateDept(dept));
    }

    /**
     * 删除部门
     */
    @PreAuthorize("@ebts.hasPermi('system:dept:remove')")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public Result<Integer> remove(@PathVariable Long deptId) {
        if (deptService.hasChildByDeptId(deptId)) {
            return Result.error("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId)) {
            return Result.error("部门存在用户,不允许删除");
        }
        return toResult(deptService.deleteDeptById(deptId));
    }
}
