<template>
  <div class="app-container">
    <!-- 顶部平台按钮区域 -->
    <div class="platform-buttons">
      <el-button
        class="authorization-btn"
        type="primary"
        @click="googleAuthorization"
      >Google</el-button>
      <el-button
        class="authorization-btn"
        type="primary"
        @click="facebookAuthorization"
      >Facebook</el-button>
      <el-button
        class="authorization-btn"
        type="primary"
        @click="tiktokAuthorization"
      >TikTok</el-button>
    </div>

    <!-- 过滤条件区域 -->
    <el-form :inline="true" class="filter-container">
<!--      <el-form-item label="平台">-->
<!--        <el-select v-model="condition.platform" clearable filterable @change="getAccountList">-->
<!--          <el-option-->
<!--            v-for="item in platformList"-->
<!--            :key="item.value"-->
<!--            :label="item.label"-->
<!--            :value="item.value"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->

<!--      <el-form-item label="账号ID">-->
<!--        <el-input v-model="condition.accountId" placeholder="请输入账号ID" clearable />-->
<!--      </el-form-item>-->

<!--      <el-form-item label="账号名称">-->
<!--        <el-input v-model="condition.accountName" placeholder="请输入账号名称" clearable />-->
<!--      </el-form-item>-->

<!--      <el-form-item>-->
<!--        <el-button type="primary" @click="getAccountList">查询</el-button>-->
<!--      </el-form-item>-->
    </el-form>

    <!-- 账户列表表格 -->
    <el-table
      v-loading="listLoading"
      element-loading-text="加载中"
      :data="tableData"
      border
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column prop="id" label="ID" width="60" align="center" />
      <el-table-column prop="actId" label="账户ID" align="center" />
      <el-table-column prop="name" label="账户名称" align="center" />
      <el-table-column prop="pkg" label="应用包名" align="center" />
<!--      <el-table-column label="授权状态" align="center">-->
<!--        <template slot-scope="scope">-->
<!--          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">-->
<!--            {{ scope.row.status === 1 ? '正常' : '异常' }}-->
<!--          </el-tag>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="操作" width="180" align="center">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="small"
            plain
            @click="editAccount(scope.row)"
          >
            修改
          </el-button>
          <el-button
            type="danger"
            size="small"
            plain
            @click="deleteAccount(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 修改账户对话框 -->
    <el-dialog
      title="修改账户"
      :visible.sync="editDialogVisible"
      width="500px"
      @close="resetEditForm"
    >
      <el-form :model="editForm" :rules="editRules" ref="editForm" label-width="100px">
        <el-form-item label="账户ID" prop="actId">
          <el-input v-model="editForm.actId" disabled></el-input>
        </el-form-item>
        <el-form-item label="账户名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入账户名称"></el-input>
        </el-form-item>
        <el-form-item label="应用包名" prop="pkg">
          <el-input v-model="editForm.pkg" placeholder="请输入应用包名"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit" :loading="editLoading">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getAccountList, deleteAccount, refreshToken, getGoogleAuthUrl, getFacebookAuthUrl, getTiktokAccountList, updateAccount, deleteTiktokAccount } from '@/api/accountManagement'

