<template>
  <div class="youtube-list-container">
    <!-- Filter section -->
    <div class="filter-section">
      <el-form :inline="true" :model="condition" class="filter-form">
        <el-form-item label="频道">

          <el-select class="filter-select"
                     v-model="condition.selectedAccount"
                     placeholder="请选择"
                     clearable
                     @change="fetchData">
            <el-option
              v-for="account in youtubeAccounts"
              :key="account.id"
              :label="account.name"
              :value="account.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="名称">
          <el-input
            v-model="condition.name"
            placeholder="请输入"
            class="filter-input">
          </el-input>
        </el-form-item>

        <el-form-item label="标题">
          <el-input
            v-model="condition.title"
            placeholder="请输入"
            class="filter-input">
          </el-input>
        </el-form-item>

        <el-form-item label="上传状态">
          <el-select
            v-model="condition.status"
            placeholder="请选择"
            class="filter-select"
            @change="fetchData">
            <el-option label="全部" value=""></el-option>
            <el-option label="成功" value="SUCCESS"></el-option>
            <el-option label="失败" value="FAILED"></el-option>
          </el-select>
        </el-form-item>

<!--        <el-form-item label="限制">-->
<!--          <el-select-->
<!--            v-model="condition.restriction"-->
<!--            placeholder="请选择"-->
<!--            class="filter-select">-->
<!--            <el-option label="全部" value=""></el-option>-->
<!--            <el-option label="无限制" value="none"></el-option>-->
<!--            <el-option label="有限制" value="restricted"></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->

<!--        <el-form-item label="播放列表">-->
<!--          <el-select-->
<!--            v-model="condition.playlist"-->
<!--            placeholder="请选择"-->
<!--            class="filter-select">-->
<!--            <el-option label="全部" value=""></el-option>-->
<!--            <el-option label="列表1" value="list1"></el-option>-->
<!--            <el-option label="列表2" value="list2"></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
      </el-form>
    </div>
    <el-divider></el-divider>
    <!-- table Header actions -->
    <div class="header-actions">
      <el-button type="primary" @click="goToUpload">上传</el-button>
      <el-dropdown>
        <el-button>
          批量操作<i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="batchRetry">批量重试</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>

      <div class="header-right">
        <el-button icon="el-icon-refresh" @click="fetchData">刷新</el-button>
