<template>
  <div class="youtube-auth-container">
    <!-- 未授权状态 -->
    <div v-if="!isAuthorized" class="auth-section">
      <el-alert
        title="请先完成 YouTube 频道授权"
        type="info"
        :closable="false">
      </el-alert>
      
      <div class="auth-content">
        <el-checkbox v-model="agreementChecked">
          我已阅读并同意 Google、YouTube 隐私与服务协议
        </el-checkbox>
        
        <el-button 
          type="primary" 
          @click="handleAuth"
          :disabled="!agreementChecked">
          添加频道
        </el-button>
      </div>
    </div>

    <!-- 已授权状态 -->
    <div v-else>
      <el-form :model="uploadForm" label-width="120px">
        <!-- 频道选择 -->
        <el-form-item label="选择频道">
          <el-select 
            v-model="uploadForm.channelId"
            placeholder="请选择上传频道">
            <el-option
              v-for="channel in authorizedChannels"
              :key="channel.id"
              :label="channel.name"
              :value="channel.id">
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 视频上传 -->
        <el-form-item label="上传视频">
          <el-upload
            class="video-uploader"
            drag
            action=""
            :http-request="handleVideoUpload"
            :before-upload="beforeVideoUpload"
            :show-file-list="false">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将视频拖到此处，或<em>点击上传</em>
            </div>
          </el-upload>
        </el-form-item>

        <!-- 视频信息 -->
        <el-form-item label="视频标题">
          <el-input v-model="uploadForm.title"></el-input>
        </el-form-item>

        <el-form-item label="视频描述">
          <el-input 
            type="textarea" 
            v-model="uploadForm.description"
            :rows="4">
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button 
            type="primary" 
            @click="handlePublish"
            :loading="publishing">
            发布到 YouTube
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  name: 'YouTubeAuth',
  data() {
    return {
      isAuthorized: false,
      agreementChecked: false,
      authorizedChannels: [],
      uploadForm: {
        channelId: '',
        title: '',
        description: '',
        videoFile: null
      },
      publishing: false
    }
  },
  created() {
    // 检查是否已授权
    this.checkAuthStatus()
  },
  methods: {
    // 检查授权状态
    async checkAuthStatus() {
      try {
        // 这里需要调用后端 API 检查授权状态
        const response = await this.$http.get('/api/youtube/auth-status')
        this.isAuthorized = response.data.isAuthorized
        if (this.isAuthorized) {
          this.fetchAuthorizedChannels()
        }
      } catch (error) {
        this.$message.error('检查授权状态失败')
        console.error(error)
      }
    },

    // 处理授权
    async handleAuth() {
      if (!this.agreementChecked) {
        this.$message.warning('请先同意服务协议')
        return
      }

      try {
        // 调用后端 API 获取授权 URL
        const response = await this.$http.get('/api/youtube/auth-url')
        // 打开 Google 授权页面
        window.location.href = response.data.authUrl
      } catch (error) {
        this.$message.error('获取授权链接失败')
        console.error(error)
      }
    },

    // 获取已授权频道列表
    async fetchAuthorizedChannels() {
      try {
        const response = await this.$http.get('/api/youtube/channels')
        this.authorizedChannels = response.data.channels
      } catch (error) {
        this.$message.error('获取频道列表失败')
        console.error(error)
      }
    },

    // 上传前验证
    beforeVideoUpload(file) {
      const isVideo = file.type.startsWith('video/')
      const isLt2GB = file.size / 1024 / 1024 / 1024 < 2

      if (!isVideo) {
        this.$message.error('只能上传视频文件!')
        return false
      }
      if (!isLt2GB) {
        this.$message.error('视频大小不能超过 2GB!')
        return false
      }
      return true
    },

    // 处理视频上传
    handleVideoUpload({ file }) {
      this.uploadForm.videoFile = file
    },

    // 发布视频
    async handlePublish() {
      if (!this.uploadForm.channelId) {
        this.$message.warning('请选择上传频道')
        return
      }

      if (!this.uploadForm.videoFile) {
        this.$message.warning('请选择要上传的视频')
        return
      }

      if (!this.uploadForm.title) {
        this.$message.warning('请输入视频标题')
        return
      }

      this.publishing = true

      try {
        const formData = new FormData()
        formData.append('channelId', this.uploadForm.channelId)
        formData.append('title', this.uploadForm.title)
        formData.append('description', this.uploadForm.description)
        formData.append('video', this.uploadForm.videoFile)

        await this.$http.post('/api/youtube/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })

        this.$message.success('视频上传成功')
        this.resetForm()
      } catch (error) {
        this.$message.error('视频上传失败')
        console.error(error)
      } finally {
        this.publishing = false
      }
    },

    // 重置表单
    resetForm() {
      this.uploadForm = {
        channelId: '',
        title: '',
        description: '',
        videoFile: null
      }
    }
  }
}
</script>

<style scoped>
.youtube-auth-container {
  padding: 20px;
}

.auth-section {
  max-width: 600px;
  margin: 0 auto;
}

.auth-content {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
  align-items: center;
}

.video-uploader {
  width: 100%;
}

.el-upload {
  width: 100%;
}

.el-upload-dragger {
  width: 100%;
  height: 200px;
}
</style>