<template>
  <a-layout class="flex-display" style="height: 100vh; background-color: white;">
    <div class="height100 width100 flex-column flex-justify-start flex-align-start">
      <!-- 头部导航 -->
      <div class="header-container">
        <div class="back-button" @click="router.push(ERouterName.PILOT_HOME)">
          <left-outlined />
          <span>返回</span>
        </div>
        <div class="action-buttons">
          <a-button
            type="primary"
            :disabled="selectedRowKeys.length === 0"
            @click="handleDownload"
          >
            <template #icon><download-outlined /></template>
            下载航线
          </a-button>
          <a-button
            type="primary"
            @click="getWaylineList"
          >
            <template #icon><reload-outlined /></template>
            刷新
          </a-button>
        </div>
      </div>

      <!-- 表格容器 -->
      <div class="table-container">
        <a-table
          :dataSource="waylineList"
          :columns="columns"
          :pagination="false"
          :row-selection="rowSelection"
          :row-key="(record: WayLine) => record.ID"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'pointList'">
              <div class="point-list">
                <div class="point-item">
                  {{ record.PointList[0] }}
                </div>
              </div>
            </template>
          </template>
        </a-table>
      </div>
    </div>
  </a-layout>
</template>

<script lang="ts" setup>
import { ERouterName } from '/@/types/enums'
import { message } from 'ant-design-vue'
import { SendOutlined, LeftOutlined, DownloadOutlined, ReloadOutlined } from '@ant-design/icons-vue'
import { getWayLineList } from '/@/api/manage'
import { onMounted, reactive, ref } from 'vue'
import { getRoot } from '/@/root'
import { ELocalStorageKey } from '/@/types'
import { useRouter } from 'vue-router'
import axios from 'axios'

const MinioHost = ref('')
const MinioBucket = ref('')
onMounted(() => {
  MinioHost.value = 'http://' + localStorage.getItem(ELocalStorageKey.MinioHost) + '/'
  MinioBucket.value = localStorage.getItem(ELocalStorageKey.MinioBucket) || ''
  getWaylineList()
})

const router = useRouter()
interface WayLine {
  ID: number
  CreateTime: string
  WayLineName: string
  WayLineType: string
  PointList: string[]
  ObjectName: string
}

interface ApiResponse {
  code: number
  data: WayLine[]
  message?: string
}

// 定义航线列表数据
const waylineList = ref<WayLine[]>([])

// 定义表格列
const columns = [
  {
    title: '航线名称',
    dataIndex: 'WayLineName',
    key: 'wayLineName',
    width: 120
  },
  {
    title: '航线类型',
    dataIndex: 'WayLineType',
    key: 'wayLineType',
    width: 100
  },
  {
    title: '点位信息',
    dataIndex: 'PointList',
    key: 'pointList',
    width: 320
  },
  {
    title: '创建时间',
    dataIndex: 'CreateTime',
    key: 'createTime',
    width: 200,
    customRender: ({ text }: { text: string }) => formatTime(text)
  }
]

// 添加选中行的状态
const selectedRowKeys = ref<number[]>([])

// 添加表格行选择配置
const rowSelection = {
  selectedRowKeys,
  onChange: (selected: number[]) => {
    selectedRowKeys.value = selected
  }
}

// 获取航线列表
function getWaylineList () {
  getWayLineList().then(res => {
    waylineList.value = (res || []).map(item => ({
      ...item,
      PointList: item.PointList
        ? [item.PointList.replace(/;/g, '\n')] // 将所有分号替换为换行符，并作为单个字符串
        : ['暂无点位信息']
    }))
  }).catch(err => {
    waylineList.value = []
    console.error('获取航线列表失败：' + err.message)
  })
}

// 格式化时间
const formatTime = (time: string) => {
  if (!time) return '-'
  try {
    const date = new Date(time)

    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hour = String(date.getHours()).padStart(2, '0')
    const minute = String(date.getMinutes()).padStart(2, '0')
    const second = String(date.getSeconds()).padStart(2, '0')

    const formatted = `${year}-${month}-${day} ${hour}:${minute}:${second}`
    return formatted
  } catch (e) {
    console.error('时间格式化失败:', e)
    return time
  }
}

// 替换下载函数
const handleDownload = () => {
  if (selectedRowKeys.value.length === 0) {
    message.warning('请选择要下载的航线')
    return
  }

  const baseUrl = MinioHost.value + MinioBucket.value
  console.log('baseUrl====', baseUrl)

  selectedRowKeys.value.forEach(key => {
    const wayline = waylineList.value.find(item => item.ID === key)
    if (wayline?.ObjectName) {
      try {
        // const url = baseUrl + '/wayline/' + wayline.ObjectName
        const url = 'http://112.44.103.230:9000/300bdf2b-a150-406e-be63-d28bd29b409f/wayline/0964e4d6-c573-4957-9640-a03780354823.kmz'
        console.log('url====', url)

        // 创建一个隐藏的 iframe
        const iframe = document.createElement('iframe')
        iframe.style.display = 'none'
        iframe.src = url

        // 添加到页面并在下载开始后移除
        document.body.appendChild(iframe)
        setTimeout(() => {
          document.body.removeChild(iframe)
        }, 2000)

        message.success('开始下载')
      } catch (error) {
        console.error('下载失败:', error)
        console.error('下载失败：' + (error as Error).message)
      }
    }
  })
}

const root = getRoot()
</script>

<style scoped>
.table-container {
  width: 100%;
  padding: 20px;
  box-sizing: border-box;
}

:deep(.ant-table-wrapper) {
  width: 100%;
}

:deep(.ant-table) {
  width: 100%;
}

:deep(.ant-table-container) {
  width: 100%;
}

:deep(.ant-table-content) {
  width: 100%;
}

/* 修改点位列表样式 */
.point-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 4px 0;
  max-height: 150px;
  overflow-y: auto;
}

.point-item {
  padding: 8px 12px;
  background-color: #f5f5f5;
  border-radius: 4px;
  line-height: 1.6;
  font-size: 14px;
  white-space: pre-wrap;
  word-break: break-all;
}

/* 美化滚动条样式 */
.point-list::-webkit-scrollbar {
  width: 6px;
}

.point-list::-webkit-scrollbar-thumb {
  background-color: #ccc;
  border-radius: 3px;
}

.point-list::-webkit-scrollbar-track {
  background-color: #f5f5f5;
}

/* 限制表格行高 */
:deep(.ant-table-row) {
  max-height: 160px;
}

:deep(.ant-table-cell) {
  vertical-align: top;
  padding: 12px 8px !important;
  max-height: 160px;
}

/* 添加到 style 部分 */
.header-container {
  width: 100%;
  height: 56px;
  background-color: #f0f2f5;
  padding: 0 24px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.back-button {
  display: flex;
  align-items: center;
  gap: 6px;
  cursor: pointer;
  padding: 6px 12px;
  border-radius: 4px;
  transition: all 0.3s;
  background-color: white;
  border: 1px solid #e5e7eb;
  color: #666;
}

.back-button:hover {
  background-color: #f4f5f7;
  color: #1890ff;
  border-color: #1890ff;
}

.back-button .anticon {
  font-size: 14px;
}

.back-button span {
  font-size: 14px;
  font-weight: 500;
}

.action-buttons {
  display: flex;
  gap: 12px;
  align-items: center;
}

:deep(.ant-btn) {
  display: flex;
  align-items: center;
  gap: 6px;
  height: 32px;
  padding: 0 16px;
  font-size: 14px;
}

:deep(.ant-btn .anticon) {
  font-size: 16px;
}
</style>
