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

const { addHangjing } = useHangjing()

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 type = ref<string>('')
const typeOptions = [
  {
    label: '全',
    value: '',
  },
  {
    label: '空',
    value: 'KONG',
  },
  {
    label: '海',
    value: 'HAI',
  },
]

const color = ref('#18A05855')

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 paginationReactive = reactive({
  page: 1,
  pageSize: 50,
  showSizePicker: true,
  pageSizes: [20, 50, 100],
  onChange: page => {
    paginationReactive.page = page
  },
  onUpdatePageSize: pageSize => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
  },
})
const handleCheck = (rowKeys: DataTableRowKey[]) => {
  const selectedList = data.value.filter(item => rowKeys.includes(item.id))

  addHangjing(selectedList)
}
const getHangjingData = async (params = {}) => {
  const { code, data: resData } = await getHangjing(params)

  if (code === '200') {
    data.value = resData || []
  }
}

onMounted(() => {
  getHangjingData()
})

const searchHangjing = () => {
  getHangjingData({
    timeBegin: timeRange.value?.[0],
    timeEnd: timeRange.value?.[1],
    wkt: drawnArea.value,
    hjType: type.value === '' ? null : type.value,
  })
}
</script>

<template>
  <div class="flex flex-col gap-2 w-h-full">
    <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"
    />
    <div class="flex gap-2">
      <n-select class="w-40" v-model:value="type" :options="typeOptions" />
      <!-- <n-color-picker
        v-model:value="color"
        :modes="['rgb', 'hex']"
        :swatches="[
          '#FFFFFF55',
          '#18A05855',
          '#2080F055',
          '#F0A02055',
          'rgba(208, 48, 80, 0.5)',
        ]"
      /> -->
      <!-- <n-input-group>
        <n-select
          v-model:value="drawType"
          :options="drawTypeOptions"
          placeholder="区域查询绘制类型"
        />
        <n-button type="info" @click="drawArea">绘制</n-button>
      </n-input-group> -->

      <n-button type="primary" @click="searchHangjing">检索</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="handleCheck"
    />
    <!-- :pagination="paginationReactive" -->
  </div>
</template>

<style lang="scss" scoped></style>
