package com.zd.system.controller;

import com.zd.common.core.constant.UserConstants;
import com.zd.common.core.domain.per.PerFun;
import com.zd.common.core.domain.per.PerPrefix;
import com.zd.common.core.utils.SecurityUtils;
import com.zd.common.core.utils.StringUtils;
import com.zd.common.core.web.controller.BaseController;
import com.zd.common.core.web.domain.AjaxResult;
import com.zd.common.core.web.domain.ResultData;
import com.zd.common.log.annotation.Log;
import com.zd.common.log.enums.BusinessType;
import com.zd.common.security.annotation.PreAuthorize;
import com.zd.common.security.service.TokenService;
import com.zd.system.api.domain.SysDept;
import com.zd.system.api.domain.SysDeptVO;
import com.zd.system.api.model.SysDeptListVO;
import com.zd.system.service.ISysDeptService;
import com.zd.system.service.impl.SysDeptManager;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 部门信息
 *
 * @author zd
 */
@RestController
@RequestMapping("/dept")
public class SysDeptController extends BaseController {
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private SysDeptManager deptManager;
    @Autowired
    private TokenService tokenService;

    /**
     * 获取部门列表 "system:dept:list"
     */
    @PreAuthorize(hasPermi = PerPrefix.SYSTEM_DEPT+ PerFun.LIST)
    @GetMapping("/list")
    public AjaxResult list(SysDept dept) {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return AjaxResult.success(depts);
    }

    @PostMapping("/listOption")
    public AjaxResult listOption(@RequestBody SysDept dept) {
        List<SysDept> depts = deptService.selectDeptListByCollege(dept);
        return AjaxResult.success(depts);
    }

    /**
     * 获取部门列表VO - 2.6 弃用
     */
//    @PreAuthorize(hasPermi = "system:dept:list")
    @GetMapping("/listVO")
    public ResultData<List<SysDeptListVO>> listVO(SysDept dept) {
        List<SysDeptListVO> depts = deptManager.querySysDeptListVO(dept);
        return ResultData.success(depts);
    }

    /**
     * 获取院系列表-不分页（按目前的需求约定第二级组织机构为院系）-应用数据权限
     */
    @ApiOperation("获取院系列表-不分页（按目前的需求约定第二级组织机构为院系）-应用数据权限")
    @GetMapping("/departments/list")
    public AjaxResult departments() {
        List<SysDept> depts = deptService.selectDeptListByCollege(new SysDept());
        return AjaxResult.success(depts);
    }

    @ApiOperation("通过ids 查询所有的本节点和父节点ID集合")
    @PostMapping("/allParentId")
    public AjaxResult allParentId(@RequestBody List<Long> deptIds) {
        if(CollectionUtils.isEmpty(deptIds)){
            return AjaxResult.success(Collections.emptyList());
        }
        List<Long> ids = deptService.selectAllParentId(deptIds);
        return AjaxResult.success(ids);
    }


    /**
     * 获取楼栋列表-不分页（按目前的需求约定第三级组织机构为楼栋）-切勿应用数据权限
     */
    @ApiOperation("获取楼栋列表-不分页（按目前的需求约定第三级组织机构为楼栋）-切勿应用数据权限")
    @GetMapping("/{deptId}/building/list")
    public AjaxResult building(@PathVariable("deptId") Long deptId) {
        SysDept sysDept = new SysDept();
        sysDept.setParentId(deptId);
        //这里不要有数据权限
        List<SysDept> depts = deptService.selectDeptListNoAuth(sysDept);
        return AjaxResult.success(depts);
    }


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

    /**
     * 根据部门编号获取详细信息 "system:dept:query"
     */
    @PreAuthorize(hasPermi = PerPrefix.SYSTEM_DEPT+ PerFun.QUERY)
    @GetMapping(value = "/{deptId}")
    public AjaxResult getInfo(@PathVariable Long deptId) {
        return AjaxResult.success(deptService.selectDeptById(deptId));
    }

    /**
     * 根据部门编号获取详细信息 "system:dept:query"-无权限
     */
    @GetMapping(value = "/info/{deptId}")
    public AjaxResult getInfoById(@PathVariable Long deptId) {
        return AjaxResult.success(deptService.selectDeptById(deptId));
    }

