package com.ylx.web.controller.system;

import java.util.List;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.ylx.common.annotation.Log;
import com.ylx.common.constant.UserConstants;
import com.ylx.common.core.controller.BaseController;
import com.ylx.common.core.domain.AjaxResult;
import com.ylx.common.core.domain.entity.SysDept;
import com.ylx.common.enums.BusinessType;
import com.ylx.common.utils.StringUtils;
import com.ylx.system.domain.dto.SysDeptPageQueryDTO;
import com.ylx.system.service.ISysDeptService;

/**
 * 部门信息
 *
 * @author ylx
 */
@RestController
@RequestMapping("/system/dept")
public class SysDeptController extends BaseController {

    @Autowired
    private ISysDeptService deptService;

    /**
     * 分页查询部门列表
     *
     * @param page 分页参数
     * @param dto 查询条件
     * @return AjaxResult 部门分页列表
     */
    @GetMapping("/list")
    public AjaxResult list(Page<SysDept> page, SysDeptPageQueryDTO dto) {
        try {
            return success(deptService.selectDeptPage(page, dto));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 按省市查询部门平铺列表，包含顶级部门
     *
     * @param dept 省市查询条件
     * @return AjaxResult 部门列表
     */
    @GetMapping("/region/list")
    public AjaxResult regionList(SysDept dept) {
        try {
            return success(deptService.selectDeptFlatListByRegion(dept));
        } catch (Exception e) {
            logger.error("按省市查询部门列表异常", e);
            return error("按省市查询部门列表失败");
        }
    }

    /**
     * 查询城市列表
     *
     * @return AjaxResult 城市编码和城市名称列表
     */
    @GetMapping("/city/list")
    public AjaxResult cityList() {
        try {
            return success(deptService.selectCityList());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 查询部门列表（排除节点）
     *
     * @param deptId 部门ID
     * @return AjaxResult 部门列表
     */
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list/exclude/{deptId}")
    public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId) {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        depts.removeIf(d -> d.getDeptId().intValue() == deptId || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""));
        return success(depts);
    }

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

    /**
     * 新增部门
     *
     * @param dept 部门信息
     * @return AjaxResult 新增结果
     */
    @PreAuthorize("@ss.hasPermi('system:dept:add')")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysDept dept) {
        try {
            logger.info("新增部门请求参数:{}", JSON.toJSONString(dept));
            if (!deptService.checkDeptNameUnique(dept)) {
                return error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
            }
            dept.setCreateBy(getUsername());
            return toAjax(deptService.insertDept(dept));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

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

    /**
     * 删除部门
     *
     * @param deptId 部门ID
     * @return AjaxResult 删除结果
     */
    @PreAuthorize("@ss.hasPermi('system:dept:remove')")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public AjaxResult remove(@PathVariable Long deptId) {
        try {
            if (deptService.hasChildByDeptId(deptId)) {
                return warn("存在下级部门,不允许删除");
            }
            /*if (deptService.checkDeptExistUser(deptId)) {
                return warn("部门存在用户,不允许删除");
            }*/
            deptService.checkDeptDataScope(deptId);
            return toAjax(deptService.deleteDeptById(deptId));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
