<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
      <el-form-item label="部门名称" prop="deptName">
        <el-input
          v-model="queryParams.deptName"
          placeholder="请输入部门名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:dept:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
    </el-row>

    <!-- 部门树形表格 -->
    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="deptList"
      row-key="deptId"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column prop="deptName" label="部门名称" width="260"></el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:dept:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['system:dept:add']"
          >新增子部门</el-button>
          <el-button
            v-if="scope.row.parentId != 0"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:dept:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/修改部门弹窗 -->
    <el-dialog :title="title" :visible.sync="open" width="400px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="上级部门" prop="parentId">
          <treeselect
            v-model="form.parentId"
            :options="deptOptions"
            :normalizer="normalizer"
            placeholder="选择上级部门"
            :disable-nodes="form.deptId ? [form.deptId] : []"
          />
        </el-form-item>
        <el-form-item label="部门名称" prop="deptName">
          <el-input v-model="form.deptName" placeholder="请输入部门名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 引入接口（保持和原代码一致）
import { listDept, getDept, delDept, addDept, updateDept, listDeptExcludeChild } from "@/api/system/appDept";
// 树形选择器组件
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "SimpleDept",
  components: { Treeselect },
  data() {
    return {
      // 加载状态
      loading: true,
      // 是否显示搜索
      showSearch: true,
      // 部门树形列表数据
      deptList: [],
      // 部门树形选择器选项
      deptOptions: [],
      // 弹窗标题
      title: "",
      // 弹窗显示状态
      open: false,
      // 是否全部展开树形表格
      isExpandAll: true,
      // 表格重新渲染标识（用于展开/折叠）
      refreshTable: true,
      // 查询参数（仅保留部门名称）
      queryParams: {
        deptName: undefined
      },
      // 表单数据
      form: {
        deptId: undefined,    // 部门ID（修改时用）
        parentId: 0,          // 上级部门ID（默认顶级）
        deptName: undefined   // 部门名称
      },
      // 表单校验规则（仅保留必填项）
      rules: {
        parentId: [
          { required: true, message: "上级部门不能为空", trigger: "blur" }
        ],
        deptName: [
          { required: true, message: "部门名称不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    // 初始化加载部门列表
    this.getList();
  },
  methods: {
    /**
     * 查询部门列表
     */
    getList() {
      this.loading = true;
      listDept(this.queryParams).then(response => {
        // 转换为树形结构（handleTree是全局方法，和原代码一致）
        this.deptList = this.handleTree(response.data, "deptId");
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },

    /**
     * 树形选择器数据格式化
     */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      };
    },

    /**
     * 取消弹窗
     */
    cancel() {
      this.open = false;
      this.reset();
    },

    /**
     * 重置表单
     */
    reset() {
      this.form = {
        deptId: undefined,
        parentId: 0,
        deptName: undefined
      };
      this.resetForm("form");
    },

    /**
     * 搜索
     */
    handleQuery() {
      this.getList();
    },

    /**
     * 重置搜索
     */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = { deptName: undefined };
      this.handleQuery();
    },

    /**
     * 新增部门
     */
    handleAdd(row) {
      this.reset();
      // 如果是新增子部门，默认选中当前部门作为上级
      if (row) {
        this.form.parentId = row.deptId;
      }
      this.open = true;
      this.title = "添加部门";
      // 加载部门树形选择器数据
      listDept().then(response => {
        this.deptOptions = this.handleTree(response.data, "deptId");
      });
    },

    /**
     * 展开/折叠全部
     */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },

    /**
     * 修改部门
     */
    handleUpdate(row) {
      this.reset();
      // 获取部门详情
      getDept(row.deptId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改部门";
      });
      // 加载排除当前部门的树形数据（防止修改时选择自己作为上级）
      listDeptExcludeChild(row.deptId).then(response => {
        this.deptOptions = this.handleTree(response.data, "deptId");
      });
    },

    /**
     * 提交表单（新增/修改）
     */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 修改操作
          if (this.form.deptId) {
            updateDept(this.form).then(() => {
              this.$message.success("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            // 新增操作
            addDept(this.form).then(() => {
              this.$message.success("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /**
     * 删除部门
     */
    handleDelete(row) {
      this.$confirm(`是否确认删除【${row.deptName}】部门?`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return delDept(row.deptId);
      }).then(() => {
        this.getList();
        this.$message.success("删除成功");
      }).catch(() => {});
    }
  }
};
</script>

<style scoped>
.mb8 {
  margin-bottom: 8px;
}
.dialog-footer {
  text-align: center;
}
</style>
