<template>
  <a-spin :spinning="state.downloadLoading" tip="下载中...">
    <div class="mediaList">
      <Search :mode="state.mode" :selectedRowKeys="state.selectedRowKeys" :onClickDownload="onClickBatchDownload"
        :onClickSearch="onClickSearch" :onClickReset="onClickReset" />
      <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>
                {{ state.selectedRowKeys.length }}/{{ paginationConfig.total }}
              </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 }" 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="删除">
                  <DeleteOutlined style="color: #2d8cf0;" @click="onClickDelete(record)" />
                </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>
                      <a-tooltip placement="bottom" :title="item.dir_name">
                        <div class="mediaList-list-name">
                          {{ item.dir_name }}
                        </div>
                      </a-tooltip>
                    </template>
                  </a-card-meta>
                </a-card>
              </a-list-item>
            </template>
          </a-list>
        </div>
      </div>
    </div>
  </a-spin>
</template>

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

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

const state: State = reactive({
  query: undefined,
  listLoading: false,
  list: [],
  selectedRowKeys: [],
  downloadLoading: false,
  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({
      ...state.query,
      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: 'size',
    width: 150,
    ellipsis: true,
    customRender: ({ text }: any) => {
      return text > 0 ? (text / 1024 / 1024).toFixed(1) + 'M' : '--';
    }
  },
  {
    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,
    customRender: ({ text }: any) => {
      let content = '--';
      switch (text) {
        case '0':
          content = '航点航线';
          break;
        case '1':
          content = '二维正射';
          break;
        case '2':
          content = '倾斜摄影';
          break;
        case '3':
          content = '带状航线';
          break;
        default:
          break;
      }
      return content;
    }
  },
  {
    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 () => {
  state.downloadLoading = true;
  try {
    const bold = await apis.batchDownloadMediaFile({
      id: state.selectedRowKeys.join(',')
    });
    const data = new Blob([bold], { type: 'application/zip' });
    downloadFile(data, moment().format('YYYY-MM-DD HH:mm:ss'));
  } catch (e) {
    console.error(e);
  } finally {
    state.downloadLoading = false;
  }
}

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

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

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

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

// 点击下载
const onClickDownload = async (record: any) => {
  state.downloadLoading = true;
  try {
    const bold = await apis.batchDownloadMediaFile({ id: record.id });
    const data = new Blob([bold], { type: 'application/zip' });
    downloadFile(data, record.dir_name);
  } catch (e) {
    console.error(e);
  } finally {
    state.downloadLoading = false;
  }
}

// 点击删除
const onClickDelete = async (record: any) => {
  const data = {
    id: record.id
  }
  Modal.confirm({
    title: '删除文件夹',
    content: '您确认删除该文件夹吗？',
    okType: 'danger',
    onOk: async () => {
      try {
        await apis.deleteDir(data);
        message.success('删除成功');
        fetchList();
      } catch (error) {
        message.error('删除失败: ' + error);
      }
    },
  })
}
</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;
    }
  }

  &-list {
    &-name {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}

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