<template>
  <div class="upload-form-container">
    <!-- YouTube账户选择 -->
    <div class="form-section">
      <div class="section-label">YouTube账户</div>
      <el-select
        v-model="form.youtubeAccountId"
        placeholder="请选择账户"
        @change="handleAccountChange"
        style="width: 300px">
        <el-option
          v-for="account in youtubeAccounts"
          :key="account.id"
          :label="account.name"
          :value="account.id">
        </el-option>
      </el-select>
    </div>

    <!-- Video section -->
    <div class="form-section">
      <div class="section-label">视频</div>
      <div class="button-group">
        <el-button type="default" icon="el-icon-plus" @click="openMaterialDialog">添加素材</el-button>
        <el-button type="default" @click="handleClearList">清空</el-button>
      </div>

      <!-- Video table -->
      <el-table
        :data="videoList"
        style="width: 100%"
        border
        :row-class-name="tableRowClassName">
        <el-table-column
          label="缩略图"
          width="80">
          <template slot-scope="scope">
            <img :src="`${scope.row.url}?x-oss-process=video/snapshot,t_1000,scaletype_fill`" class="video-thumbnail" />
          </template>
        </el-table-column>
        <el-table-column
          prop="materialName"
          label="名称"
          >
        </el-table-column>
        <el-table-column
          label="标题"
          >
          <template slot-scope="scope">
            <div class="title-input-container">
              <el-input
                :value="scope.row.title"
                size="small"
                :maxlength="100"
                @input="(value) => handleTitleInput(scope.row, value)"
                placeholder="请输入标题">
              </el-input>
              <span class="char-count">{{ scope.row.titleLength || 0 }}/100</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="200"
          align="center">
          <template slot-scope="scope">
            <el-button type="text" class="delete-button" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- Content settings -->
    <div class="form-section">
      <div class="section-label">设置</div>
      <el-form :model="form" label-position="top">
        <!-- Content for children -->
        <div class="radio-group-container">
          <el-radio-group v-model="form.forChildren">
            <el-radio :label="true">内容是面向儿童</el-radio>
            <el-radio :label="false">内容不是面向儿童</el-radio>
          </el-radio-group>
        </div>

        <!-- Category -->
        <div class="form-item-container">
          <div class="section-label">类别</div>
          <category-selector v-model="form.category"></category-selector>
        </div>

        <!-- Playlist -->
        <!-- <div class="form-item-container">
          <div class="section-label">播放列表</div>
          <div class="playlist-container">
            <el-select v-model="form.playlist" placeholder="请选择播放列表" style="width: 300px">
              <el-option
                v-for="playlist in playlists"
                :key="playlist.id"
                :label="playlist.snippet.title"
                :value="playlist.id"
              ></el-option>
            </el-select>
            <el-button type="primary" :disabled="true">创建播放列表</el-button>
          </div>
        </div> -->

        <!-- Privacy -->
        <div class="form-item-container">
          <div class="section-label">公开范围</div>
          <el-select v-model="form.visibility" placeholder="请选择公开范围" style="width: 300px">
            <el-option
              v-for="item in visibilityOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </div>

        <!-- Description -->
        <div class="form-item-container">
          <div class="section-label">说明</div>
          <el-input
            type="textarea"
            :value="form.description"
            :maxlength="5000"
            :rows="6"
            placeholder="请输入视频说明"
            resize="none"
            @input="handleDescriptionInput">
          </el-input>
          <div class="char-count">{{ descriptionLength }}/5000</div>
        </div>
      </el-form>
    </div>

    <!-- Action buttons -->
    <div class="form-actions">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handlePublish">发布</el-button>
    </div>

    <!-- Material Dialog -->
    <el-dialog title="选择素材" :visible.sync="materialDialogVisible" width="70%" @close="fetchTotalVideoNumber">
      <el-table :data="materialTableData" style="width: 100%" @selection-change="handleMaterialSelectionChange" ref="materialTable" height="400">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="预览" width="180">
          <template slot-scope="scope">
            <video style="width: 100px; height: 56px" controls>
              <source :src="scope.row.url" type="video/mp4">
              Your browser does not support the video tag.
            </video>
          </template>
        </el-table-column>
        <el-table-column prop="materialName" label="名称"></el-table-column>
        <el-table-column prop="datadate" label="日期"></el-table-column>
      </el-table>
      <div style="margin-top: 20px;">
        <el-pagination
          @size-change="handleMaterialPageSizeChange"
          @current-change="handleMaterialPageCurrentChange"
          :current-page="materialCurrentPage"
          :page-sizes="[5, 10, 20]"
          :page-size="materialPageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalVideoNumber">
        </el-pagination>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleMaterialCancel">取 消</el-button>
        <el-button type="primary" @click="confirmMaterialSelection">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getYoutubeAccountList, getVideo, getTotalVideoNumber, getListMyPlaylists, uploadFromOss } from '@/api/report';
