<script setup lang="ts">
import { h } from 'vue'
import { polygon } from '@turf/turf'
import type { DataTableRowKey } from 'naive-ui'
import { NDataTable, NButton } from 'naive-ui'
import { useDrawer } from '@/hooks/draw'
import type { TType } from '@/hooks/draw'
import { getYsHangjing } from '@/api/YsHangjing'
import { useYsHangjing } from './hooks/yshangjing'
import { convertToWKT } from '@/utils/parseWKT'
import { useHangjingDetail } from '../Hangjing/hooks/hangjingDetail'

const { addYsHangjing } = useYsHangjing()
const timeRange = ref(null)
const rangeShortcuts = {
  近一天: () => {
    const cur = new Date().getTime()
    return [cur - 24 * 60 * 60 * 1000, cur]
  },
  近一周: () => {
    const cur = new Date().getTime()
    return [cur - 7 * 24 * 60 * 60 * 1000, cur]
  },
  近一月: () => {
    const cur = new Date().getTime()
    return [cur - 30 * 24 * 60 * 60 * 1000, cur]
  },
  近一年: () => {
    const cur = new Date().getTime()
    return [cur - 365 * 24 * 60 * 60 * 1000, cur]
  },
}

const drawType = ref<TType | null>(null)
const drawTypeOptions = [
  {
    label: '矩形',
    value: 'RECTANGLE',
  },
  {
    label: '多边形',
    value: 'POLYGON',
  },
  // {
  //   label: '圆',
  //   value: 'CIRCLE',
  // },
]
const drawnArea = ref<string | null>(null)
const drawnAreaEntities = []
const drawArea = () => {
  if (!drawType.value) {
    return
  }
  // TODO: 画图
  const { drawAreaFromType } = useDrawer()

  drawAreaFromType(drawType.value, (entity, positions) => {
    drawnAreaEntities.push(entity)
    console.log('画图完成', positions)
    if (positions) {
      const ellipsoid = viewer.scene.globe.ellipsoid

      const posList = positions.map(pos => {
        const cartographic = Cesium.Cartographic.fromCartesian(pos, ellipsoid)
        const latitude = Cesium.Math.toDegrees(cartographic.latitude)
        const longitude = Cesium.Math.toDegrees(cartographic.longitude)

        return [longitude, latitude]
      })
      const area = polygon([[...posList, posList[0]]])

      const wkt = convertToWKT(area)
      wkt && (drawnArea.value = wkt)
    }
  })
}

const { showDetailsModal } = useHangjingDetail()

const columns = [
  {
    type: 'selection',
    // disabled(row) {
    //   return row.name === 'Edward King 3'
    // },
  },
  {
    title: 'Name',
    key: 'title',
  },
  {
    title: 'Type',
    key: 'hjType',
  },
  {
    title: 'Action',
    key: 'actions',
    render(row) {
      return h(
        NButton,
        {
          strong: true,
          tertiary: true,
          size: 'small',
          onClick: () => showDetailsModal(`${row.title}详情`, row),
        },
        { default: () => '详情' }
      )
    },
  },
]

const data = ref([])

const handleChecks = (rowKeys: DataTableRowKey[]) => {
  const selectedList = data.value.filter(item => rowKeys.includes(item.id))

  addYsHangjing(selectedList)
}
const getYsHangjingData = async (params = {}) => {
  const { code, data: resData } = await getYsHangjing(params)

  if (code === '200') {
    data.value = resData || []
  }
}
onMounted(() => {
  getYsHangjingData()
})
const searchYsHangjing = () => {
  getYsHangjingData({
    timeBegin: timeRange.value?.[0],
    timeEnd: timeRange.value?.[1],
    wkt: drawnArea.value,
  })
}
</script>

<template>
  <div class="flex flex-col gap-2 w-h-full">
    <div class="flex gap-2">
      <n-date-picker
        v-model:formatted-value="timeRange"
        clearable
        type="datetimerange"
        :shortcuts="rangeShortcuts"
        :update-value-on-close="true"
        format="yyyy-MM-dd HH:mm:ss"
      />
      <n-button type="primary" @click="searchYsHangjing">检索</n-button>
    </div>

    <n-data-table
      class="flex-1"
      :columns="columns"
      :data="data"
      :row-key="(rowData: Record<string, any>) => rowData.id"
      flex-height
      @update:checked-row-keys="handleChecks"
    />
  </div>
</template>
