<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>
        <div>
          <el-button type="danger" @click="handleSuspendAll(confDetail.id)">
            <el-icon><SwitchButton /></el-icon>
            全部暂停</el-button>
            <el-button type="danger" @click="handleDeleteAll(confDetail.id)">
            <el-icon><DeleteFilled /></el-icon>
            全部删除</el-button>
          <el-button type="primary" @click="handleRefresh(confDetail.id)">
            <el-icon><Refresh /></el-icon>
            刷新状态</el-button>
        </div>
      </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" style="margin-right: 8px;">
              {{ getPlanStatusText(confDetail.status) }}
            </el-tag>
            <el-tag v-if="confDetail.systemSuspendProcessStatus > 0" :type="getSuspendStatusColor(confDetail.systemSuspendProcessStatus)" size="large" style="margin-right: 8px;">
              {{ getSuspendStatusText(confDetail.systemSuspendProcessStatus) }}
            </el-tag>
            <el-tag v-if="confDetail.systemDeleteProcessStatus > 0" :type="getSuspendStatusColor(confDetail.systemDeleteProcessStatus)" size="large">
              {{ getDeleteStatusText(confDetail.systemDeleteProcessStatus) }}
            </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="warning" @click="handleSuspendPlans(confDetail.id)">
            <el-icon><SwitchButton /></el-icon>
            暂停选中计划</el-button>
            <el-button type="warning" @click="handleDeletePlans(confDetail.id)">
            <el-icon><DeleteFilled /></el-icon>
            删除选中计划</el-button>
           <el-button type="primary" @click="handleSystemStatusSync(confDetail.id)">
            <el-icon><Refresh /></el-icon>
            同步平台状态</el-button>
           <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
          filterable
          style="width: 200px"
          @change="fetchAdPlans"
        >
          <el-option
            v-for="accountId in accountIds"
            :key="accountId"
            :label="`${accountId}`"
            :value="accountId"
          />
        </el-select> -->
        <el-input 
          v-model="queryParams.accountId" 
          placeholder="按账户ID筛选" 
          clearable
          style="width: 200px"
        />
        <el-input 
          v-model="queryParams.adgroupId" 
          placeholder="按广告ID筛选" 
          clearable
          style="width: 200px"
        />
        <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>
        <el-button type="primary" @click="fetchAdPlans">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
            <el-button @click="handleReset">重置</el-button>
      </div>

      <!-- 广告计划表格 -->
      <el-table
        :data="adPlanList"
        style="width: 100%"
        v-loading="planLoading"
        stripe
        border
        row-key="id"
        :expand-row-keys="expandedRows"
        @expand-change="handleExpandChange"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection"  width="55" />
        <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="creativeName" label="创意名称" min-width="100" show-overflow-tooltip />
                <el-table-column prop="creativeId" label="腾讯创意ID" width="130">
                  <template #default="{ row }">
                    {{ row.creativeId }}
                    <el-button v-if="row.creativeId > 0" link size="small" @click="goToTencentCreative(row)">
                     <el-icon color="#409efc" class="no-inherit">
                      <Share />
                    </el-icon>
                    </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.creativeFileType === 'image' && creative.creativeFileUrl"
                      :src="creative.creativeFileUrl"
                      :preview-src-list="[creative.creativeFileUrl]"
                      :preview-teleported="true"
                      style="width: 60px; height: 60px"
                      class="cursor-pointer rounded"
                    />
                    <video v-else-if="creative.creativeFileType === 'video' && creative.creativeFileUrl" controls>
                      <source :src="creative.creativeFileUrl" type="video/mp4">
                    </video>
                  </template>
                </el-table-column>
                <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]"
                      :preview-teleported="true"
                      fit="cover"
                      style="width: 60px; height: 60px"
                      class="cursor-pointer rounded border"
                    />
                    <span v-else>-</span>
                  </template>
                </el-table-column>
                <el-table-column prop="buttonText" label="按钮文案" width="120" />
                <el-table-column label="设置状态" prop="configuredStatus" width="100" >
                  <template #default="{ row }">
                    {{ getConfiguredStatusText(row.configuredStatus) }}
                  </template>
                </el-table-column>
                <el-table-column prop="approvalStatus" label="审核状态" width="120" show-overflow-tooltip />
                <el-table-column label="系统删除" prop="systemDelete" width="85" >
                  <template #default="{ row }">
                    {{ row.systemDelete == 'true' ? '是' : '否'}}
                  </template>
                  </el-table-column>
                <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="花费" prop="cost" width="100">
          <template #default="{ row }">
            {{ row.cost && (row.cost / 100).toFixed(2) || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="目标转化成本" prop="conversionsCost" width="120">
          <template #default="{ row }">
            {{ row.conversionsCost && (row.conversionsCost / 100).toFixed(2) || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="加粉成本" prop="scanFollowUserCost" width="100">
          <template #default="{ row }">
            {{ row.scanFollowUserCost && (row.scanFollowUserCost / 100).toFixed(2) || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="曝光" prop="viewCount" width="100"></el-table-column>
        <el-table-column label="有效点击" prop="validClickCount" width="100"></el-table-column>
        <el-table-column label="点击率" prop="ctr" width="100"></el-table-column>
        <el-table-column label="播放首日变现" prop="reqIncomeVal1" width="120"></el-table-column>
        <el-table-column label="播放首日ROI" prop="reqIncomeRoi1" width="120"></el-table-column>
        <el-table-column label="转化首日变现" prop="repIncomeVal1" width="120"></el-table-column>
        <el-table-column label="转化首日ROI" prop="repIncomeRoi1" width="120"></el-table-column>
                 <el-table-column prop="pageIds" label="落地页IDs" min-width="150" show-overflow-tooltip />
                <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="adgroupName" label="广告组名称" min-width="100" show-overflow-tooltip />
        <el-table-column prop="accountId" label="账户ID" width="130" >
          <template #default="{ row }">
            {{ row.accountId }}
            <el-button v-if="row.accountId > 0" size="small"  link  @click="goToTencentByAccountId(row)">
               <el-icon color="#409efc" class="no-inherit">
                <Share />
              </el-icon>
              </el-button>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="adgroupId" label="广告ID" width="150" >
          <template #default="{ row }">
            {{ row.adgroupId }}
            <el-button v-if="row.adgroupId > 0" size="small" link @click="goToTencentByAdgroupId(row)">
              <el-icon color="#409efc" class="no-inherit">
                <Share />
              </el-icon>
            </el-button>
            <span v-else>-</span>
          </template>
          </el-table-column>
        <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 label="期望ROI" width="100">
          <template #default="{ row }">
            {{ row.deepConversionWorthRate }}
          </template>
        </el-table-column>
        <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="设置状态" prop="configuredStatus" width="100" >
          <template #default="{ row }">
            {{ getConfiguredStatusText(row.configuredStatus) }}
          </template>
        </el-table-column>
        <el-table-column label="系统状态" prop="systemStatus" width="100" show-overflow-tooltip />
        <el-table-column label="系统删除" prop="systemDelete" width="85" >
          <template #default="{ row }">
            {{ row.systemDelete == 'true' ? '是' : '否'}}
          </template>
          </el-table-column>
        <el-table-column label="花费" prop="cost" width="100">
          <template #default="{ row }">
            {{ row.cost && (row.cost / 100).toFixed(2) || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="预算" prop="dailyBudget" width="100">
          <template #default="{ row }">
            {{ row.dailyBudget && (row.dailyBudget / 100).toFixed(2) || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="目标转化成本" prop="conversionsCost" width="120">
          <template #default="{ row }">
            {{ row.conversionsCost && (row.conversionsCost / 100).toFixed(2) || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="加粉成本" prop="scanFollowUserCost" width="100">
          <template #default="{ row }">
            {{ row.scanFollowUserCost && (row.scanFollowUserCost / 100).toFixed(2) || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="曝光" prop="viewCount" width="100"></el-table-column>
        <el-table-column label="有效点击" prop="validClickCount" width="100"></el-table-column>
        <el-table-column label="点击率" prop="ctr" width="100"></el-table-column>
        <el-table-column label="播放首日变现" prop="reqIncomeVal1" width="120"></el-table-column>
        <el-table-column label="播放首日ROI" prop="reqIncomeRoi1" width="120"></el-table-column>
        <el-table-column label="转化首日变现" prop="repIncomeVal1" width="120"></el-table-column>
        <el-table-column label="转化首日ROI" prop="repIncomeRoi1" width="120"></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="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>
defineOptions({
  name: 'AdPlanConfDetail'
})

import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getAdPlanConfDetail, 
  getAdPlanList, 
  reGeneratePlan,
  getAdPlanCreativesByPlanId,
  syncSystemStatus,
    suspendByConfId,
    deleteByConfId,
    deleteByPlanIds,
  suspendByPlanIds
} from '@/api/adPlanConf'
import dayjs from 'dayjs'

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 selectedRows = ref([])

// 查询参数
const queryParams = ref({
  confId: route.query.id,
  adgroupId: null,
  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 goToTencentByAccountId  = (row) => {
  const date = dayjs().format('YYYY-MM-DD')
  window.open(`https://ad.qq.com/atlas/${row.accountId}/admanage/index?start_date=${date}&end_date=${date}&tab=adgroup&query={%22operation_status%22:[%22CALCULATE_STATUS_EXCLUDE_DEL%22],%22system_status%22:[]}`, '_blank')
}

const goToTencentByAdgroupId = (row) => {
  const date = dayjs().format('YYYY-MM-DD')
  window.open(`https://ad.qq.com/atlas/${row.accountId}/admanage/index?start_date=${date}&end_date=${date}&tab=adgroup&query={%22operation_status%22:[%22CALCULATE_STATUS_EXCLUDE_DEL%22],%22system_status%22:[],%22search_name%22:%22${row.adgroupId}%22}`, '_blank')
}

const goToTencentCreative = (row) => {
  window.open(`https://ad.qq.com/atlas/${row.accountId}/admanage/index?tab=dynamic_creative&query={%22operation_status%22:[],%22created_time%22:%22-89%22,%22fuzzy_name%22:%22${row.creativeId}%22}`, '_blank')
}

const handleReset = () => {
  queryParams.value = {
    confId: route.query.id,
    adgroupId: null,
    accountId: null,
    status: null,
    pageNum: 1,
    pageSize: 10
  }
  fetchAdPlans()
}

// 获取广告计划列表
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 handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 处理展开行变化
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: '已提交',
    5: '部分失败'
  }
  return map[status] || '未知'
}

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

//0 未暂停 1 暂停中 2 暂停完毕 3 暂停失败 
const getSuspendStatusColor = (status) => {
  const map = {
    1: 'warning',
    2: 'success',
    3: 'danger',
  }
  return map[status] || ''
}

const getSuspendStatusText = (status) => {
  const map = {
    1: '暂停中',
    2: '暂停完毕',
    3: '暂停失败'
  }
  return map[status] || '未知'
}

const getDeleteStatusText = (status) => {
  const map = {
    1: '删除中',
    2: '删除成功',
    3: '删除失败'
  }
  return map[status] || '未知'
}

//AD_STATUS_NORMAL 有效
// AD_STATUS_SUSPEND 暂停
const getConfiguredStatusText = (status) => {
  const map = {
    1: '有效',
    2: '暂停'
  }
  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()
}

const handleSuspendAll = async (confId) => {
    ElMessageBox.confirm(
      `确定要暂停配置"${confDetail.value.name}"的全部计划吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(async () => {
        const res = await suspendByConfId(confId)
        if (res.success) {
          ElMessage.success(res.msg || '暂停中。。。')
          handleRefresh()
        } else {
          ElMessage.error(res.msg || '暂停中。。。')
        }
    })
}

const handleDeleteAll = (confId) => {
  ElMessageBox.confirm(
    `确定要删除配置"${confDetail.value.name}"的全部计划吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    const res = await deleteByConfId(confId)
    if (res.success) {
      ElMessage.success(res.msg || '删除中。。。')
      handleRefresh()
    } else {
      ElMessage.error(res.msg || '删除中。。。')
    }
  })
}

const handleSuspendPlans = (confId) => {
  ElMessageBox.confirm(
    `确定要暂停配置"${confDetail.value.name}"的选中的计划吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    if (selectedRows.value.length < 1) {
      return
    }
    const res = await suspendByPlanIds(confId, selectedRows.value.map(r => r.id))
    if (res.success) {
      ElMessage.success(res.msg || '暂停中。。。')
      handleRefresh()
    } else {
      ElMessage.error(res.msg || '暂停中。。。')
    }
  })
}

const handleDeletePlans = (confId) => {
  ElMessageBox.confirm(
    `确定要删除配置"${confDetail.value.name}"的选中的计划吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    if (selectedRows.value.length < 1) {
      return
    }
    const res = await deleteByPlanIds(confId, selectedRows.value.map(r => r.id))
    if (res.success) {
      ElMessage.success(res.msg || '删除中。。。')
      handleRefresh()
    } else {
      ElMessage.error(res.msg || '删除中。。。')
    }
  })
}

const handleSystemStatusSync = (confId) => {
  ElMessageBox.confirm(
    `确定要同步"${confDetail.value.name}"的全部计划的广告平台状态吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    const res = await syncSystemStatus(confId)
    if (res.success) {
      ElMessage.success(res.msg || '同步平台状态中。。。')
      handleRefresh()
    } else {
      ElMessage.error(res.msg || '同步平台状态失败')
    }
  })
}

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

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