<template>
  <div class="mediaList">
    <Search :selectedRowKeys="state.selectedRowKeys" :onClickDownload="onClickBatchDownload"
      :onClickSearch="async () => { }" :onClickReset="async () => { }" />
    <div style="background: #FFFFFF;padding: 20px;">
      <div class="mediaList-info">
        <div>
          媒体文件
        </div>
        <div class="mediaList-info-right">
          <div class="mediaList-info-right-text">
            <div>
              已选/全部：
            </div>
            <div>
              0/175
            </div>
          </div>
          <a-button style="padding:0 5px;" :type="state.mode === 'table' ? 'primary' : 'default'"
            :ghost="state.mode === 'table'" size="small" @click="state.mode = 'table'">
            <MenuOutlined />
          </a-button>
          <a-button style="padding:0 5px;" :type="state.mode === 'list' ? 'primary' : 'default'"
            :ghost="state.mode === 'list'" size="small" @click="state.mode = 'list'">
            <AppstoreOutlined />
          </a-button>
        </div>
      </div>
      <div class="mediaList-table" v-if="state.mode === 'table'">
        <a-table :scroll="{ x: '100%', y: 500 }" :childrenColumnName="null" rowKey="id" :loading="state.listLoading"
          :columns="columns" :dataSource="state.list" :rowClassName="rowClassName" :pagination="paginationConfig"
          :rowSelection="{ selectedRowKeys: state.selectedRowKeys, onChange: onSelectChange }">
          <!-- 文件夹名称 -->
          <template #dir_name="{ record }">
            <a-tooltip :title="record.dir_name">
              <div class="fileName" @click="onClickFile(record)">
                <img :src="fileSrc">
                <div>
                  {{ record.dir_name }}
                </div>
              </div>
            </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)" />
              </a-tooltip>
              <a-tooltip title="轨迹回放">
                <EnvironmentOutlined @click="onClickTrajectory" />
              </a-tooltip>
            </div>
          </template>
        </a-table>
      </div>
      <div class="mediaList-list" v-else>
        <a-list :grid="{ gutter: 16, xs: 1, sm: 2, md: 3, lg: 4, xl: 8, xxl: 12 }" :loading="state.listLoading"
          :dataSource="state.list" :pagination="paginationConfig">
          <template #renderItem="{ item }">
            <a-list-item>
              <a-card hoverable @click="onClickFile(item)">
                <template #cover>
                  <div style="display: flex;justify-content:center;align-items: center;">
                    <img style="width: 70%;" :src="fileSrc" />
                  </div>
                </template>
                <a-card-meta>
                  <template #description>
                    <div>
                      {{ item.dir_name }}
                    </div>
                  </template>
                </a-card-meta>
              </a-card>
            </a-list-item>
          </template>
        </a-list>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, onMounted } from 'vue';
import { MenuOutlined, AppstoreOutlined, DownloadOutlined, EnvironmentOutlined } from '@ant-design/icons-vue';
import Search from './components/Search.vue';
import fileSrc from '/@/assets/media/file.svg';
import { apis } from '/@/api/custom';
import { downloadFile } from '/@/utils/common';
import router from '/@/router/index';

interface State {
  listLoading: boolean,
  list: any[],
  selectedRowKeys: string[],
  mode: 'table' | 'list',
};

const state: State = reactive({
  listLoading: false,
  list: [],
  selectedRowKeys: [],
  mode: 'table',
})

const paginationConfig = reactive({
  pageSizeOptions: ['20', '50', '100'],
  showQuickJumper: true,
  showSizeChanger: true,
  pageSize: 20,
  current: 1,
  total: 0,
  onChange: async (current: number) => {
    paginationConfig.current = current;
    await fetchList();
  },
  onShowSizeChange: async (current: number, pageSize: number) => {
    paginationConfig.pageSize = pageSize;
    await fetchList();
  }
})

const fetchList = async () => {
  state.listLoading = true;
  try {
    const res = await apis.fetchMediaFileList({ page: paginationConfig.current, page_size: paginationConfig.pageSize });
    state.list = res.data.list;
    paginationConfig.current = res.data.pagination.page;
    paginationConfig.pageSize = res.data.pagination.page_size;
    paginationConfig.total = res.data.pagination.total;
  } catch (e) {
    console.error(e);
  } finally {
    state.listLoading = false;
  }
}

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

const columns = [
  {
    title: '文件夹名称',
    dataIndex: 'dir_name',
    width: 250,
    ellipsis: true,
    sorter: (a: any, b: any) => a.dir_name.localeCompare(b.dir_name),
    slots: { customRender: 'dir_name' }
  },
  {
    title: '设备型号',
    dataIndex: 'device_name',
    width: 150,
    ellipsis: true,
  },
  {
    title: '拍摄负载',
    dataIndex: 'payload',
    width: 150,
    ellipsis: true,
  },
  {
    title: '容量大小',
    dataIndex: 'is_original',
    width: 150,
    ellipsis: true,
  },
  {
    title: '创建时间',
    dataIndex: 'create_time',
    width: 200,
    sorter: (a: any, b: any) => a.create_time.localeCompare(b.create_time),
  },
  {
    title: '航线名称',
    dataIndex: 'wayline_name',
    width: 150,
  },
  {
    title: '任务类型',
    dataIndex: 'template_type',
    width: 150,
  },
  {
    title: '创建人',
    dataIndex: 'username',
    width: 150,
  },
  {
    title: '操作',
    dataIndex: 'actions',
    fixed: 'right',
    width: 80,
    slots: { customRender: 'action' },
  },
]

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

// 点击批量下载
const onClickBatchDownload = async () => {
  console.log(state.selectedRowKeys, '点击批量下载');
}

// 点击文件夹
const onClickFile = (record: any) => {
  router.push({ path: `/media/${record.id}` })
}

// 勾选
const onSelectChange = (selectedRowKeys: string[]) => {
  state.selectedRowKeys = selectedRowKeys;
}

// 点击下载
const onClickDownload = async (record: any) => {
  state.listLoading = true;
  try {
    // const res = await downloadMediaFile(state.workspaceId, record.id);
    // if (!res) {
    //   return
    // }
    // const data = new Blob([res]);
    // downloadFile(data, record.dir_name);
  } catch (e) {
    console.error(e);
  } finally {
    state.listLoading = false;
  }
}

// 点击轨迹回放
const onClickTrajectory = () => {
  router.push({ path: '/trajectory' })
}
</script>

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

  &-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    &-right {
      display: flex;
      align-items: center;

      &-text {
        display: flex;
        align-items: center;
        margin-right: 20px;
      }
    }
  }

  .fileName {
    display: flex;
    align-items: center;
    cursor: pointer;

    img {
      width: 36px;
      height: 36px;
      margin-right: 5px;
    }
  }
}

.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;
}

.ant-card-body {
  padding: 0 10px 10px;
}
</style>