<template>
  <div class="space-y-6">
    <!-- 返回按钮 -->
    <div>
      <el-button @click="goBack">
        <el-icon><ArrowLeft /></el-icon>
        返回
      </el-button>
    </div>

    <!-- 配置信息卡片 -->
    <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 flex items-center justify-between">
        <h2 class="text-xl font-semibold text-gray-800 flex items-center gap-2">
          <el-icon><Document /></el-icon>
          配置信息
        </h2>
        <el-button type="primary" @click="handleRefresh(confDetail.id)">
            <el-icon><Refresh /></el-icon>
            刷新计划状态</el-button>
      </div>
      
      <div v-if="confDetail">
        <!-- 主要信息：名称和状态 -->
        <div class="flex items-center gap-6 mb-4">
          <div class="flex-1">
            <div class="text-sm text-gray-500 mb-1">计划名称</div>
            <div class="text-lg font-semibold">{{ confDetail.name }}</div>
          </div>
          <div>
            <div class="text-sm text-gray-500 mb-1">状态</div>
            <el-tag :type="getPlanStatusColor(confDetail.status)" size="large">
              {{ getPlanStatusText(confDetail.status) }}
            </el-tag>
          </div>
        </div>

        <!-- 折叠面板：详细信息 -->
        <el-collapse v-model="activeCollapse" class="mt-4">
          <el-collapse-item title="详细配置信息" name="detail">
            <div class="grid grid-cols-2 gap-6 p-4">
              <div class="space-y-2">
                <div class="text-sm text-gray-500">配置ID</div>
                <div class="text-base font-medium">{{ confDetail.id }}</div>
              </div>
              <div class="space-y-2">
                <div class="text-sm text-gray-500">广告类型</div>
                <el-tag :type="getAdTypeColor(confDetail.adType)">
                  {{ getAdTypeText(confDetail.adType) }}
                </el-tag>
              </div>
              <div class="space-y-2">
                <div class="text-sm text-gray-500">出价金额</div>
                <div class="text-base font-medium">¥{{ (confDetail.bidAmount / 100).toFixed(2) }}</div>
              </div>
              <div class="space-y-2">
                <div class="text-sm text-gray-500">账号组ID</div>
                <div class="text-base font-medium">{{ confDetail.accountGroupId }}</div>
              </div>
              <div class="space-y-2">
                <div class="text-sm text-gray-500">转化ID</div>
                <div class="text-base font-medium">{{ confDetail.conversionId }}</div>
              </div>
              <div class="space-y-2">
                <div class="text-sm text-gray-500">定向模版</div>
                <div class="text-base font-medium">{{ confDetail.targets || '-' }}</div>
              </div>
              <div class="space-y-2">
                <div class="text-sm text-gray-500">版位模版</div>
                <div class="text-base font-medium">{{ confDetail.sites || '-' }}</div>
              </div>
              <div class="space-y-2" v-if="confDetail.adType === 1">
                <div class="text-sm text-gray-500">企微主体ID</div>
                <div class="text-base font-medium">{{ confDetail.wxCorpid || '-' }}</div>
              </div>
              <div class="space-y-2" v-if="confDetail.adType === 2">
                <div class="text-sm text-gray-500">短剧ID</div>
                <div class="text-base font-medium">{{ confDetail.dramaId || '-' }}</div>
              </div>
              <div class="space-y-2">
                <div class="text-sm text-gray-500">图片IDs</div>
                <div class="text-base font-medium">{{ confDetail.imageIds || '-' }}</div>
              </div>
              <div class="space-y-2">
                <div class="text-sm text-gray-500">落地页IDs</div>
                <div class="text-base font-medium">{{ confDetail.pageIds || '-' }}</div>
              </div>
              <div class="space-y-2">
                <div class="text-sm text-gray-500">创意图片/视频</div>
                <div class="text-base font-medium">
                  <div v-if="confDetail.creativeFileUrls" class="flex flex-wrap gap-2">
                    <el-image
                      v-for="(url, index) in confDetail.creativeFileUrls.split(',')"
                      :key="index"
                      :src="url"
                      :preview-src-list="confDetail.creativeFileUrls.split(',')"
                      :initial-index="index"
                      fit="cover"
                      style="width: 80px; height: 80px"
                      class="cursor-pointer rounded border"
                    />
                  </div>
                  <span v-else>-</span>
                </div>
              </div>
              <div class="space-y-2">
                <div class="text-sm text-gray-500">品牌形象图片</div>
                <div class="text-base font-medium">
                  <el-image
                    v-if="confDetail.brandImageUrl"
                    :src="confDetail.brandImageUrl"
                    :preview-src-list="[confDetail.brandImageUrl]"
                    fit="cover"
                    style="width: 120px; height: 120px"
                    class="cursor-pointer rounded border"
                  />
                  <span v-else>-</span>
                </div>
              </div>
              <div class="space-y-2">
                <div class="text-sm text-gray-500">创意文案</div>
                <div class="text-base font-medium whitespace-pre-wrap">{{ confDetail.creativeText || '-' }}</div>
              </div>
              <div class="space-y-2">
                <div class="text-sm text-gray-500">品牌名称</div>
                <div class="text-base font-medium">{{ confDetail.brandName || '-' }}</div>
              </div>
              <div class="space-y-2">
                <div class="text-sm text-gray-500">按钮文案</div>
                <div class="text-base font-medium">{{ confDetail.buttonText || '-' }}</div>
              </div>
              <div class="space-y-2">
                <div class="text-sm text-gray-500">失败原因</div>
                <div class="text-base text-red-500">{{ confDetail.failReason }}</div>
              </div>
              <div class="space-y-2">
                <div class="text-sm text-gray-500">创建时间</div>
                <div class="text-base font-medium">{{ formatDate(confDetail.createTime) }}</div>
              </div>
              <div class="space-y-2">
                <div class="text-sm text-gray-500">更新时间</div>
                <div class="text-base font-medium">{{ formatDate(confDetail.updateTime) }}</div>
              </div>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
      
      <div v-else v-loading="confLoading" style="min-height: 200px"></div>
    </div>

    <!-- 广告计划列表卡片 -->
    <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">
          <el-icon><List /></el-icon>
          广告计划列表
        </h2>
        <div>
           <el-button type="primary" @click="handleRefresh(confDetail.id)">
            <el-icon><Refresh /></el-icon>
            刷新计划状态</el-button>
        <el-button type="primary" @click="handleReGeneratePlan(confDetail.id)">
          <el-icon><Refresh /></el-icon>
          重新生成广告/创意</el-button>
        </div>
        </div>
        
      </div>

      <!-- 筛选条件 -->
      <div class="mb-4 flex gap-4">
        <el-select 
          v-model="queryParams.accountId" 
          placeholder="按账户ID筛选" 
          clearable
          style="width: 200px"
          @change="fetchAdPlans"
        >
          <el-option
            v-for="accountId in accountIds"
            :key="accountId"
            :label="`账户 ${accountId}`"
            :value="accountId"
          />
        </el-select>
        <el-select 
          v-model="queryParams.status" 
          placeholder="按状态筛选" 
          clearable
          style="width: 200px"
          @change="fetchAdPlans"
        >
          <el-option label="待执行" :value="1" />
          <el-option label="执行中" :value="2" />
          <el-option label="失败" :value="3" />
          <el-option label="已结束" :value="4" />
        </el-select>
      </div>

      <!-- 广告计划表格 -->
      <el-table
        :data="adPlanList"
        style="width: 100%"
        v-loading="planLoading"
        stripe
        border
        row-key="id"
        :expand-row-keys="expandedRows"
        @expand-change="handleExpandChange"
      >
        <el-table-column type="expand">
          <template #default="{ row }">
            <div class="p-4 bg-gray-50">
              <div class="mb-3 font-semibold text-gray-700">创意列表</div>
              <el-table
                :data="row.creatives"
                v-loading="row.creativesLoading"
                border
                size="small"
              >
                <el-table-column prop="id" label="创意ID" width="100" />
                <el-table-column prop="creativeName" label="创意名称" min-width="200" show-overflow-tooltip />
                <el-table-column prop="creativeId" label="腾讯创意ID" width="150">
                  <template #default="{ row: creative }">
                    <el-button
                      v-if="creative.creativeId"
                      type="primary"
                      link
                      @click="router.push({ path: '/daily-report', query: { dynamicCreativeId: creative.creativeId } })"
                    >{{ creative.creativeId }}</el-button>
                    <span v-else>-</span>
                  </template>
                </el-table-column>
                <el-table-column label="创意图片/视频" width="120">
                  <template #default="{ row: creative }">
                    <el-image
                      v-if="creative.creativeFileUrl"
                      :src="creative.creativeFileUrl"
                      :preview-src-list="[creative.creativeFileUrl]"
                      fit="cover"
                      style="width: 60px; height: 60px"
                      class="cursor-pointer rounded border"
                    />
                    <span v-else>-</span>
                  </template>
                </el-table-column>
                <el-table-column prop="imageId" label="图片ID" width="120" />
                <el-table-column prop="creativeText" label="创意文案" min-width="150" show-overflow-tooltip />
                <el-table-column prop="brandName" label="品牌名称" width="120" />
                <el-table-column label="品牌形象图片" width="120">
                  <template #default="{ row: creative }">
                    <el-image
                      v-if="creative.brandImageUrl"
                      :src="creative.brandImageUrl"
                      :preview-src-list="[creative.brandImageUrl]"
                      fit="cover"
                      style="width: 60px; height: 60px"
                      class="cursor-pointer rounded border"
                    />
                    <span v-else>-</span>
                  </template>
                </el-table-column>
                <el-table-column prop="brandImageId" label="品牌形象图片ID" width="120" />
                <el-table-column prop="buttonText" label="按钮文案" width="120" />
                <el-table-column prop="pageIds" label="落地页IDs" min-width="150" show-overflow-tooltip />
                <el-table-column label="状态" width="100">
                  <template #default="{ row: creative }">
                    <el-tag :type="getPlanStatusColor(creative.status)" size="small">
                      {{ getPlanStatusText(creative.status) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="失败原因" min-width="200" show-overflow-tooltip>
                  <template #default="{ row: creative }">
                    <span class="text-red-500">{{ creative.failReason || '-' }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="创建时间" width="180">
                  <template #default="{ row: creative }">
                    {{ formatDate(creative.createTime) }}
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="id" label="计划ID" width="100" />
        <el-table-column prop="adgroupName" label="广告组名称" min-width="200" show-overflow-tooltip />
        <el-table-column prop="accountId" label="账户ID" width="120" />
        <el-table-column prop="adgroupId" label="广告组ID" width="120" />
        <el-table-column label="广告类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getAdTypeColor(row.adType)" size="small">
              {{ getAdTypeText(row.adType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="出价金额" width="120">
          <template #default="{ row }">
            ¥{{ (row.bidAmount / 100).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="target" label="定向模版ID" width="100" show-overflow-tooltip />
        <el-table-column prop="site" label="版位模版ID" width="100" show-overflow-tooltip />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getPlanStatusColor(row.status)" size="small">
              {{ getPlanStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="失败原因" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <span class="text-red-500">{{ row.failReason || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
      </el-table>

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

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  getAdPlanConfDetail, 
  getAdPlanList, 
  reGeneratePlan,
  getAdPlanCreativesByPlanId 
} from '@/api/adPlanConf'

const route = useRoute()
const router = useRouter()

// 配置详情
const confDetail = ref(null)
const confLoading = ref(false)
const activeCollapse = ref([]) // 折叠面板激活项

// 广告计划列表
const adPlanList = ref([])
const planLoading = ref(false)
const total = ref(0)
const expandedRows = ref([])

// 查询参数
const queryParams = ref({
  confId: route.query.id,
  accountId: null,
  status: null,
  pageNum: 1,
  pageSize: 10
})
const handleReGeneratePlan = async (confId) => {
  try {
    const res = await reGeneratePlan(confId)
    if (res.success) {
      ElMessage.success('重新生成计划执行中')
    } else {
      ElMessage.error(res.msg || '重新生成计划失败')
    }
  } catch (error) {
    console.error('重新生成计划失败:', error)
    ElMessage.error('重新生成计划失败')
  }
}

// 获取唯一的账户ID列表
const accountIds = computed(() => {
  const ids = new Set()
  adPlanList.value.forEach(plan => {
    if (plan.accountId) {
      ids.add(plan.accountId)
    }
  })
  return Array.from(ids).sort((a, b) => a - b)
})

// 获取配置详情
const fetchConfDetail = async () => {
  confLoading.value = true
  try {
    const res = await getAdPlanConfDetail(queryParams.value.confId)
    if (res.success) {
      confDetail.value = res.data
    } else {
      ElMessage.error(res.msg || '获取配置详情失败')
    }
  } catch (error) {
    console.error('获取配置详情失败:', error)
    ElMessage.error('获取配置详情失败')
  } finally {
    confLoading.value = false
  }
}

// 获取广告计划列表
const fetchAdPlans = async () => {
  planLoading.value = true
  try {
    const res = await getAdPlanList(queryParams.value)
    if (res.success) {
      adPlanList.value = res.data.records || []
      total.value = res.data.total || 0
      
      // 初始化创意列表
      adPlanList.value.forEach(plan => {
        plan.creatives = []
        plan.creativesLoading = false
      })
      
      // 默认展开第一个广告计划并加载其创意
      if (adPlanList.value.length > 0) {
        const firstPlan = adPlanList.value[0]
        expandedRows.value = [firstPlan.id]
        await fetchCreatives(firstPlan)
      }
    } else {
      ElMessage.error(res.msg || '获取广告计划列表失败')
    }
  } catch (error) {
    console.error('获取广告计划列表失败:', error)
    ElMessage.error('获取广告计划列表失败')
  } finally {
    planLoading.value = false
  }
}

// 处理展开行变化
const handleExpandChange = async (row, expandedRowsArray) => {
  expandedRows.value = expandedRowsArray.map(r => r.id)
  
  // 如果展开且还没加载创意
  if (expandedRowsArray.some(r => r.id === row.id) && row.creatives.length === 0) {
    await fetchCreatives(row)
  }
}

// 获取创意列表
const fetchCreatives = async (plan) => {
  plan.creativesLoading = true
  try {
    const res = await getAdPlanCreativesByPlanId(plan.id)
    if (res.success) {
      plan.creatives = res.data || []
    } else {
      ElMessage.error(res.msg || '获取创意列表失败')
    }
  } catch (error) {
    console.error('获取创意列表失败:', error)
    ElMessage.error('获取创意列表失败')
  } finally {
    plan.creativesLoading = false
  }
}

// 返回
const goBack = () => {
  router.back()
}

// 广告类型文本
const getAdTypeText = (type) => {
  const map = {
    1: '企微',
    2: 'ROI'
  }
  return map[type] || '未知'
}

// 广告类型颜色
const getAdTypeColor = (type) => {
  const map = {
    1: 'success',
    2: 'primary'
  }
  return map[type] || ''
}

// 计划状态文本
const getPlanStatusText = (status) => {
  const map = {
    1: '待执行',
    2: '执行中',
    3: '失败',
    4: '已结束'
  }
  return map[status] || '未知'
}

// 计划状态颜色
const getPlanStatusColor = (status) => {
  const map = {
    1: 'info',
    2: 'warning',
    3: 'danger',
    4: 'success'
  }
  return map[status] || ''
}

// 格式化日期
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',
    hour12: false
  })
}

const handleRefresh = async () => {
  await fetchConfDetail()
  await fetchAdPlans()
}

// 初始化
onMounted(() => {
  if (!queryParams.value.confId) {
    ElMessage.error('缺少配置ID参数')
    goBack()
    return
  }
  
  fetchConfDetail()
  fetchAdPlans()
})
</script>

<style scoped>
/* 自定义样式 */
</style>
