package com.zksy.web.controller.system;

import com.zksy.common.annotation.Log;
import com.zksy.common.constant.UserConstants;
import com.zksy.common.core.controller.BaseController;
import com.zksy.common.core.domain.AjaxResult;
import com.zksy.common.core.domain.entity.SysDept;
import com.zksy.common.enums.BusinessType;
import com.zksy.common.exception.ServiceException;
import com.zksy.common.utils.StringUtils;
import com.zksy.common.utils.poi.ExcelUtil;
import com.zksy.common.utils.result.Response;
import com.zksy.system.model.request.AddSysDeptReq;
import com.zksy.system.model.request.NextDeptExportReq;
import com.zksy.system.model.request.NextDeptReq;
import com.zksy.system.model.respone.DataDeptRecord;
import com.zksy.system.model.respone.FindNextDeptPagerVo;
import com.zksy.system.model.respone.NextDeptExport;
import com.zksy.system.service.ISysDeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.ObjectUtils;
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.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 部门信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/dept")
@Api(tags = "部门信息", description = "部门信息 desc")
public class SysDeptController extends BaseController {

    @Autowired
    private ISysDeptService deptService;
    /**
     * 获取部门列表
     */
    @GetMapping("/list")
    @ApiOperation(value = "获取部门列表", notes = "获取部门列表")
    public AjaxResult list(SysDept dept) {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return AjaxResult.success(depts);
    }

    /**
     * 查询部门列表（排除节点）
     */
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list/exclude/{deptId}")
    @ApiOperation(value = "查询部门列表（排除节点）", notes = "查询部门列表（排除节点）")
    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);
    }

    /**
     * 根据部门编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:dept:query')")
    @GetMapping(value = "/{deptId}")
    @ApiOperation(value = "根据部门编号获取详细信息", notes = "根据部门编号获取详细信息")
    public AjaxResult getInfo(@PathVariable Long deptId) {
        deptService.checkDeptDataScope(deptId);
        return AjaxResult.success(deptService.selectDeptById(deptId));
    }

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

    @GetMapping("/treeselect2")
    @ApiOperation(value = "获取部门下拉树列表（下拉框组织树）", notes = "新增组织账号时下拉框组织树")
    public AjaxResult treeselect2(SysDept dept) {
        List<SysDept> depts = deptService.selectDeptList(dept);
        //屏蔽树顶端部门
        //depts.remove(depts.get(0));
        List<SysDept> depts1 = new ArrayList<>();
        for (SysDept sysDept : depts) {
            if (sysDept.getParentId() != 0) {
                depts1.add(sysDept);
            }
        }
        return AjaxResult.success(deptService.buildDeptTreeSelect(depts1));
    }

    /**
     * 加载对应角色部门列表树
     */
    @GetMapping(value = "/roleDeptTreeselect/{roleId}")
    @ApiOperation(value = "加载对应角色部门列表树", notes = "加载对应角色部门列表树")
    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;
    }

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

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

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


    @ApiOperation(value = "新增、编辑部门", notes = "新增、编辑部门")
    @RequestMapping(path = "/addSysDept", method = RequestMethod.POST)
    @Log(title = "新增、编辑部门", businessType = BusinessType.UPDATE)
    public Response addSysDept(@Validated @RequestBody AddSysDeptReq req) {
        SysDept dept = new SysDept();
        dept.setDeptName(req.getDeptName());
        dept.setDelFlag("0");
        dept.setStatus("0");
        List<SysDept> sysDepts = deptService.selectDeptList(dept);
        if (!ObjectUtils.isEmpty(sysDepts) && sysDepts.size() > 0 && req.getDeptId() == null) {
            throw new ServiceException("【%s】名称已经存在!", req.getDeptName());
        }
        return deptService.addSysDept(req);
    }

    @ApiOperation(value = "查看下级单位", notes = "查看下级单位")
    @RequestMapping(path = "/findNextDept", method = RequestMethod.POST)
    public Response<FindNextDeptPagerVo> findNextDept(@Validated @RequestBody NextDeptReq req) {

        return deptService.findNextDept(req);
    }

    @ApiOperation(value = "查看部门资料", notes = "查看部门资料")
    @RequestMapping(path = "/findDataDept", method = RequestMethod.GET)
    public Response<DataDeptRecord> findDataDept(@ApiParam(value = "当前部门id", required = true) @RequestParam(value = "deptId", required = true) String deptId) {

        return deptService.findDataDept(deptId);
    }

    @ApiOperation(value = "通过机构id查询本级跟子级", notes = "通过机构id查询本级跟子级")
    @RequestMapping(path = "/selectLevelAndChild", method = RequestMethod.POST)
    public Response<List<SysDept>> selectLevelAndChild(Long deptId) {
        return deptService.selectLevelAndChild(deptId);
    }

    @Log(title = "下级单位导出", businessType = BusinessType.EXPORT)
    @ApiOperation(value = "下级单位导出", notes = "下级单位导出")
    @PostMapping("/exportDept")
    public void exportDept(HttpServletResponse response, NextDeptExportReq req) {
        List<NextDeptExport> res = deptService.exportDept(req);
        ExcelUtil<NextDeptExport> util = new ExcelUtil<NextDeptExport>(NextDeptExport.class);
        util.exportExcel(response, res, "下级单位");
    }


    @ApiOperation(value = "变更部门信息，上级单位下拉框", notes = "变更部门信息，上级单位下拉框")
    @RequestMapping(path = "/findUpDept", method = RequestMethod.GET)
    public Response<List<SysDept>> findUpDept(@ApiParam(value = "当前部门id", required = true)
                                              @RequestParam(value = "deptId", required = true) Long deptId) {

        return deptService.findUpDept(deptId);
    }


}
