<script setup lang="tsx">
import { h, onMounted, reactive, ref } from 'vue';
import type { DataTableColumns, DataTableRowKey } from 'naive-ui';
import { NButton, NSpace, useDialog, useMessage } from 'naive-ui';
import { RowData } from 'naive-ui/es/data-table/src/interface';
import { Add } from '@vicons/ionicons5';
import { Subtract16Regular } from '@vicons/fluent';
import { api_fenceCarPage, api_fencePersonPage, deleteFenceApi } from '@/api';
import Cesium from '../common/Cesium.vue';

const tableData = ref([]);
const message = useMessage();

const ids = ref<DataTableRowKey[]>([]);
const expandedKeys = ref<string[] | number[]>([]);
const show = ref(false);
const pageSizes = ref([10, 20, 50, 100]);
const createModal = ref(false);
const showModal = ref(false);

const formData = ref({
  id: '',
  depName: '',
  isTop: true,
  parentResourceNo: ''
});

const searchFrom = ref({
  miningName: ''
});

const pageData = ref({
  pageNum: 1,
  pageSize: 10,
  total: 10
});

const serarchData = ref({
  pageNum: pageData.value.pageNum,
  pageSize: pageData.value.pageSize,
  rangeName: ''
});

const tableColumn = [
  {
    type: 'selection' as const,
    width: 100,
    render(row: any) {
      const isParentNode = row.ycoordinate == undefined && row.xcoordinate == undefined;
      if (!isParentNode) {
        // 非父节点（即子节点）不显示选择框
        return null;
      }
      // 父节点正常显示选择框
      return undefined;
    }
  },
  {
    title: '区域名称',
    key: 'rangeName',
    align: 'center',
    minWidth: 80,
    treeConfig: {
      indent: 20,
      expandable: (row: any) => Boolean(row.coordinate) && row.coordinate.length > 0
    },
    render(row: any) {
      return h('span', null, row.rangeName);
    }
  },
  {
    title: '序号',
    key: 'id',
    align: 'center',
    minWidth: 50,
    render(row: any) {
      if (row.id != undefined && row.rangeType != undefined) {
        return '';
      }
      return row.id;
    }
  },
  {
    title: 'X坐标',
    key: 'xcoordinate',
    align: 'center',
    minWidth: 170
  },
  {
    title: 'Y坐标',
    key: 'ycoordinate',
    align: 'center',
    minWidth: 170
  },
  {
    title: '操作',
    key: 'actions',
    align: 'center',
    minWidth: 100,
    render(row: any) {
      const isParentNode = row.ycoordinate == undefined && row.xcoordinate == undefined;
      if (isParentNode) {
        return h(NSpace, { justify: 'center' }, [
          h(
            NButton,
            {
              size: 'small',
              style: {
                color: '#eee',
                backgroundColor: '#f16255',
                borderColor: '#f16255',
                borderRadius: '5px',
                padding: '4px 12px'
              },
              onClick: () => handleDelete(row)
            },
            [
              h('img', {
                src: '/src/assets/delete.png',
                alt: '删除',
                style: {
                  width: '10px',
                  height: '10px',
                  marginRight: '5px'
                }
              }),
              '删除'
            ]
          )
        ]);
      }
      return null;
    }
  }
];

// 头部删除
function topDelete() {
  if (ids.value == null || ids.value.length == 0) {
    message.error('请选择要删除的用户');
  } else {
    dialog.create({
      title: '提示',
      content: '确定删除数据？',
      positiveText: '确定',
      negativeText: '取消',
      positiveButtonProps: {
        type: 'primary' // 设置确定按钮为蓝色
      },
      showIcon: false, // 去掉感叹号图标
      onPositiveClick: async () => {
        const id = ids.value.join(',');
        // 用户确认删除后执行删除操作
        const res = await deleteFenceApi(id);
        if (res.data.code == 200) {
          search();
          message.success('删除成功');
        } else {
          message.error(res.data.msg);
        }
      }
    });
  }
}
// 选中
function handleCheck(rowKeys: DataTableRowKey[]) {
  // 创建一个新的Set来存储最终的选中键
  // const finalKeys = new Set<DataTableRowKey>(rowKeys);

  // // 辅助函数：递归收集所有子节点的key
  // const collectChildKeys = (data: any[], result: Set<DataTableRowKey>) => {
  //   data.forEach(item => {
  //     if (item.children && item.children.length > 0) {
  //       item.children.forEach((child: any) => {
  //         result.add(child.number);
  //         if (child.children && child.children.length > 0) {
  //           collectChildKeys([child], result);
  //         }
  //       });
  //     }
  //   });
  // };

  // // 处理父节点选中时子节点全部选中
  // tableData.value.forEach(item => {
  //   if (finalKeys.has(item.id)) {
  //     // 选中所有子节点
  //     if (item.children && item.children.length > 0) {
  //       item.children.forEach((child: any) => {
  //         finalKeys.add(child.number);
  //       });
  //     }
  //   }
  // });

  // // 更新选中的键
  // ids.value = Array.from(finalKeys);
  // 创建一个新的数组来存储最终的选中键
  const finalKeys: DataTableRowKey[] = [];

  // 遍历所有选中的键
  rowKeys.forEach(key => {
    // 检查是否为父节点
    const row = tableData.value.find(item => item.id === key);
    if (row && row.ycoordinate == undefined && row.xcoordinate == undefined) {
      // 只保留父节点的选中状态
      finalKeys.push(key);
    }
  });

  // 更新选中的键
  ids.value = finalKeys;
}
// 重置
function handleReset() {
  serarchData.value = {
    pageNum: pageData.value.pageNum,
    pageSize: pageData.value.pageSize,
    rangeName: ''
  };
  search();
}

