<template>
  <div class="app-container">
    <!-- 搜索条件 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="目录名称" prop="cataName">
        <el-input
          v-model="queryParams.cataName"
          placeholder="请输入目录名称"
          clearable
          @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="['gallery:cata: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>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 树状表格 -->
    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="cataList"
      row-key="id"
      :default-expand-all="isExpandAll"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        label="目录名称"
        prop="cataName"
        sortable="custom"
      />
      <el-table-column
        label="类型"
        align="center"
        prop="type"
        sortable="custom"
      />
      <el-table-column
        label="备注"
        align="center"
        prop="remarks"
        sortable="custom"
      />
      <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="['gallery:cata:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['gallery:cata:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      hide-on-single-page
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加/修改对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="70%"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <!-- 新增条件渲染：只有当parentId存在（非根目录）时显示父级目录选择框 -->
        <el-col :span="24" v-if="form.parentId !== undefined && form.parentId !== 0">
          <el-form-item label="父级目录" prop="parentId">
            <treeselect
              v-model="form.parentId"
              :options="cataOptions"
              :normalizer="normalizer"
              placeholder="选择父级目录"
              :allow-empty="true"
            />
          </el-form-item>
        </el-col>
        <!-- 其他表单项保持不变 -->
        <el-col :span="12">
          <el-form-item label="目录名称" prop="cataName">
            <el-input
              v-model="form.cataName"
              placeholder="请输入目录名称"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注" prop="remarks">
            <el-input
              v-model="form.remarks"
              type="textarea"
              placeholder="请输入内容"
            />
          </el-form-item>
        </el-col>
      </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 {pageListCata, getCata, delCata, addCata, updateCata} from "@/api/gallery/cata";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {mapGetters} from "vuex";

export default {
  name: "Cata",
  components: {Treeselect},
  data() {
    return {
      // 重新渲染表格状态
      refreshTable: true,
      // 加载状态
      loading: false,
      // 搜索条件显示
      showSearch: true,
      // 树状表格数据
      cataList: [],
      // 对话框父级目录选项
      cataOptions: [],
      // 弹出层标题
      title: "",
      // 弹出层显示状态
      open: false,
      // 展开/折叠状态
      isExpandAll: true,
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        cataName: null,
      },
      // 表单数据
      form: {
        id: null,
        cataName: null,
        parentId: null,
        remarks: null,
        type: null, // 若有类型字段需补充
      },
      // 表单校验规则
      rules: {
        cataName: [
          {required: true, message: "目录名称不能为空", trigger: "blur"}
        ],
        // 父级目录允许为空（根节点）
        remarks: [
          {required: false, message: "备注长度不超过500字", trigger: "blur"}
        ]
      },
      // 选中项
      ids: [],
      names: [],
      single: true,
      multiple: true,
    };
  },
  computed: {
    ...mapGetters(["getToken"]) // 若需权限控制
  },
  created() {
    this.getList();
  },
  methods: {
    /** 获取目录列表 */
    getList() {
      this.loading = true;
      pageListCata(this.queryParams).then(({rows, total}) => {
        this.cataList = rows;
        this.cataOptions = rows; // 父级目录选项使用全量数据
        this.total = total;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    /** 展开/折叠所有节点 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 重置表单 */
    reset() {
      this.form = {
        id: null,
        cataName: null,
        parentId: null,
        remarks: null,
        type: null,
      };
      this.resetForm("form");
    },
    /** 搜索 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置搜索 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 处理选中项 */
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.names = selection.map((item) => item.cataName);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增目录";
    },
    /** 修改 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getCata(id).then(({data}) => {
        this.form = data;
        this.open = true;
        this.title = "修改目录";
      });
    },
    /** 提交表单 */
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const api = this.form.id ? updateCata : addCata;
          api(this.form).then(() => {
            this.$modal.msgSuccess(this.form.id ? "修改成功" : "新增成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 删除 */
    handleDelete(row) {
      // 校验是否存在子节点
      if (row.children && row.children.length > 0) {
        // 使用与成功提示统一的提示方法（假设警告提示为 msgWarning）
        this.$modal.msgWarning("该目录存在下级目录，无法直接删除，请先删除下级目录");
        return; // 终止删除流程
      }
      // 无下级目录时执行原删除逻辑
      const id = row.id;
      const name = row.cataName;
      this.$modal.confirm(`是否确认删除“${name}”？`).then(() => {
        delCata(id).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功"); // 保持原有成功提示
        });
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    /** Treeselect 节点格式化（若字段名不一致时使用） */
    normalizer(node) {
      return {
        id: node.id,
        label: node.cataName,
        children: node.children,
      };
    }
  }
};
</script>
