<template>
  <div class="waylineList">
    <Search :importWayline="importWayline" :onClickSearch="onClickSearch" :onClickReset="onClickReset" />
    <a-table :scroll="{ x: '100%', y: 500 }" rowKey="id" :loading="state.listLoading" :columns="columns"
      :dataSource="state.list" @change="refreshData" :rowClassName="rowClassName" :pagination="paginationConfig">
      <!-- 航线名称 -->
      <template #name="{ record }">
        <a-tooltip :title="record.name">
          {{ record.name }}
        </a-tooltip>
      </template>
      <!-- 操作 -->
      <template #action="{ record }">
        <div class="flex-align-center flex-row" style="color: #2d8cf0">
          <a-tooltip title="下载">
            <DownloadOutlined style="margin-right: 10px;" @click="onClickDownload(record.id, record.name)" />
          </a-tooltip>
          <a-tooltip title="删除">
            <DeleteOutlined @click="onClickDelete(record.id, record.name)" />
          </a-tooltip>
        </div>
      </template>
    </a-table>
  </div>
</template>

<script lang="ts" setup>
import { reactive, onMounted } from 'vue';
import { Modal, message } from 'ant-design-vue';
import { DownloadOutlined, DeleteOutlined } from '@ant-design/icons-vue';
import Search from './components/Search.vue';
import { apis } from '/@/api/custom'
import { importKmzFile, downloadWaylineFile, deleteWaylineFile } from '/@/api/wayline'
import { getWorkspaceId } from '/@/utils/index';
import moment from 'moment';
import { downloadFile } from '/@/utils/common'
import { DEVICE_NAME } from '/@/types/device'

interface State {
  workspaceId: string,
  query: any,
  listLoading: boolean,
  list: any[],
};

const state: State = reactive({
  workspaceId: getWorkspaceId(),
  query: undefined,
  listLoading: false,
  list: [],
})

const paginationConfig = reactive({
  pageSizeOptions: ['20', '50', '100'],
  showQuickJumper: true,
  showSizeChanger: true,
  pageSize: 20,
  current: 1,
  total: 0
})

const fetchList = async () => {
  state.listLoading = true;
  try {
    const res = await apis.fetchWaylineList({
      ...state.query,
      order_by: 'update_time desc',
      page: paginationConfig.current,
      page_size: paginationConfig.pageSize,
    });
    if (res.code === 0) {
      state.list = res.data.list;
      paginationConfig.total = res.data.pagination.total
      paginationConfig.current = res.data.pagination.page
      paginationConfig.pageSize = res.data.pagination.page_size
    }
  } catch (e) {
    console.error(e);
  } finally {
    state.listLoading = false;
  }
}

onMounted(async () => {
  await fetchList();
});

const columns = [
  {
    title: '航线名称',
    dataIndex: 'name',
    width: 150,
    ellipsis: true,
    slots: { customRender: 'name' }
  },
  {
    title: '上传时间',
    dataIndex: 'create_time',
    width: 200,
    sorter: (a: any, b: any) => a.create_time.localeCompare(b.create_time),
    customRender: ({ text }: any) => {
      return moment(text).format('YYYY-MM-DD HH:mm:ss')
    }
  },
  {
    title: '航线类型',
    dataIndex: 'template_types',
    width: 150,
    customRender: ({ text }: any) => {
      let content = '--';
      switch (text[0]) {
        case 0:
          content = '航点航线';
          break;
        case 1:
          content = '二维正射';
          break;
        case 2:
          content = '倾斜摄影';
          break;
        case 3:
          content = '带状航线';
          break;
        default:
          break;
      }
      return content;
    }
  },
  {
    title: '飞行器型号',
    dataIndex: 'drone_model_key',
    width: 150,
    customRender: ({ text }: any) => {
      return DEVICE_NAME[text]
    }
  },
  {
    title: '负载云台',
    dataIndex: 'payload_model_keys',
    width: 150,
    customRender: ({ text }: { text: string[] }) => {
      const payloadList = text.map(key => DEVICE_NAME[key]);
      return payloadList.join('、');
    }
  },
  {
    title: '上传操作人',
    dataIndex: 'user_name',
    width: 150,
  },
  {
    title: '操作',
    dataIndex: 'actions',
    fixed: 'right',
    align: 'center',
    width: 60,
    slots: { customRender: 'action' },
  },
]

const rowClassName = (record: any, index: number) => {
  const className = []
  if ((index & 1) === 0) {
    className.push('table-striped')
  }
  return className.toString().replaceAll(',', ' ')
}

const refreshData = async (page: any) => {
  paginationConfig.current = page?.current!
  paginationConfig.pageSize = page?.pageSize!
  await fetchList();
}

// 点击搜索
const onClickSearch = async (query: any) => {
  state.query = query;
  await fetchList();
}

// 点击重置
const onClickReset = async (query: any) => {
  state.query = query;
  await fetchList();
}

// 上传航线
const importWayline = async (fileData: FormData) => {
  try {
    const res = await importKmzFile(getWorkspaceId(), fileData);
    if (res.code === 0) {
      message.success('上传成功')
      await fetchList();
    }
  } catch (error) {
    console.error(error);
  }
}

// 点击下载
const onClickDownload = async (id: string, name: string) => {
  state.listLoading = true;
  try {
    const res = await downloadWaylineFile(state.workspaceId, id);
    if (!res) {
      return;
    }
    const data = new Blob([res], { type: 'application/zip' });
    downloadFile(data, name + '.kmz');
  } catch (error) {
    console.error(error);
  } finally {
    state.listLoading = false;
  }
}

// 点击删除
const onClickDelete = (id: string, name: string) => {
  Modal.confirm({
    title: '删除航线',
    content: `确定删除${name}吗？`,
    okType: 'danger',
    onOk: async () => {
      try {
        await deleteWaylineFile(getWorkspaceId(), id);
        await fetchList();
        message.success('删除成功');
      } catch (error) {
        message.error('删除失败: ' + error);
      }
    },
  })
}
</script>

<style lang="scss">
.waylineList {
  padding: 20px;
}

.ant-table {
  border-top: 1px solid rgb(0, 0, 0, 0.06);
  border-bottom: 1px solid rgb(0, 0, 0, 0.06);
}

.ant-table-tbody tr td {
  border: 0;
}

.table-striped {
  background-color: #f7f9fa;
}
</style>