<!--        <el-button icon="el-icon-back">导出</el-button>-->
<!--        <el-button icon="el-icon-user">登出</el-button>-->
      </div>
    </div>
    <!-- Main table -->
    <el-table
      :data="tableData"
      border
      style="width: 100%"
      :row-class-name="tableRowClassName"
      v-loading="dataLoading"
      @selection-change="handleSelectionChange">
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column
        prop="id"
        label="ID"
        width="50">
      </el-table-column>
      <el-table-column
        label="缩略图"
        width="100">
        <template slot-scope="scope">
          <img :src="`${scope.row.ossUrl}?x-oss-process=video/snapshot,t_1000,scaletype_fill`" class="video-thumbnail" />
        </template>
      </el-table-column>
      <el-table-column
        prop="title"
        label="标题"
        width="180">
      </el-table-column>
      <el-table-column
        prop="youtubeAccountName"
        label="频道"
        width="120">
      </el-table-column>
      <el-table-column
        prop="videoId"
        label="视频ID"
        width="150">
      </el-table-column>
      <el-table-column
        prop="videoUrl"
        label="视频播放地址">
        <template slot-scope="scope">
          <el-link type="primary" :href="`https://www.youtube.com/watch?v=${scope.row.videoId}`" target="_blank">
            https://www.youtube.com/watch?v={{ scope.row.videoId }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column prop="materialBusinessId" label="Local ID" width="120"></el-table-column>
      <el-table-column
        prop="status"
        label="状态"
        width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.uploadStatus === 'SUCCESS' ? 'success' : 'danger'">
            {{ scope.row.uploadStatus === 'SUCCESS' ? '成功' : '失败' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column
        prop="name"
        label="名称"
        width="250">
      </el-table-column>
<!--      <el-table-column-->
<!--        prop="contentRating"-->
<!--        label="内容是否面向儿童"-->
<!--        width="150">-->
<!--      </el-table-column>-->
<!--      <el-table-column-->
<!--        prop="viewCount"-->
<!--        label="观看次数"-->
<!--        width="100">-->
<!--      </el-table-column>-->
      <el-table-column
        prop="uploadEndTime"
        label="上传时间"
        align="center"
        width="180">
        <template slot-scope="scope">
          {{ scope.row.uploadEndTime ? scope.row.uploadEndTime.substring(0, 10) : '' }}
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="120">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.uploadStatus === 'FAILED'"
            size="mini"
            type="primary"
            :loading="scope.row.retryStatus === 'running'"
            :disabled="scope.row.retryStatus === 'running' || scope.row.retryStatus === 'complete'"
            @click="retryUploadYoutube(scope.row)">
            重新上传
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        :total="total"
        layout="total, prev, pager, next, sizes"
        >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import {
  getYoutubeAccountList,
  getVideoLog,
  getVideoLogCount,
  retryUploadYoutube } from '@/api/report';
export default {
  name: 'YouTubeList',
  data() {
    return {
      dataLoading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      condition: {
        channel: '',
        name: '',
        format: '',
        status: '',
        restriction: '',
        playlist: '',
        selectedAccount: ''
      },
      tableData: [],
      youtubeAccounts: [],
    }
  },
  created() {
    this.fetchYoutubeAccounts();
    this.fetchData();
  },

  methods: {
    goToUpload() {
      window.open('/tools/uploadYoutube');
    },
    async retryUploadYoutube(row) {
      this.$set(row, 'retryStatus', "running");
      try {
        const response = await retryUploadYoutube({
          id: row.id
        });

        if (response.status === 200) {
          this.$message.success('提交成功');
          this.$set(row, 'retryStatus', "complete");
        } else {
          this.$message.error('提交失败');
          this.$set(row, 'retryStatus', "default");
        }
      } catch (error) {
        this.$message.error('提交失败');
        this.$set(row, 'retryStatus', "default");
      } finally {
      }
    },
    tableRowClassName({ rowIndex }) {
      if (rowIndex % 2 === 1) {
        return 'blue-row'
      }
      return ''
    },
    handleSelectionChange(selection) {
      console.log('Selected rows:', selection)
    },
    fetchData() {
      this.dataLoading=true
      Promise.all([
        getVideoLog({page: this.currentPage - 1, size: this.pageSize, status: this.condition.status, youtube_account_id: this.condition.selectedAccount}),
        getVideoLogCount({status: this.condition.status, youtube_account_id: this.condition.selectedAccount})
      ])
        .then(([logResponse, countResponse]) => {
          if (logResponse.status === 200) {
            this.tableData = logResponse.result.data;
          } else {
            this.$message.error('获取上传日志列表失败');
          }

          if (countResponse.status === 200) {
            this.total = countResponse.result.data;
          } else {
            this.$message.error('获取上传日志总数失败');
          }
        })
        .catch(error => {
          console.error('Error fetching data:', error);
          this.$message.error('获取数据失败');
        }).finally(() => {
          this.dataLoading = false
      });
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchData();
    },

    fetchYoutubeAccounts() {
      getYoutubeAccountList()
        .then(response => {
          if (response.status === 200) {
            this.youtubeAccounts = response.result.data;
          } else {
            this.$message.error('获取YouTube账户列表失败');
          }
        })
        .catch(error => {
          console.error('Error fetching YouTube accounts:', error);
          this.$message.error('获取YouTube账户列表失败');
        });
    },
  },
  watch: {
    condition: {
      handler(newVal) {
        console.log('Filter changed:', newVal)
        // Implement your filter logic here
      },
      deep: true
    }
  }
}
</script>

<style>
.youtube-list-container {
  padding: 20px;
  background-color: #fff;
}

.header-actions {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  gap: 10px;
}

.header-right {
  margin-left: auto;
  display: flex;
  gap: 10px;
}

.filter-section {
  /*margin-bottom: 20px;*/
  /*padding: 16px;*/
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.filter-select {
  width: 180px;
}

.filter-input {
  width: 180px;
}

.video-thumbnail {
  width: 60px;
  height: 45px;
  object-fit: cover;
  border-radius: 2px;
}

.blue-row {
  background-color: #f0f7ff !important;
}

/* Element UI overrides */
.el-form--inline .el-form-item {
  margin-right: 10px;
  margin-bottom: 10px;
}

.el-table th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: normal;
  padding: 8px 0;
}

.el-table td {
  padding: 8px 0;
}

.el-table--enable-row-hover .el-table__body tr:hover > td {
  background-color: #f5f7fa;
}

.el-button--primary {
  background-color: #1890ff;
  border-color: #1890ff;
}

.el-button--primary:hover,
.el-button--primary:focus {
  background-color: #40a9ff;
  border-color: #40a9ff;
}

.el-link {
  color: #1890ff;
}

.el-link:hover {
  color: #40a9ff;
}

.el-select .el-input__inner,
.el-input__inner {
  border-radius: 2px;
}

/* Previous styles remain the same, add pagination styles */
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  padding: 10px 0;
}

/* Customize Element UI pagination to match the design */
.el-pagination {
  font-weight: normal;
}

.el-pagination .el-select .el-input {
  width: 110px;
}

.el-pagination .el-select .el-input__inner {
  padding-right: 25px;
}

.el-pagination .btn-prev,
.el-pagination .btn-next {
  background: transparent;
}

.el-pagination .el-pager li {
  background: transparent;
  border: none;
}

.el-pagination .el-pager li.active {
  color: #1890ff;
  background-color: #e6f7ff;
  border-radius: 2px;
}

.el-pagination__total {
  margin-right: 10px;
}

.el-pagination__sizes {
  margin-left: 10px;
}
</style>
