<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">
        <div class="flex items-center justify-between">
          <h2 class="text-xl font-semibold text-gray-800 flex items-center gap-2">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-indigo-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>
            短剧资产列表
          </h2>
          <div class="flex items-center gap-3">
            <el-select
              v-model="orgAccountId"
              placeholder="选择组织账户"
              clearable
              filterable
              style="width: 250px"
            >
              <el-option
                v-for="auth in orgAccounts"
                :key="auth.accountId"
                :label="`${auth.accountId} (${auth.accountType || ''})`"
                :value="auth.accountId"
              />
            </el-select>
            <el-input
              v-model="accountId"
              placeholder="推广账号ID"
              clearable
              style="width: 200px"
            />
            <el-button 
              type="primary" 
              @click="handleSync"
              :loading="syncing"
              :disabled="!orgAccountId || !accountId"
            >
              <el-icon><Refresh /></el-icon>
              同步资产
            </el-button>
          </div>
        </div>
      </div>

      <!-- 数据统计 -->
      <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
        <div class="bg-gradient-to-br from-indigo-50 to-indigo-100 rounded-lg p-4 border border-indigo-200">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm text-indigo-600 mb-1">总资产数</p>
              <p class="text-2xl font-bold text-indigo-700">{{ total }}</p>
            </div>
            <div class="p-3 bg-indigo-200 rounded-lg">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-indigo-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z" />
              </svg>
            </div>
          </div>
        </div>
        <div class="bg-gradient-to-br from-blue-50 to-blue-100 rounded-lg p-4 border border-blue-200">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm text-blue-600 mb-1">当前页数量</p>
              <p class="text-2xl font-bold text-blue-700">{{ dramaList.length }}</p>
            </div>
            <div class="p-3 bg-blue-200 rounded-lg">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-blue-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
              </svg>
            </div>
          </div>
        </div>
        <div class="bg-gradient-to-br from-green-50 to-green-100 rounded-lg p-4 border border-green-200">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm text-green-600 mb-1">总页数</p>
              <p class="text-2xl font-bold text-green-700">{{ totalPages }}</p>
            </div>
            <div class="p-3 bg-green-200 rounded-lg">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-green-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
              </svg>
            </div>
          </div>
        </div>
      </div>

      <!-- 短剧资产列表表格 -->
      <el-table
        :data="dramaList"
        style="width: 100%"
        v-loading="loading"
        stripe
        border
      >
        <el-table-column prop="marketingAssetId" label="资产ID" width="150" />
        <el-table-column prop="marketingAssetName" label="短剧名称" width="300" show-overflow-tooltip />
        <el-table-column prop="marketingAssetType" label="资产类型" width="200" />
        <el-table-column label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatTimestamp(row.createdTime) }}
          </template>
        </el-table-column>
        <el-table-column label="更新时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              link
              @click="handleViewDetail(row)"
            >
              <el-icon><View /></el-icon>
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页组件 -->
      <div class="mt-6 flex justify-end">
        <el-pagination
          v-if="total > 0"
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          style="justify-content: flex-end"
        />
      </div>
    </div>

    <!-- 短剧资产详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="短剧资产详情"
      width="700px"
    >
      <el-descriptions :column="1" border v-if="currentDrama">
        <el-descriptions-item label="资产ID">
          {{ currentDrama.marketingAssetId }}
        </el-descriptions-item>
        <el-descriptions-item label="短剧名称">
          {{ currentDrama.marketingAssetName }}
        </el-descriptions-item>
        <el-descriptions-item label="资产类型">
          {{ currentDrama.marketingAssetType }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ formatTimestamp(currentDrama.createdTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="记录创建时间">
          {{ formatDate(currentDrama.createTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="记录更新时间">
          {{ formatDate(currentDrama.updateTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="资产属性">
          <pre v-if="currentDrama.properties" style="margin: 0; white-space: pre-wrap; word-break: break-all; max-height: 400px; overflow-y: auto;">{{ formatJSON(currentDrama.properties) }}</pre>
          <span v-else>无</span>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getDramaList, syncDrama } from '@/api/drama'
import { getAuthList } from '@/api/auth'

import {
  Refresh,
  VideoPlay,
  Document,
  Files,
  View
} from '@element-plus/icons-vue'

// 数据
const loading = ref(false)
const syncing = ref(false)
const dramaList = ref([])
const detailDialogVisible = ref(false)
const currentDrama = ref(null)

// 同步参数
const orgAccountId = ref('')
const phone = ref('')
const accountId = ref('')
const orgAccounts = ref([])

// 分页数据
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 计算属性
const totalPages = computed(() => {
  return Math.ceil(total.value / pageSize.value)
})

// 方法
const loadDramaList = async () => {
  loading.value = true
  try {
    const res = await getDramaList(currentPage.value, pageSize.value)
    if (res.success) {
      dramaList.value = res.data || []
      total.value = res.total || 0
    } else {
      ElMessage.error(res.message || '加载短剧资产列表失败')
    }
  } catch (error) {
    console.error('加载短剧资产列表失败:', error)
    ElMessage.error('加载短剧资产列表失败')
  } finally {
    loading.value = false
  }
}

// 分页方法
const handleSizeChange = async (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1
  await loadDramaList()
}

const handleCurrentChange = async (newPage) => {
  currentPage.value = newPage
  await loadDramaList()
}

const handleSync = async () => {
  if (!orgAccountId.value || !accountId.value) {
    ElMessage.warning('请填写所有同步参数')
    return
  }

  try {
    await ElMessageBox.confirm(
      '确定要同步该账户下的短剧资产吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    syncing.value = true
    const res = await syncDrama(orgAccountId.value, accountId.value)
    
    if (res.success) {
      ElMessage.success(res.message || '同步成功')
      // 重新加载资产列表
      currentPage.value = 1 // 重置到第一页
      await loadDramaList()
    } else {
      ElMessage.error(res.message || '同步失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('同步短剧资产失败:', error)
      ElMessage.error('同步短剧资产失败')
    }
  } finally {
    syncing.value = false
  }
}

const handleViewDetail = (drama) => {
  currentDrama.value = drama
  detailDialogVisible.value = true
}

const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleString('zh-CN')
}

const formatTimestamp = (timestamp) => {
  if (!timestamp) return '-'
  return new Date(timestamp * 1000).toLocaleString('zh-CN')
}

const formatJSON = (jsonStr) => {
  if (!jsonStr) return ''
  try {
    return JSON.stringify(JSON.parse(jsonStr), null, 2)
  } catch {
    return jsonStr
  }
}

const loadAuthList = async () => {
  try {
    const response = await getAuthList()
    if (response.success) {
      orgAccounts.value = response.data || []
    } else {
      ElMessage.error(response.message || '加载授权列表失败')
    }
  } catch (error) {
    console.error('加载授权列表失败:', error)
    ElMessage.error('加载授权列表失败')
  }
}

// 生命周期
onMounted(async () => {
  await loadAuthList()
  loadDramaList()
})
</script>

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