<template>
  <div class="app-container">
    <div class="channel-management">
      <!-- 查询条件 -->
      <div class="filter-container">
        <!-- <div class="filter-item">
          <span class="filter-label">名称</span>
          <el-input v-model="queryParams.name" placeholder="请输入" clearable class="filter-input"></el-input>
        </div> -->
        <div class="filter-item">
          <span class="filter-label">状态</span>
          <el-select v-model="queryParams.status" placeholder="全部" clearable class="filter-input" @change="handleQuery">
            <el-option label="全部" value=""></el-option>
            <el-option label="正常" value="1"></el-option>
            <el-option label="受限" value="2"></el-option>
          </el-select>
        </div>
        <div class="filter-item">
          <span class="filter-label">开发者账号</span>
          <google-developer-selector v-model="queryParams.developerId" @change="handleQuery" class="filter-input"></google-developer-selector>
        </div>
      </div>

      <!-- 操作区 -->
      <div class="operation-container">
        <div class="operation-left">
          <el-button type="primary" class="add-button" @click="showAddChannelDialog" >添加频道</el-button>
        </div>
        <div class="operation-right">
          <el-button icon="el-icon-refresh" class="refresh-btn" @click="handleQuery">刷新</el-button>
        </div>
      </div>

      <el-table :data="tokenList" style="width: 100%" border v-loading="loading">
        <el-table-column
          prop="id"
          label="频道ID"
          width="100"
          align="center">
        </el-table-column>
        <el-table-column
          prop="picture"
          label="头像"
          width="100">
          <template slot-scope="scope">
            <img :src="scope.row.picture" alt="头像" style="width: 50px; height: 50px;">
          </template>
        </el-table-column>
        <el-table-column
          prop="name"
          label="频道名称"
          width="250"
          align="center">
        </el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
          width="250"
          align="center">
        </el-table-column>

        <el-table-column
          prop="status"
          label="状态"
          width="100"
          align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 1 || scope.row.status === '1' ? 'success' : 'warning'">
              {{ scope.row.status === 1 || scope.row.status === '1' ? '正常' : '受限' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="developerId"
          label="开发者账号"
          width="100"
          sortable
          align="center">
        </el-table-column>

        <el-table-column
          prop="create_time"
          :formatter="formatDate"
          label="添加时间"
          align="center">
        </el-table-column>
        <el-table-column
          label="操作"
          width="150"
          align="center">
          <template slot-scope="scope">
            <el-button type="text" size="small" class="operation-btn">编辑</el-button>
            <el-button type="text" size="small" class="operation-btn" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

    </div>

    <!-- 添加频道选择对话框 -->
    <el-dialog
      title="添加YouTube频道"
      :visible.sync="addChannelDialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="dialog-content">
        <el-form :model="addChannelForm" ref="addChannelForm" label-width="120px" :rules="addChannelRules">
          <el-form-item label="开发者账号" prop="developerId">
            <google-developer-selector v-model="addChannelForm.developerId"></google-developer-selector>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addChannelDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmAddChannel">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<style>
.jsoneditor-vue {
  height: 600px;
}

.el-drawer {
  width: 50% !important;
}
</style>
<script>

import {commonFetchData, getAdAccountApps, saveNewMessage,getRefreshToken} from "@/api/report";
import moment from "moment";
import axios from 'axios';
import ZxAppsSelect from '@/components/ZxAppsSelect'
import GoogleDeveloperSelector from '@/components/GoogleDeveloperSelector';
import vueJsonEditor from "vue-json-editor";
import {getGoogleTokenList,deleteYouTubeAccountById} from "../../api/report";
import {getGoogleAuthUrl} from "@/api/googleDeveloper";

export default {
  components: {vueJsonEditor, GoogleDeveloperSelector},
  data: () => ({
    alias:'',
    authCode: null,
    accessToken: null,
    refreshToken: null,
    tokenList: [],
    loading: false,
    showSuccessMessage: false,
    showErrorMessage: false,
    errorMessage: '',
    queryParams: {
      name: '',
      status: '',
      channel: '',
      uploadStatus: '',
      developerId: ''
    },
    addChannelDialogVisible: false,
    addChannelForm: {
      developerId: ''
    },
    addChannelRules: {
      developerId: [
        { required: true, message: '请选择开发者账号', trigger: 'change' }
      ]
    }
  }),
  created() {
    this.getTokenList();
  },
  mounted() {
    const urlParams = new URLSearchParams(window.location.search);
    const success = urlParams.get('success');
    const error = urlParams.get('error');
    if (success === 'true') {
      this.$message.success('授权成功!');
      this.getTokenList();
    } else if (success === 'false') {
      this.$message.error(`授权失败: ${error || '未知错误'}`);
    }
  },
  methods: {
    handleQuery() {
      this.getTokenList();
    },
    
    resetQuery() {
      this.queryParams = {
        name: '',
        status: '',
        channel: '',
        uploadStatus: '',
        developerId: ''
      };
      this.getTokenList();
    },
    
    getTokenList(){
      this.loading = true;
      getGoogleTokenList(this.queryParams).then(res => {
        this.tokenList = res.result.data;
        this.loading = false;
      }).catch(error => {
        this.loading = false;
        this.$message.error('获取频道列表失败: ' + error);
      })
    },

    formatDate(row, column, cellValue) {
      return moment(cellValue).format('YYYY-MM-DD HH:mm:ss');
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该YouTube账户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.loading = true;
          return deleteYouTubeAccountById({ id: row.id });
        })
        .then(response => {
          this.loading = false;
          if (response.status === 1) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getTokenList();
          } else {
            this.$message.error('删除失败: ' + response.msg);
          }
        })
        .catch(error => {
          this.loading = false;
          if (error === 'cancel') {
            // 用户取消操作，不提示错误
          } else {
            this.$message.error('删除失败: ' + error);
          }
        });
    },

    // 显示添加频道对话框
    showAddChannelDialog() {
      this.addChannelForm.developerId = '';
      this.addChannelDialogVisible = true;
    },

    // 确认添加频道
    confirmAddChannel() {
      this.$refs.addChannelForm.validate((valid) => {
        if (valid) {
          this.authorize(this.addChannelForm.developerId);
          this.addChannelDialogVisible = false;
        }
      });
    },

    // 使用开发者账号ID获取并跳转到Google授权页面
    async authorize(developerId) {
      if (!developerId) {
        this.$message.error("请选择开发者账号");
        return;
      }
      
      this.loading = true;
      try {
        const response = await getGoogleAuthUrl(developerId);
        if (response.status === 200 && response.result && response.result.data && response.result.data.auth_url) {
          // 跳转到Google授权页面
          window.location.href = response.result.data.auth_url;
        } else {
          this.$message.error("获取授权链接失败");
        }
      } catch (error) {
        console.error("获取授权链接失败:", error);
        this.$message.error("获取授权链接失败");
      } finally {
        this.loading = false;
      }
    },

  },
};
</script>
<style scoped>
.channel-management {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

/* 查询条件样式 */
.filter-container {
  display: flex;
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

.filter-item {
  display: flex;
  align-items: center;
  margin-right: 20px;
}

.filter-label {
  font-size: 14px;
  color: #606266;
  margin-right: 8px;
}

.filter-input {
  width: 180px;
}

/* 操作区样式 */
.operation-container {
  display: flex;
  justify-content: space-between;
  padding: 20px 0px;
  background-color: #fff;
}

.operation-left {
  display: flex;
}

.operation-left .el-button {
  margin-right: 10px;
}

.operation-right .el-button {
  font-size: 14px;
}

/* 表格样式 */
.el-table {
  margin-top: 5px;
}

.operation-btn {
  margin-right: 5px;
}
</style>
