<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryFormRef"
      v-show="showSearch"
      :inline="true"
      @submit.native.prevent
    >
      <el-form-item label="所属站点" prop="tenantId">
        <el-select
          v-model="queryParams.tenantId"
          placeholder="请选择，支持搜索"
          size="default"
          filterable
        >
          <el-option
            v-for="item in siteList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="search"
          size="default"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="refresh" size="default" @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="plus"
          size="default"
          @click="handleAdd"
        >
          新增
        </el-button>
      </el-col>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="dataList"
      row-key="id"
      :default-expand-all="isExpandAll"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column prop="title" label="导航名称"></el-table-column>
      <el-table-column
        prop="link"
        label="链接"
        align="center"
      ></el-table-column>
      <el-table-column label="站点" align="center">
        <template #default="{ row }">
          {{ siteList.find((el) => el.id === row.tenantId)?.name || "无" }}
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center">
        <template #default="{ row }">
          <span>{{ row.updateTime }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="{ row }">
          <el-button
            size="small"
            type="text"
            icon="edit"
            @click="handleUpdate(row)"
            >修改</el-button
          >
          <el-button
            size="small"
            type="text"
            icon="delete"
            @click="handleDelete(row)"
            >删除</el-button
          >
          <el-button
            v-if="row.parentId == ''"
            size="small"
            type="text"
            icon="plus"
            @click="handleAdd(row)"
            >新增子导航</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改导航对话框 -->
    <el-dialog
      :title="title"
      v-model="showEditDialog"
      width="680px"
      append-to-body
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="所属站点:" prop="tenantId">
          <el-select
            v-model="form.tenantId"
            placeholder="请选择，支持搜索"
            size="default"
            filterable
          >
            <el-option
              v-for="item in siteList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="上级导航" prop="parentId">
          <!-- <treeselect
            v-model="form.parentId"
            :options="menuOptions"
            :normalizer="normalizer"
            :show-count="true"
            placeholder="选择上级导航"
          /> -->
          <TreeSelect
            :objMap="{
              value: 'id', // ID字段名
              label: 'title', // 显示名称
              children: 'children', // 子级字段名
            }"
            :options="menuOptions"
            v-model:value="form.parentId"
            placeholder="选择上级领域"
          />
        </el-form-item>
        <el-form-item label="导航名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入导航名称" />
        </el-form-item>
        <el-form-item label="导航链接" prop="link">
          <el-input v-model="form.link" 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 setup name="Footer">
import {
  navigationList,
  navigationAdd,
  navigationEdit,
  navigationDelete,
} from "@/api/website/siteSet";
import { tenantSelect } from "@/api/subPlatform/tenant";
import { ElMessage, ElMessageBox } from "element-plus";
import { cloneDeep } from "lodash";
import { toRefs } from "vue";

const loading = ref(true); // 是否正在加载
const showSearch = ref(true); // 是否显示搜索栏
const showEditDialog = ref(false);
const queryFormRef = ref(null);
const formRef = ref(null);
const siteList = ref([]);
const menuOptions = ref([]);
const total = ref(0);
const title = ref("");
const dataList = ref([]);
// 是否展开，默认全部折叠
const isExpandAll = ref(false);
// 重新渲染表格状态
const refreshTable = ref(true);
const data = reactive({
  // 查询参数
  queryParams: {
    tenantId: undefined,
  },
  // 表单参数
  form: {},
  // 表单校验
  rules: {
    tenantId: [
      {
        required: true,
        message: "所属站点不能为空",
        trigger: ["blur", "change"],
      },
    ],
    title: [{ required: true, message: "导航名称不能为空", trigger: "blur" }],
    link: [{ required: true, message: "导航链接不能为空", trigger: "blur" }],
  },
});
const { queryParams, form, rules } = toRefs(data);

/** 查询导航列表 */
const getList = async () => {
  loading.value = true;
  const resp = await navigationList(queryParams.value);
  getTreeselect(resp.data);
  dataList.value = resp.data;
  loading.value = false;
};

// 获取站点列表
const getSiteList = async () => {
  const resp = await tenantSelect();
  siteList.value = resp.rows;
};
/** 转换导航数据结构 */
const normalizer = (node) => {
  if (node.children && !node.children.length) {
    delete node.children;
  }
  return {
    id: node.id,
    label: node.title,
    children: node.children,
  };
};
/** 查询导航下拉树结构 */
const getTreeselect = (options) => {
  // const arr = JSON.parse(JSON.stringify(options));
  const arr = cloneDeep(options);
  arr.forEach((item) => {
    delete item.children;
  });
  menuOptions.value = [];
  const menu = { id: 0, title: "主类目", children: [] };
  menu.children = arr;
  menuOptions.value.push(menu);
};
// 取消按钮
const cancel = () => {
  showEditDialog.value = false;
  reset();
};
// 表单重置
const reset = () => {
  form.value = {
    tenantId: undefined,
    parentId: undefined,
    title: undefined,
    link: undefined,
    status: 1,
  };
  if (formRef.value) {
    formRef.value.resetFields();
  }
};
/** 搜索按钮操作 */
const handleQuery = () => {
  getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
  if (queryFormRef.value) {
    queryFormRef.value.resetFields();
  }
  handleQuery();
};
/** 新增按钮操作 */
const handleAdd = (row) => {
  reset();
  if (row != null && row.parentId == "") {
    form.value.parentId = row.id;
  } else {
    form.value.parentId = "";
  }
  showEditDialog.value = true;
  title.value = "添加导航";
};
/** 修改按钮操作 */
const handleUpdate = (row) => {
  reset();
  form.value = Object.assign({}, row);
  showEditDialog.value = true;
  title.value = "修改导航";
};
/** 提交按钮 */
const submitForm = async () => {
  await formRef.value.validate();
  if (form.value.id) {
    await navigationEdit(form.value);
    ElMessage.success("修改成功");
    showEditDialog.value = false;
    getList();
  } else {
    await navigationAdd(form.value);
    ElMessage.success("新增成功");
    showEditDialog.value = false;
    getList();
  }
};
/** 删除按钮操作 */
const handleDelete = (row) => {
  ElMessageBox.confirm(`是否确认删除编号为${row.id}的数据项？`)
    .then(async () => {
      await navigationDelete(row.id);
      getList();
      ElMessage.success("删除成功");
    })
    .catch(() => {});
};
getList();
getSiteList();
</script>