export default {
  name: 'AccountManagement',
  data() {
    return {
      // 查询条件
      condition: {
        platform: '',
        accountId: '',
        accountName: '',
        offset: 1,
        size: 10
      },
      // 平台列表
      platformList: [
        { value: 'google', label: 'Google' },
        { value: 'facebook', label: 'Facebook' },
        { value: 'tiktok', label: 'TikTok' }
      ],
      // 表格数据
      tableData: [],
      // 总记录数
      totalNum: 0,
      // 加载状态
      listLoading: false,
      // 修改对话框相关
      editDialogVisible: false,
      editLoading: false,
      editForm: {
        id: null,
        actId: '',
        name: '',
        pkg: ''
      },
      editRules: {
        name: [
          { required: true, message: '请输入账户名称', trigger: 'blur' }
        ],
        pkg: [
          { required: true, message: '请输入应用包名', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    // 判断是否为TikTok账户
    isTikTokAccount() {
      return this.tableData.some(item => item.actId || item.pkg)
    }
  },
  mounted() {
    // 初始化加载数据
    this.getAccountList()
  },
  methods: {
    // 获取账号列表
    async getAccountList() {
      this.listLoading = true
      try {
        const res = await getAccountList(this.condition)
        if (res.status === 200) {
          this.tableData = res.result.data || []
        } else {
          this.$message.error(res.message || '获取账号列表失败')
        }
      } catch (error) {
        console.error('获取账号列表异常', error)
        this.$message.error('获取账号列表失败')
      } finally {
        this.listLoading = false
      }
    },

    // 谷歌授权
    googleAuthorization() {
      // 调用后端获取授权URL，并跳转到Google授权页面
      getGoogleAuthUrl().then(res => {
        if (res.status === 200) {
          window.location.href = res.result.data.url
        } else {
          this.$message.error(res.message || 'Google授权失败')
        }
      }).catch(error => {
        console.error('Google授权异常', error)
        this.$message.error('获取Google授权链接失败')
      })
    },

    // Facebook授权
    facebookAuthorization() {
      // 调用后端获取授权URL，并跳转到Facebook授权页面
      getFacebookAuthUrl().then(res => {
        console.log("=====", JSON.stringify(res))
        if (res.status === 200) {
          window.location.href = res.result.data.authorizationUrl
        } else {
          this.$message.error(res.message || 'Facebook授权失败')
          console.error('获取授权URL失败', res)
        }
      }).catch(error => {
        console.error('Facebook授权异常', error)
        this.$message.error('获取Facebook授权链接失败')
      })
    },

    // TikTok账户列表
    tiktokAuthorization() {
      // 调用TikTok账户列表接口
      this.getTiktokAccountList()
    },

    // 获取TikTok账户列表
    async getTiktokAccountList() {
      this.listLoading = true
      try {
        const res = await getTiktokAccountList()
        if (res.status === 200) {
          this.tableData = res.result.data || []
          this.$message.success('获取TikTok账户列表成功')
        } else {
          this.$message.error(res.message || '获取TikTok账户列表失败')
        }
      } catch (error) {
        console.error('获取TikTok账户列表异常', error)
        this.$message.error('获取TikTok账户列表失败')
      } finally {
        this.listLoading = false
      }
    },

    // 刷新授权
    async refreshToken(row) {
      try {
        const res = await refreshToken({ accountId: row.accountId, platform: row.platform })
        if (res.code === 200) {
          this.$message.success('刷新授权成功')
          this.getAccountList()
        } else {
          this.$message.error(res.message || '刷新授权失败')
        }
      } catch (error) {
        console.error('刷新授权异常', error)
        this.$message.error('刷新授权失败')
      }
    },

    // 修改账户
    editAccount(row) {
      this.editForm = {
        id: row.id,
        actId: row.actId,
        name: row.name,
        pkg: row.pkg
      }
      this.editDialogVisible = true
    },

    // 提交修改
    async submitEdit() {
      this.$refs.editForm.validate(async (valid) => {
        if (valid) {
          this.editLoading = true
          try {
            const res = await updateAccount({
              id: this.editForm.id,
              name: this.editForm.name,
              pkg: this.editForm.pkg
            })
            if (res.status === 200) {
              this.$message.success('修改成功')
              this.editDialogVisible = false
              this.getTiktokAccountList()
            } else {
              this.$message.error(res.message || '修改失败')
            }
          } catch (error) {
            console.error('修改账户异常', error)
            this.$message.error('修改失败')
          } finally {
            this.editLoading = false
          }
        }
      })
    },

    // 重置修改表单
    resetEditForm() {
      this.editForm = {
        id: null,
        actId: '',
        name: '',
        pkg: ''
      }
      if (this.$refs.editForm) {
        this.$refs.editForm.resetFields()
      }
    },

    // 删除账号
    deleteAccount(row) {
      this.$confirm('确认删除该账号?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const res = await deleteTiktokAccount(row.id)
          if (res.status === 200) {
            this.$message.success('删除成功')
            this.getTiktokAccountList()
          } else {
            this.$message.error(res.message || '删除失败')
          }
        } catch (error) {
          console.error('删除账号异常', error)
          this.$message.error('删除失败')
        }
      }).catch(() => {
        // 取消删除
      })
    },

    // 根据平台类型获取标签类型
    getPlatformTagType(type) {
      switch (type) {
        case 1:
          return 'success'
        case 2:
          return 'warning'
        case 3:
          return 'info'
        default:
          return 'default'
      }
    },

    // 根据平台类型获取平台名称
    getPlatformName(type) {
      switch (type) {
        case 1:
          return 'Google'
        case 2:
          return 'TikTok'
        case 3:
          return 'Facebook'
        default:
          return '未知'
      }
    }
  }
}
</script>

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

.platform-buttons {
  margin-bottom: 20px;
}

.authorization-btn {
  margin-right: 10px;
}

.filter-container {
  margin-bottom: 20px;
}
</style>
