<template>
  <div class="space-y-6">
    <!-- 主卡片 -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
      <div class="border-b border-gray-200 pb-4 mb-6">
        <h1 class="text-2xl font-bold text-gray-800 flex items-center gap-3">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-7 w-7 text-purple-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 4v16M17 4v16M3 8h4m10 0h4M3 12h18M3 16h4m10 0h4M4 20h16a1 1 0 001-1V5a1 1 0 00-1-1H4a1 1 0 00-1 1v14a1 1 0 001 1z" />
          </svg>
          广告组数据同步与查询
        </h1>
      </div>

      <!-- 同步功能区 -->
      <div class="sync-section">
        <h3>数据同步</h3>
        <el-form :model="syncForm" inline label-width="120px">
          <el-form-item label="授权账号">
            <el-select
              v-model="syncForm.orgAccountId"
              placeholder="选择组织账户"
              clearable
              filterable
              style="width: 250px"
              @change="handleOrgAccountChange"
            >
              <el-option
                v-for="auth in orgAccounts"
                :key="auth.accountId"
                :label="`${auth.accountId} (${auth.accountType || ''})`"
                :value="auth.accountId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="账户ID">
            <el-input 
              v-model="syncForm.accountId" 
              placeholder="请输入账户ID，例如：66612379"
              style="width: 300px"
            />
          </el-form-item>
          
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="syncForm.timeRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="x"
              style="width: 400px"
            />
          </el-form-item>
          
          <el-form-item>
            <el-button 
              type="primary" 
              :loading="syncing" 
              @click="handleSync"
            >
              开始同步
            </el-button>
            <el-button @click="resetSyncForm">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-divider />

      <!-- 查询功能区 -->
      <div class="query-section">
        <h3>广告组列表</h3>
        <el-form :model="queryForm" inline>
          <el-form-item label="账户ID">
            <el-input 
              v-model="queryForm.accountId" 
              placeholder="请输入账户ID（可选）"
              style="width: 200px"
              clearable
            />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
            <el-button icon="Refresh" @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>

        <!-- 数据表格 -->
        <el-table 
          :data="tableData" 
          style="width: 100%; margin-top: 20px"
          v-loading="loading"
          border
        >
          <el-table-column prop="adgroupId" label="广告组ID" width="150" />
          <el-table-column prop="adgroupName" label="广告组名称" width="200" />
          <el-table-column prop="accountId" label="账户ID" width="120" />
          <el-table-column prop="configuredStatus" label="配置状态" width="120" />
          <el-table-column prop="dailyBudget" label="日预算（分）" width="120" />
          <el-table-column prop="marketingGoal" label="营销目标" width="120" />
          <el-table-column prop="optimizationGoal" label="优化目标" width="120" />
          <el-table-column prop="bidMode" label="出价模式" width="120" />
          <el-table-column prop="beginDate" label="开始日期" width="110" />
          <el-table-column prop="endDate" label="结束日期" width="110" />
          <el-table-column prop="marketingScene" label="营销场景" width="150" />
          <el-table-column prop="createdTime" label="创建时间" width="110">
            <template #default="{ row }">
              {{ formatTimestamp(row.createdTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="lastModifiedTime" label="最后修改时间" width="160">
            <template #default="{ row }">
              {{ formatTimestamp(row.lastModifiedTime) }}
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="mt-6 flex justify-end">
          <el-pagination
            v-model:current-page="queryForm.page"
            v-model:page-size="queryForm.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
defineOptions({
  name: 'Adgroup'
})

import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import { getAuthList } from '@/api/auth'

// 同步表单
const syncForm = reactive({
  orgAccountId: '',
  accountId: '',
  timeRange: []
})

// 查询表单
const queryForm = reactive({
  accountId: '',
  page: 1,
  pageSize: 20
})

const orgAccounts = ref([])

// 状态
const syncing = ref(false)
const loading = ref(false)
const tableData = ref([])
const total = ref(0)

// 方法
const loadOrgAccounts = async () => {
  try {
    const res = await getAuthList()
    console.log('组织账户列表:', res)
    if (res.success) {
      orgAccounts.value = res.data || []
    }
  } catch (error) {
    console.error('加载组织账户失败:', error)
    ElMessage.error('加载组织账户失败')
  }
}


// 同步数据
const handleSync = async () => {
  if (!syncForm.accountId) {
    ElMessage.warning('请输入账户ID')
    return
  }

  syncing.value = true
  
  const params = {
    orgAccountId: syncForm.orgAccountId,
    accountId: syncForm.accountId
  }
  
  // 如果选择了时间范围
  if (syncForm.timeRange && syncForm.timeRange.length === 2) {
    params.startTime = Math.floor(syncForm.timeRange[0] / 1000) // 转为秒
    params.endTime = Math.floor(syncForm.timeRange[1] / 1000)
  }

  try {
    const res = await request.post('/adgroups/sync', null, { params })
    if (res.success) {
      ElMessage.success(res.message || '同步成功')
      // 同步成功后刷新列表
      queryForm.accountId = syncForm.accountId
      await handleQuery()
    } else {
      ElMessage.error(res.message || '同步失败')
    }
  } catch (error) {
    ElMessage.error('同步失败：' + (error.message || '未知错误'))
  } finally {
    syncing.value = false
  }
}

// 重置同步表单
const resetSyncForm = () => {
  syncForm.accountId = '66612379'
  syncForm.timeRange = []
}

// 查询数据
const handleQuery = async () => {
  loading.value = true
  
  const params = {
    page: queryForm.page,
    pageSize: queryForm.pageSize
  }
  
  if (queryForm.accountId) {
    params.accountId = queryForm.accountId
  }

  try {
    const res = await request.get('/adgroups/list', { params })
    if (res.success) {
      tableData.value = res.data || []
      total.value = res.total || 0
    } else {
      ElMessage.error(res.message || '查询失败')
    }
  } catch (error) {
    ElMessage.error('查询失败：' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 重置查询
const handleReset = () => {
  queryForm.accountId = ''
  queryForm.page = 1
  queryForm.pageSize = 20
  handleQuery()
}

// 分页大小改变
const handleSizeChange = () => {
  handleQuery()
}

// 页码改变
const handleCurrentChange = () => {
  handleQuery()
}

// 格式化时间戳
const formatTimestamp = (timestamp) => {
  if (!timestamp) return '-'
  const date = new Date(timestamp * 1000)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 组件挂载时查询数据
onMounted(async () => {
  await loadOrgAccounts()
  handleQuery()
})
</script>

<style scoped>
/* 使用Tailwind CSS类替代自定义样式 */
</style>
