<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: 'areaChildVOS',
          label: 'areaName',
          nodeKey: 'areaCode',
        }"
        :default-expand-all="tableExpand"
      >
        <el-table-column prop="areaName" label="区域名称" />
        <el-table-column prop="areaCode" label="区域代码" />
        <el-table-column prop="level" label="区域级别" />
        <el-table-column prop="operate" label="操作" slotName="operate">
          <template #default="slotProps">
            <el-button text type="success" @click="addArea(slotProps.row)">新增</el-button>
            <el-button
              text
              type="success"
              v-if="slotProps.row.areaCode != 530000"
              @click="handleEdit(slotProps.row)"
              >编辑</el-button
            >
            <el-button
              text
              type="danger"
              v-if="slotProps.row.areaCode != 530000"
              @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="areaName">
          <el-input
            v-model="dialogForm.areaName"
            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 { getRegion, addRegion, editRegion, deleteRegion } from "@/api/common";
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 getRegion();
    loading.value = false;
    if (res.code === 200) {
      tableData.value = res.data;
    } else {
      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: "",
  areaName: "", //分类名字
  parentId: "", //父级id
  level: "", //分类层级,parentId的长度
  sort: "", //排序值
  status: "1", //分类状态(1-启用 2-禁用)
});
const dialogFormRules = ref({
  areaName: [
    { required: true, message: "请输入区域名称", trigger: "blur" },
  ],
  parentId: [
    { required: true, message: "请选择上级分类", trigger: ["blur", "change"] },
  ],
  status: [{ required: true, message: "请选择分类状态", trigger: "change" }],
});
// 级联选择器配置
const cascaderProps = ref({
  label: "areaName", // 选项标签字段名
  value: "areaCode", // 选项值字段名
  children: "areaChildVOS", // 子选项字段名
  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,
    areaName: "",
    level: row.level,
    parentId: row.parentId,
    status: "1",
  });
  dialogFormVisible.value = true;
};
const handleEdit = (row) => {
  console.log("要编辑的行:", row);
  dialogTitle.value = "编辑";
  dialogFormVisible.value = true;
  dialogForm.id = row.id;
  dialogForm.areaName = row.areaName;
  dialogForm.level = row.level;
  dialogForm.parentId = row.parentId;
  // dialogForm.status = row.status?.toString() ?? '1';
};
const handleDelete = (row) => {
  console.log("要删除的行:", row);
  // 确认框
  proxy.$modal
    .confirm("是否确认要删除【" + row.areaName + "】的数据项?")
    .then(function () {
      return true
      // return deleteRegion(row.id);
    })
    .then(() => {
      getArea();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
};

const cancelDialog = () => {
  Object.assign(dialogForm, {
    // 保持响应性，手动清空字段
    id: "",
    areaName: "",
    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>