import CategorySelector from './components/CategorySelector.vue';

export default {
  name: 'YouTubeUploadForm',
  components: {
    CategorySelector
  },
  data() {
    return {
      materialDialogVisible: false,
      materialTableData: [],
      selectedMaterials: [],
      materialCurrentPage: 1,
      materialPageSize: 5,
      totalVideoNumber: 0,
      youtubeAccounts: [],
      playlists: [],
      visibilityOptions: [
      { label: '不公开', value: 'unlisted' },
        { label: '公开', value: 'public' },
        { label: '私有', value: 'private' },
        
      ],
      descriptionLength: 0,
      form: {
        youtubeAccountId: '',
        forChildren: true,
        category: '1',
        playlist: null,
        description: '',
        privacy: 'unlisted',
        visibility: 'unlisted'
      },
      videoList: [
      ]
    }
  },
  created() {
    this.getYoutubeAccounts();
    this.fetchTotalVideoNumber();
  },
  methods: {
    // 获取YouTube账户列表
    async getYoutubeAccounts() {
      try {
        const response = await getYoutubeAccountList();
        if (response.status === 200) {
          this.youtubeAccounts = response.result.data;
          // 自动选择第一个账户
          if (this.youtubeAccounts.length > 0) {
            this.form.youtubeAccountId = this.youtubeAccounts[0].id;
            // this.fetchPlaylists();
          }
        } else {
          this.$message.error('获取YouTube账户列表失败');
        }
      } catch (error) {
        console.error('获取YouTube账户列表错误:', error);
        this.$message.error('获取YouTube账户列表失败');
      }
    },

    handleAccountChange(accountId) {
      this.form.youtubeAccountId = accountId;
      // this.fetchPlaylists();
    },

    openMaterialDialog() {
      this.materialDialogVisible = true;
      this.fetchMaterials();
    },

    fetchMaterials() {
      getVideo({ page: this.materialCurrentPage - 1, size: this.materialPageSize })
        .then(response => {
          if (response.status === 200) {
            this.materialTableData = response.result.data;
            this.$nextTick(() => {
              const selectedVideoIds = this.videoList.map(video => video.id);
              this.materialTableData.forEach(row => {
                if (selectedVideoIds.includes(row.id)) {
                  this.$refs.materialTable.toggleRowSelection(row, true);
                }
              });
            });
          } else {
            this.$message.error('获取素材列表失败');
          }
        })
        .catch(error => {
          console.error('Error fetching materials:', error);
          this.$message.error('获取素材列表失败');
        });
    },

    handleMaterialSelectionChange(val) {
      this.selectedMaterials = val;
    },

    handleMaterialCancel() {
      this.materialDialogVisible = false;
      this.selectedMaterials = [];
      this.$refs.materialTable.clearSelection();
    },

    handleTitleInput(row, value) {
      // 直接使用输入的值
      const title = value || '';
      // 更新标题
      this.$set(row, 'title', title);
      // 更新字数统计
      this.$set(row, 'titleLength', title.length);
    },

    confirmMaterialSelection() {
      if (this.selectedMaterials.length === 0) {
        this.$message.warning('请选择要添加的素材');
        return;
      }

      this.selectedMaterials.forEach(newVideo => {
        const isDuplicate = this.videoList.some(existingVideo => existingVideo.id === newVideo.id);
        if (!isDuplicate) {
          const title = newVideo.materialName;
          this.videoList.push({
            ...newVideo,
            materialName: newVideo.materialName,
            title,
            progress: '0',
            thumbnail: newVideo.url,
            titleLength: title.length
          });
        }
      });

      this.$message.success('添加素材成功');
      this.materialDialogVisible = false;
      this.selectedMaterials = [];
      this.$refs.materialTable.clearSelection();
    },

    handleMaterialPageSizeChange(val) {
      this.materialPageSize = val;
      this.fetchMaterials();
    },

    handleMaterialPageCurrentChange(val) {
      this.materialCurrentPage = val;
      this.fetchMaterials();
    },

    fetchTotalVideoNumber() {
      getTotalVideoNumber()
        .then(response => {
          if (response.status === 200) {
            this.totalVideoNumber = response.result.data;
          } else {
            this.$message.error('获取视频总数失败');
          }
        })
        .catch(error => {
          console.error('Error fetching total video number:', error);
          this.$message.error('获取视频总数失败');
        });
    },

    handleDelete(index, row) {
      this.$confirm('确定要删除这个视频吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.videoList.splice(index, 1);
        this.$message.success('删除成功');
      }).catch(() => {
        // 取消删除，不做任何处理
      });
    },

    handleClearList() {
      if (this.videoList.length === 0) {
        return;
      }

      this.$confirm('确定要清空当前列表吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.videoList = [];
        this.$message.success('列表已清空');
      }).catch(() => {
        // 取消操作，不需要做任何处理
      });
    },



    fetchPlaylists() {
      if (!this.form.youtubeAccountId) {
        this.playlists = [];
        return;
      }
      getListMyPlaylists({ youTubeAccountId: this.form.youtubeAccountId })
        .then(response => {
          if (response.status === 200) {
            this.playlists = response.result.data;
          } else {
            this.$message.error('获取YouTube播放列表失败');
          }
        })
        .catch(error => {
          console.error('Error fetching YouTube playlists:', error);
          this.$message.error('获取YouTube播放列表失败');
        });
    },

    handlePublish() {
      if (this.videoList.length === 0) {
        this.$message.warning('请选择要上传的视频');
        return;
      }

      // 构建 videoInfos 数组
      const videoInfos = this.videoList.map(video => ({
        id: video.id,
        title: video.title
      }));

      // 构建 UploadRequest 对象
      const uploadRequest = {
        videoInfos: videoInfos,
        youTubeAccountId: this.form.youtubeAccountId,
        description: this.form.description,
        tags: this.form.tags,
        categoryId: this.form.category,
        privacyStatus: this.form.visibility,
        playlistId: this.form.playlist
      };

      // 发送上传请求
      uploadFromOss(uploadRequest)
        .then(response => {
          if (response.status === 200) {
            this.$message.success('开始上传视频');
            // 清空视频列表
            this.videoList = [];
            // 跳转到视频管理页面
            this.$router.push('/tools/YoutubeVideoManage');
          } else {
            this.$message.error('上传视频失败: ' + response.message);
          }
        })
        .catch(error => {
          this.$message.error('上传视频失败');
          console.error(error);
        });
    },

    handleDescriptionInput(value) {
      const description = value || '';
      this.form.description = description;
      this.descriptionLength = description.length;
    },

    handleCancel() {
      this.$router.push('/tools/YoutubeVideoManage');
    },

    tableRowClassName({ rowIndex }) {
      if (rowIndex % 2 === 1) {
        return 'blue-row'
      }
      return ''
    }
  }
}
</script>