    /**
     * 获取部门下拉树列表
     */
    @GetMapping("/treeselect")
    public AjaxResult treeselect(SysDept dept) {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return AjaxResult.success(deptService.buildDeptTreeSelect(depts));
    }


    /**
     * 获取部门下拉树列表(获取登录人的部门父级部门)
     */
    @GetMapping("/treeselectByUser")
    public AjaxResult treeselectByUser(SysDept dept) {
        List<SysDept> depts = deptService.treeselectByUser(dept);
        return AjaxResult.success(deptService.buildDeptTreeSelectByNo(depts));
    }

    /**
     * 加载对应角色部门列表树
     */
    @GetMapping(value = "/roleDeptTreeselect/{roleId}")
    public AjaxResult roleDeptTreeselect(@PathVariable("roleId") Long roleId) {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
        ajax.put("depts", deptService.buildDeptTreeSelect(depts));
        return ajax;
    }

    /**
     * 新增部门 "system:dept:add"
     */
    @PreAuthorize(hasPermi = PerPrefix.SYSTEM_DEPT+ PerFun.ADD)
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysDept dept) {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
            return AjaxResult.error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        dept.setCreateBy(SecurityUtils.getUsername());
        return toAjax(deptService.insertDept(dept));
    }


    /**
     * 新增部门 "system:dept:add"   (教师专用)
     */
    @PreAuthorize(hasPermi = PerPrefix.SYSTEM_DEPT+ PerFun.ADD)
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping("/addDeptByTeacher")
    public AjaxResult addDeptByTeacher(@Validated @RequestBody SysDeptVO deptVO) {
        for (SysDept sysDept : deptVO.getTeaCherDpetList()){
            if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(sysDept))) {
                return AjaxResult.error("新增部门'" + sysDept.getDeptName() + "'失败，部门名称已存在");
            }
        }
        return toAjax(deptService.insertDeptByTeaCher(deptVO));
    }

    /**
     * 部门排序 "system:dept:edit"    (教师专用)
     */
    @PreAuthorize(hasPermi = PerPrefix.SYSTEM_DEPT+ PerFun.EDIT)
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PutMapping("/editDeptOrder")
    public AjaxResult editDeptOrder(@Validated @RequestBody SysDeptVO deptVO) {
        return toAjax(deptService.editDeptOrder(deptVO));
    }

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


    /**
     * 修改部门名称 "system:dept:edit"
     */
    @PreAuthorize(hasPermi = PerPrefix.SYSTEM_DEPT+ PerFun.EDIT)
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PutMapping("/updateDeptName")
    public AjaxResult updateDeptName(@RequestBody SysDept dept) {
        dept.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(deptService.updateDeptName(dept));
    }

    /**
     * 删除部门 "system:dept:remove"
     */
    @PreAuthorize(hasPermi = PerPrefix.SYSTEM_DEPT+ PerFun.REMOVE)
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public AjaxResult remove(@PathVariable Long deptId) {
        if (deptService.hasChildByDeptId(deptId)) {
            return AjaxResult.error("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId)) {
            return AjaxResult.error("部门存在用户,不允许删除");
        }
        return toAjax(deptService.deleteDeptById(deptId));
    }


    /**
     * 查询所有的楼栋-- 默认写死第三级
     */
    @GetMapping("/builds/list")
    public AjaxResult buildsList() {
        List<SysDept> depts = deptService.selectBuildsList(new SysDept());
        return AjaxResult.success(depts);
    }


    /**
     * 获取部门下拉树列表(处理过滤，如果为父级，返回下级列表，如果为子集，返回当前。)
     */
    @GetMapping("/filterDept")
    public AjaxResult filterDept() {
        SysDept sysDept1 = deptService.selectDeptById(tokenService.getLoginUser().getSysUser().getDeptId());
        if(sysDept1.getParentId()==0){
            SysDept sysDept = new SysDept();
            sysDept.setParentId(sysDept1.getDeptId());
            List<SysDept> depts = deptService.selectDeptList(sysDept);
            return AjaxResult.success(depts);
        }
        List<SysDept> depts = new ArrayList<>();
        depts.add(sysDept1);
        return AjaxResult.success(depts);
    }
}
