<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-purple-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
            </svg>
            转化归因列表
          </h2>
          <div class="flex items-center gap-3">
            <el-select
              v-model="syncOrgAccountId"
              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-input
              v-model="syncAccountId"
              placeholder="请输入广告账户ID"
              clearable
              style="width: 200px"
              @keyup.enter="handleSync"
            />
            <el-button 
              type="primary" 
              @click="handleSync"
              :loading="syncing"
              :disabled="!syncOrgAccountId || !syncAccountId"
            >
              <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-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">{{ pagination.total }}</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="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z" />
              </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">{{ conversionList.length }}</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="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
              </svg>
            </div>
          </div>
        </div>
        <div class="bg-gradient-to-br from-purple-50 to-purple-100 rounded-lg p-4 border border-purple-200">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm text-purple-600 mb-1">总页数</p>
              <p class="text-2xl font-bold text-purple-700">{{ totalPages }}</p>
            </div>
            <div class="p-3 bg-purple-200 rounded-lg">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-purple-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
              </svg>
            </div>
          </div>
        </div>
      </div>

      <!-- 转化列表表格 -->
      <el-table
        :data="conversionList"
        style="width: 100%; margin-top: 20px"
        v-loading="loading"
        stripe
      >
        <el-table-column prop="conversionId" label="转化ID" width="150" />
        <el-table-column prop="conversionName" label="转化名称" min-width="250" show-overflow-tooltip />
        <el-table-column label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </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-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="转化归因详情"
      width="600px"
    >
      <el-descriptions :column="1" border v-if="currentConversion">
        <el-descriptions-item label="转化ID">
          {{ currentConversion.conversionId }}
        </el-descriptions-item>
        <el-descriptions-item label="转化名称">
          {{ currentConversion.conversionName || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ formatDate(currentConversion.createTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="更新时间">
          {{ formatDate(currentConversion.updateTime) }}
        </el-descriptions-item>
      </el-descriptions>
      
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

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

import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh, View } from '@element-plus/icons-vue'
import { syncConversions, getConversionList, getConversionDetail } from '@/api/conversion'
import { getAuthList } from '@/api/auth'
// 响应式数据
const loading = ref(false)
const syncing = ref(false)
const syncOrgAccountId = ref('')
const syncAccountId = ref('')
const conversionList = ref([])
const detailDialogVisible = ref(false)
const currentConversion = ref(null)
const orgAccounts = ref([])


// 分页数据
const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

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

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 加载转化列表
const loadConversionList = async () => {
  loading.value = true
  try {
    const response = await getConversionList(pagination.page, pagination.pageSize)
    if (response.success) {
      conversionList.value = response.data || []
      pagination.total = response.total || 0
    } else {
      ElMessage.error(response.message || '加载转化列表失败')
    }
  } catch (error) {
    console.error('加载转化列表失败:', error)
    ElMessage.error('加载转化列表失败')
  } finally {
    loading.value = false
  }
}

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('加载授权列表失败')
  }
}

// 同步转化
const handleSync = async () => {
  if (!syncOrgAccountId.value) {
    ElMessage.warning('请输入组织账户ID')
    return
  }
  if (!syncAccountId.value) {
    ElMessage.warning('请输入广告账户ID')
    return
  }

  ElMessageBox.confirm(
    `确定要同步组织账户 ${syncOrgAccountId.value} 下的广告账户 ${syncAccountId.value} 的转化归因数据吗？`,
    '确认同步',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    syncing.value = true
    const response = await syncConversions(Number(syncOrgAccountId.value), Number(syncAccountId.value))
    syncing.value = false
    if (response.success) {
      ElMessage.success(response.message || '同步成功')
      await loadConversionList()
    } else {
      ElMessage.error(response.message || '同步失败')
    }
  })
}

// 查看详情
const handleViewDetail = async (row) => {
  try {
    const res = await getConversionDetail(row.conversionId)
    if (res.success) {
      currentConversion.value = res.data
      detailDialogVisible.value = true
    } else {
      ElMessage.error(res.message || '查询详情失败')
    }
  } catch (error) {
    console.error('查询详情失败:', error)
    ElMessage.error('查询详情失败')
  }
}

// 分页大小改变
const handleSizeChange = (newSize) => {
  pagination.pageSize = newSize
  pagination.page = 1
  loadConversionList()
}

// 当前页改变
const handleCurrentChange = (newPage) => {
  pagination.page = newPage
  loadConversionList()
}

// 页面加载时获取列表
onMounted(async () => {
  await loadAuthList()
  loadConversionList()
})
</script>

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

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stats-row {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-statistic__head) {
  font-size: 14px;
  color: #909399;
}

:deep(.el-statistic__number) {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

:deep(.success .el-statistic__number) {
  color: #67c23a;
}

:deep(.info .el-statistic__number) {
  color: #409eff;
}

:deep(.warning .el-statistic__number) {
  color: #e6a23c;
}
</style>