function handleQuery() {
  search();
}

function handlePageSize() {
  serarchData.value.pageSize = pageData.value.pageSize;
  pageData.value.pageNum = 1;
  serarchData.value.pageNum = 1;
  search();
}
function handlePage() {
  serarchData.value.pageNum = pageData.value.pageNum;
  search();
}
// 分页
async function search() {
  const res = await api_fencePersonPage(serarchData.value);
  if (res.data.code == 200) {
    const data = res.data.data.records;
    data.forEach((item: any, index: any) => {
      let children: any = [];
      if (item.coordinate.length > 0) {
        item.coordinate.forEach((data: any, id: any) => {
          children.push({
            id: `${item.id}-${id + 1}`,
            xcoordinate: data.xcoordinate,
            ycoordinate: data.ycoordinate
          })
        });
      }

      item.coordinate = children
    });

    tableData.value = data;
    pageData.value.total = Number(res.data.data.total);
  } else {
    message.error(res.data.msg);
  }
}
const dialog = useDialog();
// 操作删除
function handleDelete(row: any) {
  dialog.create({
    title: '提示',
    content: '确定删除数据？',
    positiveText: '确定',
    negativeText: '取消',
    positiveButtonProps: {
      type: 'primary' // 设置确定按钮为蓝色
    },
    showIcon: false, // 去掉感叹号图标
    onPositiveClick: async () => {
      const res = await deleteFenceApi(row.id);
      if (res.data.code == 200) {
        search();
        message.success('删除成功');
      } else {
        message.error(res.data.msg);
      }
    }
  });
}

// 电子围栏
function createFence() {
  showModal.value = true;
}

function handlerCancel() {
  search();
  showModal.value = false;
}

function handlerClose() {
  search();
  showModal.value = false;
}

onMounted(() => {
  search();
});
</script>

<template>
  <div id="DepartmentPage">
    <div id="home">
      <NModal v-model:show="showModal">
        <NCard style="width: 80%" title="新增电子围栏" :bordered="false" size="huge" role="dialog" aria-modal="true">
          <template #header-extra>
            <NButton @click="handlerClose()">x</NButton>
          </template>
          <Cesium></Cesium>
          <template #footer>
            <NRow>
              <NCol :span="22"></NCol>
              <NCol :span="1"></NCol>
              <NCol :span="1">
                <NButton color="#ceced6" @click="handlerCancel()">关闭</NButton>
              </NCol>
            </NRow>
          </template>
        </NCard>
      </NModal>
    </div>
    <div>
      <NSpin :show="show">
        <NCard size="medium">
          <div style="margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center">
            <NSpace>
              <div>
                区域名称
                <NInput
                  v-model:value="serarchData.rangeName"
                  placeholder="请输入采区名称"
                  style="width: 240px; margin-left: 10px"
                  clearable="true"
                />
              </div>
              <NButton
                color="#2198f2"
                style="padding: 0px 17px; border-radius: 5px; margin-left: 30px"
                @click="handleQuery"
              >
                查询
              </NButton>
              <NButton style="padding: 0px 17px; border-radius: 5px" @click="handleReset">重置</NButton>
            </NSpace>
          </div>
          <NSpace style="margin-bottom: 20px">
            <NButton color="#2198f2" style="padding: 0px 15px; border-radius: 5px" @click="createFence()">
              <img src="@/assets/xinzeng.png" alt="" style="width: 12px; height: 12px; margin-right: 10px" />
              新增电子围栏
            </NButton>
            <NButton color="#f36255" style="padding: 0px 15px; border-radius: 10px" @click="topDelete">
              <img src="@/assets/delete.png" alt="" style="width: 12px; height: 12px; margin-right: 10px" />
              删除
            </NButton>
          </NSpace>

          <NDataTable
            :columns="tableColumn"
            :row-key="row => row.id || row.rangeName"
            :data="tableData"
            :bordered="true"
            tree-column-key="rangeName"
            children-key="coordinate"
            :checked-row-keys="ids"
            default-expand-all
            @update:checked-row-keys="handleCheck"
          />

          <div style="display: flex; justify-content: end; margin-top: 30px;">
            <ElPagination v-model:current-page="pageData.pageNum" v-model:page-size="pageData.pageSize"
              :page-sizes="[10, 20, 30, 40]" background="#2196f3" layout="sizes, prev, pager, next"
              :total="pageData.total" @size-change="handlePageSize" @current-change="handlePage" />
          </div>
        </NCard>
      </NSpin>
    </div>
  </div>
</template>

<style scoped>
.table {
  margin-top: 20px;
  margin-left: 10px;
}

.search {
  margin-top: 20px;
  margin-left: 10px;
}

.n-button {
  border-radius: 0 !important;
}

.page {
  color: black;
  padding: 30px;
}

:deep(table thead tr th) {
  color: inherit;
}

.pos-add01 {
  width: 20px;
  height: 20px;
  z-index: 135;
  cursor: pointer;
  margin-right: 20px;
}

.pos-delete01 {
  width: 20px;
  height: 20px;
  z-index: 135;
  cursor: pointer;
  margin-right: 10px;
}
</style>
