<template>
  <div class="app-container customer-control">
    <div ref="buttonRef" class="button-cont">
      <el-button :icon="btnIcon" type="primary" @click="handleClick">{{
        btnText
      }}</el-button>
      <el-button icon="Download" type="primary" @click="exportFile"
        >导出</el-button
      >
      <el-button circle icon="Refresh" @click="getArea" style="float: right;"></el-button>
    </div>
    <div class="table-cont">
      <el-table
        :header-cell-class-name="'custom-table-header'"
        ref="tableRef"
        :data="tableData"
        style="width: 100%"
        row-key="id"
        border
        lazy
        v-loading="loading"
        :tree-props="{
          children: 'children',
          label: 'landType',
          nodeKey: 'id',
        }"
        :default-expand-all="tableExpand"
      >
        <el-table-column prop="landType" label="分类名称" />
        <el-table-column prop="status" label="状态">
          <template #default="slotProps">
            <div v-if="slotProps.row.id != 0">
              <el-tag type="success" v-if="slotProps.row.status == 1">启用</el-tag>
              <el-tag type="danger" v-else>禁用</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="operate" label="操作">
          <template #default="slotProps">
            <el-button text type="success" @click="addArea(slotProps.row)">新增</el-button>
            <el-button
              text
              type="success"
              v-if="slotProps.row.id != 0"
              @click="handleEdit(slotProps.row)"
              >编辑</el-button
            >
            <el-button
              text
              type="danger"
              v-if="slotProps.row.id != 0"
              @click="handleDelete(slotProps.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 新增修改节点 -->
    <el-dialog
      v-model="dialogFormVisible"
      :title="dialogTitle"
      width="500"
      :close-on-click-modal="false"
    >
      <el-form
        :model="dialogForm"
        :label-width="'80'"
        :rules="dialogFormRules"
        ref="dialogRef"
      >
        <el-form-item label="分类名称" prop="landType">
          <el-input
            v-model="dialogForm.landType"
            autocomplete="off"
            placeholder="请输入分类名称"
          />
        </el-form-item>
        <el-form-item label="上级分类" prop="parentId">
          <el-cascader
            v-model="dialogForm.parentId"
            :options="tableData"
            :props="cascaderProps"
            placeholder="请选择上级分类"
            clearable
            style="width: 100%"
            @change="handleCascaderChange"
          />
        </el-form-item>
        <el-form-item label="是否禁用" prop="status" required>
          <el-radio-group v-model="dialogForm.status" style="margin-top: -3px">
            <el-radio value="1" size="large">启用类别</el-radio>
            <el-radio value="2" size="large">禁用类别</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelDialog">取消</el-button>
          <el-button type="primary" @click="onSaveCategory"> 保存 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { getLandTree, addLandTree, editLandTree, deleteLandTree } from "@/api/land/land";
const { proxy } = getCurrentInstance();
import { ElMessage } from 'element-plus'
const route = useRoute();
const router = useRouter();
const { params, query } = route;

const tableRef = ref(null);
const tableData = ref([]);
let loading = ref(false);
let tableExpand = ref(true);
let btnText = ref("全部折叠");
let btnIcon = ref("SortUp");
const getArea = async () => {
  loading.value = true;
  try {
    const res = await getLandTree();
     console.log(res);
    loading.value = false;
    if (res.code === 200) {
      tableData.value = [{ id: '0', landType: '土地分类', children: res.data }];
    } else {
      tableData.value = [];
    }
    console.log(tableData.value);
  } catch (error) {
    loading.value = false;
  }
};

const handleClick = () => {
  if (btnText.value === "全部展开") {
    btnText.value = "全部折叠";
    btnIcon.value = "SortUp";
    expandAllRows(tableData.value, true);
  } else {
    btnText.value = "全部展开";
    btnIcon.value = "SortDown";
    expandAllRows(tableData.value, false);
  }
};

/**
 * 递归展开/折叠所有行
 * @param {Array} rows - 当前层级的行数据
 * @param {Boolean} isExpand - true: 展开, false: 折叠
 */
const expandAllRows = (rows, isExpand) => {
  rows.forEach((row) => {
    tableRef.value.toggleRowExpansion(row, isExpand); // 控制当前行
    if (row.areaChildVOS?.length) {
      expandAllRows(row.areaChildVOS, isExpand); // 递归处理子级
    }
  });
};