<style>
.upload-form-container {
  padding: 20px;
  /* max-width: 1200px; */
  margin: 0 auto;
  background-color: #fff;
}

.form-section {
  margin-bottom: 24px;
}

.section-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
  font-weight: bold;
}

.button-group {
  margin-bottom: 16px;
  display: flex;
  gap: 8px;
}

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

.operation-cell {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.progress-text {
  color: #909399;
}

.delete-button {
  color: #409EFF;
}

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

.form-item-container {
  margin-bottom: 20px;
}

.radio-group-container {
  margin-bottom: 20px;
}

.playlist-container {
  display: flex;
  gap: 16px;
  align-items: flex-start;
}

.privacy-container {
  margin-bottom: 16px;
}

.privacy-sub-option {
  margin-top: 8px;
  margin-left: 24px;
}

.char-count {
  text-align: right;
  color: #909399;
  font-size: 12px;
  margin-top: 4px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #EBEEF5;
}

/* Element UI overrides */
.el-table th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: normal;
}

.el-radio {
  margin-right: 30px;
  margin-bottom: 12px;
}

.el-radio__label {
  font-weight: normal;
}

.el-textarea__inner {
  font-family: inherit;
}

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

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

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

.title-input-container {
  display: flex;
  align-items: center;
  gap: 8px;
}

.char-count {
  color: #909399;
  font-size: 12px;
  white-space: nowrap;
}
</style>
