<template>
  <div class="menu-index">
    <a-card :bordered="false" class="pt-3 mb-3 proCard">
      <div>
        <a-button type="primary" @click="handleAdd()" v-perm="['sys:city:add']">
          <template #icon><PlusOutlined /></template>
          新增
        </a-button>
      </div>
    </a-card>
    <a-card :bordered="false" class="pt-3 mb-3 proCard">
      <a-table
        border
        v-loading="loading"
        ref="tableRef"
        :columns="columns"
        :dataSource="lists"
        @expand="getChild"
        :style="{ minHeight: fwbHeight+'px' }"
        :scroll="{x:'100%',y:fwbHeight}"
        rowKey="areaCode"
      >
        <template #bodyCell="{ column, record, index }">
          <template v-if="column.key == 'action'">
            <a-space>
              <a-button type="primary" @click="handleAdd(record)" v-perm="['sys:city:add']">
                <template #icon><PlusOutlined /></template>
                新增</a-button
              >
              <a-button type="primary" @click="handleEdit(record)" v-perm="['sys:city:update']">
                <template #icon><EditOutlined /></template>
                编辑
              </a-button>
              <a-button
                type="primary"
                danger
                @click="handleDelete(record)"
                v-perm="['sys:city:delete']"
              >
                <template #icon><DeleteOutlined /></template>
                删除
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>
    <editDialog
      ref="editRef"
      v-if="editVisible"
      :cityId="cityId"
      :parentData="parentData"
      :itemData="itemData"
      v-model:visible="editVisible"
      @success="refreshDataList"
    />
  </div>
</template>

<script lang="ts" setup name="menu">
  import { defineAsyncComponent, nextTick, onMounted, ref, shallowRef } from 'vue';
  import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons-vue';
  import { cityDelete } from '@/api/data/city';
  import { getCityByList } from '@/api/system/user';
  import { columns } from './columns';
  import { Modal, message } from 'ant-design-vue';

  /**
   * 导入组件
   */
  const editDialog = defineAsyncComponent(() => import('./edit.vue'));

  /**
   * 定义参数变量
   */
  const fwbHeight = document.body.clientHeight - 350;
  const tableRef = ref();
  const loading = ref(false);
  const editVisible = ref(false);
  const cityId = ref(0);
  const parentData = ref();
  const itemData = ref({});
  const lists = ref([]);
  const maps = ref(new Map());

  /**
   * 获取行政区划列表
   * @param code 参数
   */
  const getDataList = async (code: any) => {
    try {
      loading.value = true;
      let res = await getCityByList(code);
      let data = res.length > 0 ? res : [];
      data.map((item) => {
        item.children = [];
      });
      lists.value = data;
    } catch (e) {
      lists.value = [];
    } finally {
      loading.value = false;
    }
  };

  /**
   * 刷新数据列表
   */
  const refreshDataList = (code) => {
    console.log(code);
    if (code == 0 || Object.keys(code).length === 0) {
      getDataList(0);
    } else {
      console.log(code);
      getChild(true, code);
    }
  };

  /**
   * 执行添加
   * @param data 参数
   */
  const handleAdd = async (data: any) => {
    cityId.value = 0;
    if (data) {
      itemData.value = data;
      let datas = findParentNode(lists.value, data.pid);
      if (datas) {
        parentData.value = datas;
      } else {
        parentData.value = data;
      }
    }
    await nextTick();
    editVisible.value = true;
  };

  /**
   * 执行编辑
   * @param data 参数
   */
  const handleEdit = async (data: any) => {
    cityId.value = data.id;
    parentData.value = findParentNode(lists.value, data.pid);
    await nextTick();
    editVisible.value = true;
  };

  /**
   * 执行删除
   * @param row 参数
   */
  const handleDelete = async (row: any) => {
    console.log(row);
    Modal.confirm({
      title: '提示',
      content: '确定要删除？',
      onOk: async () => {
        loading.value = true;
        await cityDelete(row.id);
        message.success('删除成功');
        refreshDataList({ areaCode: row.parentCode });
        loading.value = false;
      },
    });
  };

  /**
   * 表格点击获取子级
   * @param expanded 是否展开
   * @param record 记录
   */
  const getChild = async (expanded, record) => {
    console.log(record);
    if (expanded) {
      let res = await getCityByList(record.areaCode);
      const data = lists.value;
      const children = res;
      children.forEach((item) => {
        if (item.level < 4) {
          item.children = [];
        }
      });
      const dataSourceMap = (items) => {
        items.find((item) => {
          if (item.areaCode === record.areaCode) {
            item.children = children;
            return items;
          }
          if (item.children && item.children.length > 0) {
            dataSourceMap(item.children);
          }
        });
      };
      dataSourceMap(data);
      lists.value = [...lists.value];
    }
  };

  /**
   * 根据子节点找到父节点
   * @param nodes 节点
   * @param targetId 目标节点ID
   */
  const findParentNode = (nodes, targetId) => {
    for (let node of nodes) {
      if (node.id == targetId) {
        return node;
      }
      if (node.children && node.children.length > 0) {
        const result = findParentNode(node.children, targetId);
        if (result) {
          return node;
        }
      }
    }
  };

  /**
   * 钩子函数
   */
  onMounted(() => {
    getDataList(0);
  });
</script>

<style scoped></style>