const dialogFormVisible = ref(false);
const dialogRef = ref(null);
const dialogTitle = ref("新增");
const dialogForm = reactive({
  id: "",
  landType: "", //分类名字
  parentId: "", //父级id
  level: "", //分类层级,parentId的长度
  sort: "", //排序值
  status: "1", //分类状态(1-启用 2-禁用)
});
const dialogFormRules = ref({
  landType: [
    { required: true, message: "请输分类名称", trigger: "blur" },
  ],
  parentId: [
    { required: true, message: "请选择上级分类", trigger: ["blur", "change"] },
  ],
  status: [{ required: true, message: "请选择分类状态", trigger: "change" }],
});
// 级联选择器配置
const cascaderProps = ref({
  label: "landType", // 选项标签字段名
  value: "id", // 选项值字段名
  children: "children", // 子选项字段名
  emitPath: false, // 只返回当前节点值，不返回路径
  checkStrictly: true, //可以点击任意层级节点直接选中（不再需要展开到最后一级）
  expandTrigger: "hover", // 展开触发方式，默认为点击，可选值为 hover
  selectedNode: {},
});
// 递归查找节点对象
const findNodeById = (options, id) => {
  for (const node of options) {
    if (node.id === id) return node;
    if (node.children) {
      const found = findNodeById(node.children, id);
      if (found) return found;
    }
  }
  return null;
};
const handleCascaderChange = (selectedId) => {
  const selectedNode = findNodeById(tableData.value, selectedId);
  dialogForm.selectedNode = selectedNode;
};
const addArea = (row) => {
  console.log("要编辑的行:", row);
  dialogTitle.value = "新增";
  Object.assign(dialogForm, {
    // 保持响应性，手动清空字段
    id: row.id,
    landType: "",
    // level: row.level,
    parentId: row.id,
    status: "1",
  });
  dialogFormVisible.value = true;
};
const handleEdit = (row) => {
  console.log("要编辑的行:", row);
  dialogTitle.value = "编辑";
  
  dialogForm.id = row.id;
  dialogForm.landType = row.landType;
  dialogForm.status = row.status ?? '1';
  // dialogForm.level = row.level;
  dialogForm.parentId = row.id;
  // dialogForm.status = row.status?.toString() ?? '1';

  dialogFormVisible.value = true;
};
const handleDelete = (row) => {
  console.log("要删除的行:", row);
  // 确认框
  proxy.$modal
    .confirm("是否确认要删除【" + row.landType + "】的数据项?")
    .then(function () {
      return true
      // return deleteRegion(row.id);
    })
    .then(() => {
      getArea();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
};

const cancelDialog = () => {
  Object.assign(dialogForm, {
    // 保持响应性，手动清空字段
    id: "",
    landType: "",
    level: "",
    parentId: "",
    status: "1",
  });
  dialogFormVisible.value = false;
};
const onSaveCategory = () => {
  console.log(dialogForm);
  return

  dialogRef.value.validate(async (valid, fields) => {
    if (valid) {
      try {
        proxy.$modal.loading("正在保存...");
        let param = { ...dialogForm };
        param.level = dialogForm.selectedNode.level;
        let response;
        if (dialogTitle.value == "编辑") {
          response = await editRegion(param);
        } else {
          response = await addRegion(param);
        }
        proxy.$modal.closeLoading();
        if (response.code == 200) {
          cancelDialog();
          getArea();
          if (dialogTitle.value == "编辑") {
            ElMessage.success("编辑成功!");
          } else {
            ElMessage.success("新增成功!");
          }
        } else {
          ElMessage.error(response.msg);
        }
      } catch (error) {
        proxy.$modal.closeLoading();
      }
    }
  });
};

const exportFile = () => {
  console.log("导出");
};

onMounted(() => {
  getArea();
});
</script>
<style scoped>
.button-cont {
  position: absolute;
  top: 16px;
  left: 16px;
  right: 16px;
}

.table-cont {
  position: absolute;
  top: 64px;
  left: 16px;
  right: 16px;
  bottom: 16px;
  overflow-y: auto;
}
</style>
