<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>
            <el-button type="primary" @click="loadConfList">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
          <el-button type="primary" @click="handleCreate">
            <el-icon><Plus /></el-icon>
            创建配置
          </el-button>
          </div>
        </div>
      </div>

      <!-- 查询表单 -->
      <div class="mb-6 p-4 bg-gray-50 rounded-lg">
        <el-form :model="searchForm" inline>
          <el-form-item label="查询范围">
            <el-radio-group v-model="searchForm.queryScope" @change="handleSearch">
              <el-radio label="我的" :value="1" />
              <el-radio label="全部" :value="2" />
            </el-radio-group>
          </el-form-item>
          <el-form-item label="计划名称">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入计划名称"
              clearable
              style="width: 200px"
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              clearable
              style="width: 120px"
              @change="handleSearch"
            >
              <el-option label="待执行" :value="1" />
              <el-option label="执行中" :value="2" />
              <el-option label="失败" :value="3" />
              <el-option label="已结束" :value="4" />
              <el-option label="部分失败" :value="5" />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="searchForm.createTimeRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              @change="handleSearch"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 配置列表 -->
      <el-table
        :data="confList"
        style="width: 100%"
        v-loading="loading"
        stripe
        border
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="计划名称" width="200" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100" >
          <template #default="{ row }">
            <el-tag :type="getPlanStatusColor(row.status)">
              {{ getPlanStatusText(row.status) }}
            </el-tag>
          </template>
          </el-table-column>
          <el-table-column prop="failReason" label="原因" width="100" show-overflow-tooltip>
          </el-table-column>
        <el-table-column label="广告类型" align="center" width="90">
          <template #default="{ row }">
            <el-tag :type="getAdTypeColor(row.adType)">
              {{ getAdTypeText(row.adType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="出价金额" width="100">
          <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 prop="accountGroupId" label="账号组ID" width="90" />
        <el-table-column prop="conversionId" label="转化ID" width="120" />
        <el-table-column prop="assetType" align="center" label="资产类型" width="100" >
          <template #default="{ row }">
            {{ getAssetTypeText(row.assetType) }}
          </template>
           </el-table-column>
        <el-table-column prop="assetModel" align="center" label="资产模型" width="100" >
          <template #default="{ row }">
            <el-tag :type="row.assetModel === 1 ? 'success' : 'primary'">
              {{ getAssetModelText(row.assetModel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="dramaAmount" align="center" label="资产数量" width="120" >
          <template #default="{ row }">
            {{ `${row.dramaAmount}  ｜  ${row.fictionAmount}` }}
          </template>
        </el-table-column>
        <el-table-column prop="targets" label="定向" width="80" show-overflow-tooltip/>
        <el-table-column prop="sites" label="版位" width="80" show-overflow-tooltip/>
        <el-table-column prop="wxCorpid" label="企微主体ID" width="150" show-overflow-tooltip />
        <el-table-column prop="pageIds" label="落地页ID" width="150" show-overflow-tooltip />
        <el-table-column label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" link @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <!-- <el-button type="danger" size="small" link @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button> -->
            <el-button size="small"  link @click="goToDetail(row)">
              <el-icon><View /></el-icon>
              详情
            </el-button>
            <el-button size="small" link @click="copyConf(row)">
             <el-icon><CopyDocument /></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]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </div>

    <!-- 创建/编辑配置对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="60%"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="计划名称" prop="name">
          <el-input
            v-model="formData.name"
            placeholder="请输入计划名称"
            clearable
          />
        </el-form-item>

        <el-form-item label="广告类型" prop="adType">
          <el-radio-group v-model="formData.adType">
            <el-radio label="企微" :value="1" />
            <el-radio label="ROI" :value="2" />
          </el-radio-group>
        </el-form-item>

        <el-form-item label="账号组ID" prop="accountGroupId">
          <el-select
            :disabled="valueDisabled"
            v-model="formData.accountGroupId"
            style="width: 100%"
            placeholder="请选择账号组"
          >
            <el-option
              v-for="accountGroup in accountGroupList"
              :key="accountGroup.id"
              :label="accountGroup.groupName"
              :value="accountGroup.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="出价金额(元)" prop="bidAmount">
          <el-input-number
            v-model="bidAmountYuan"
            :min="0"
            :precision="2"
            :step="0.10"
            placeholder="请输入出价金额"
            style="width: 100%"
            :controls="true"
          />
          <span class="ml-2 text-sm text-gray-500">= {{ formData.bidAmount }} 分</span>
        </el-form-item>

        <el-form-item label="期望ROI" prop="deepConversionWorthRate" v-if="formData.adType === 2">
          <el-input-number
            v-model="formData.deepConversionWorthRate"
            :min="0"
            :precision="2"
            :step="0.10"
            placeholder="请输入期望ROI"
            style="width: 100%"
            :controls="true"
          />
        </el-form-item>

        <el-form-item label="转化ID" prop="conversionId">
          <el-select
          :disabled="valueDisabled"
            v-model="formData.conversionId"
            :min="1"
            placeholder="请输入转化ID"
            style="width: 100%"
          >
            <el-option
              v-for="conversion in conversions"
              :key="conversion.conversionId"
              :label="conversion.conversionName"
              :value="conversion.conversionId"
            />
          </el-select>
        </el-form-item>
         <el-form-item label="定向模版IDs" prop="targets">
          <el-input
          :disabled="valueDisabled"
            v-model="formData.targets"
            type="textarea"
            :rows="2"
            placeholder="多个定向ID用逗号分隔，例如：1,2,3"
          />
          <el-collapse class="mt-1 text-xs text-gray-500" >
            <el-collapse-item title="定向模版ID配置说明(新模版【2】)">
              <div>【1】</div>
              <p class="whitespace-pre-line">
                地域：中国（常住地）<br />
                年龄：大于等于42岁<br />
                性别：男性<br />
                排除已转化用户：同集团（自定义转化行为：指定页面曝光,加企业微信客服）（转化时间区间：1个月）<br />
                排除人群：44106830，44107982，43712084，44241932<br />
                不限：学历，婚恋育儿状态，用户消费能力，应用安装，设备品牌型号，操作系统版本，联网方式，移动运营商，定向人群，设备价格，微信再营销
              </p>
              <div style="color: red;">【2】</div>
              <p style="color: red;" class="whitespace-pre-line">
                地域：中国（常住地）<br />
                年龄：大于等于50岁<br />
                性别：男性<br />
                排除已转化用户：同集团（自定义转化行为：指定页面曝光,加企业微信客服）（转化时间区间：1个月）<br />
                排除人群：44106830，44107982，43712084，44241932<br />
                不限：学历，婚恋育儿状态，用户消费能力，应用安装，设备品牌型号，操作系统版本，联网方式，移动运营商，定向人群，设备价格，微信再营销
              </p>
            </el-collapse-item>
          </el-collapse>
        </el-form-item>
         <el-form-item label="版位模版IDs" prop="sites">
          <el-input
          :disabled="valueDisabled"
            v-model="formData.sites"
            type="textarea"
            :rows="2"
            placeholder="多个版位ID用逗号分隔，例如：1,2,3"
          />
          <el-collapse class="mt-1 text-xs text-gray-500" >
            <el-collapse-item title="版位模版ID配置说明(新模版【11】)">
              <div>1:[KANDIAN, QQ_MUSIC_GAME, TENCENT_NEWS, TENCENT_VIDEO, SEARCH_SCENE, MOBILE_UNION, WECHAT, WECHAT_PLUGIN]</div>
              <div>2:[QQ_MUSIC_GAME, TENCENT_NEWS, TENCENT_VIDEO, SEARCH_SCENE, MOBILE_UNION, WECHAT, WECHAT_PLUGIN]</div>
              <div>3:[TENCENT_NEWS, TENCENT_VIDEO, SEARCH_SCENE, MOBILE_UNION, WECHAT, WECHAT_PLUGIN]</div>
              <div>4:[KANDIAN, QQ_MUSIC_GAME, TENCENT_VIDEO, SEARCH_SCENE, MOBILE_UNION, WECHAT, WECHAT_PLUGIN]</div>
              <div>5:[KANDIAN, QQ_MUSIC_GAME, TENCENT_NEWS, TENCENT_VIDEO, SEARCH_SCENE, WECHAT, WECHAT_PLUGIN]</div>
              <div>6:[KANDIAN, QQ_MUSIC_GAME, TENCENT_NEWS, SEARCH_SCENE, MOBILE_UNION, WECHAT, WECHAT_PLUGIN]</div>
              <div>7:[QQ_MUSIC_GAME, TENCENT_NEWS, TENCENT_VIDEO, SEARCH_SCENE, MOBILE_UNION, WECHAT, WECHAT_PLUGIN]</div>
              <div>8:[KANDIAN, QQ_MUSIC_GAME, TENCENT_VIDEO, SEARCH_SCENE, MOBILE_UNION, WECHAT, WECHAT_PLUGIN]</div>
              <div>9:[KANDIAN, TENCENT_NEWS, TENCENT_VIDEO, SEARCH_SCENE, MOBILE_UNION, WECHAT, WECHAT_PLUGIN]</div>
              <div>10:[TENCENT_VIDEO, SEARCH_SCENE, MOBILE_UNION, WECHAT, WECHAT_PLUGIN]</div>
              <div style="color: red;">* 11:[SITE_SET_WECHAT, SITE_SET_WECHAT_PLUGIN, SITE_SET_SEARCH_SCENE]</div>
            </el-collapse-item>
          </el-collapse>
        </el-form-item>
        <el-form-item label="企微主体ID" prop="wxCorpid" v-if="formData.adType === 1">
          <el-input
            v-model="formData.wxCorpid"
            placeholder="请输入企微主体ID"
            clearable
          />
        </el-form-item>

        <!-- <el-form-item label="短剧ID" prop="dramaId" v-if="formData.adType === 2">
          <el-radio-group v-model="dramaSort">
            <el-radio label="最新" :value="1" />
            <el-radio label="最老" :value="0" />
          </el-radio-group>
          <el-select
            :disabled="valueDisabled"
            v-model="formData.dramaId"
            style="width: 100%"
            placeholder="请选择短剧"
            filterable
            clearable
          >
            <el-option
              v-for="drama in sortedDramaList"
              :key="drama.id"
              :label="`${drama.marketingAssetName}[${drama.marketingAssetId}]`"
              :value="drama.marketingAssetId"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="资产模型" prop="assetModel" v-if="formData.adType === 2">
          <el-radio-group v-model="formData.assetModel">
            <el-radio label="随机" :value="1" />
            <el-radio label="最新" :value="2" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="资产类型" prop="assetType" v-if="formData.adType === 2">
          <el-radio-group v-model="formData.assetType">
            <el-radio label="短剧" :value="1" />
            <el-radio label="小说" :value="2" />
            <el-radio label="混合" :value="3" />
          </el-radio-group>
        </el-form-item>
        <p style="color: red;font-size: 12px; padding-left: 120px;" v-if="formData.adType === 2 && [1, 3].includes(formData.assetType)">*请确保【短剧资产列表】已同步短剧资产</p>
        <el-form-item label="每户几部短剧" prop="dramaAmount" v-if="formData.adType === 2 && [1, 3].includes(formData.assetType)">
          <el-input-number
            v-model="formData.dramaAmount"
            :min="0"
            :precision="0"
            :step="1"
            placeholder="请输入每户几部短剧"
            style="width: 100%"
            :controls="true"
          />
        </el-form-item>

        <p style="color: red;font-size: 12px; padding-left: 120px;" v-if="formData.adType === 2 && [2, 3].includes(formData.assetType)">*请确保【小说资产列表】已同步短剧资产</p>
        <el-form-item label="每户几部小说" prop="fictionAmount" v-if="formData.adType === 2 && [2, 3].includes(formData.assetType)">
          <el-input-number
            v-model="formData.fictionAmount"
            :min="0"
            :precision="0"
            :step="1"
            placeholder="请输入每户几部小说"
            style="width: 100%"
            :controls="true"
          />
        </el-form-item>

        <el-form-item label="落地页" prop="pageIdArr">
          <el-select
            :disabled="valueDisabled"
            v-model="formData.pageIdArr"
            style="width: 100%"
            placeholder="请选择落地页"
            multiple
            filterable
          >
            <el-option
              v-for="page in loadPageList"
              :key="page.id"
              :label="`${page.name}[${page.pageId}]`"
              :value="page.pageId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="创意图片/视频" prop="creativeFileArr">
          <div class="flex flex-col gap-2">
            <div class="flex flex-row gap-2">
              <el-button  :disabled="valueDisabled" size="small" @click="openFileSelector('creative')" style="width: fit-content">选择文件</el-button>
              <el-button type="primary" :disabled="valueDisabled" size="small" @click="addOneCreativeImage" style="width: fit-content"><el-icon><Plus /></el-icon> 加个图片</el-button>
              <el-button type="primary" :disabled="valueDisabled" size="small" @click="addOneCreativeVideo" style="width: fit-content"><el-icon><Plus /></el-icon> 加个视频</el-button>
            </div>
            <div v-if="formData.creativeFileArr" class="flex flex-wrap gap-2">
              <div
                v-for="(cf, index) in formData.creativeFileArr"
                :key="index"
                class="relative inline-block"
              >
                <el-image
                  v-if="cf.fileType === 'image'"
                  :src="cf.fileUrl"
                  fit="cover"
                  style="width: 80px; height: 80px; display: block"
                  class="cursor-pointer rounded border"
                ></el-image>
                <video
                  v-else-if="cf.fileType === 'video'"
                  :src="cf.fileUrl"
                  controls
                  style="width: 80px; height: 80px; display: block"
                  class="cursor-pointer rounded border"></video>
                <button
                  type="button"
                  :disabled="valueDisabled"
                  @click="removeFile('creative', index)"
                  class="absolute -top-1 -right-1 cursor-pointer bg-red-500 text-white rounded-full w-5 h-5 flex items-center justify-center hover:bg-red-600 transition-colors"
                  style="z-index: 10"
                >
                  <el-icon :size="14">
                    <Close />
                  </el-icon>
                </button>
              </div>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="品牌形象图片" prop="brandImageUrl">
          <div class="flex flex-col gap-2">
            <div class="flex flex-row gap-2">
              <el-button  :disabled="valueDisabled" size="small" @click="openFileSelector('brand')" style="width: fit-content">选择图片</el-button>
              <el-button type="primary" :disabled="valueDisabled" size="small" @click="randomOneBrandImage" style="width: fit-content"><el-icon><Refresh /></el-icon> 随机图片</el-button>
            </div>
            <div v-if="formData.brandImageUrl">
              <div class="relative inline-block">
                <el-image
                  :src="formData.brandImageUrl"
                  :preview-src-list="[formData.brandImageUrl]"
                  fit="cover"
                  style="width: 80px; height: 80px; display: block"
                  class="cursor-pointer rounded border"
                />
                <button
                  type="button"
                  :disabled="valueDisabled"
                  @click="removeFile('brand', 0)"
                  class="absolute -top-1 -right-1 cursor-pointer bg-red-500 text-white rounded-full w-5 h-5 flex items-center justify-center hover:bg-red-600 transition-colors"
                  style="z-index: 10"
                >
                  <el-icon :size="14">
                    <Close />
                  </el-icon>
                </button>
              </div>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="创意文案" prop="creativeText">
          <el-input
            v-model="formData.creativeText"
            placeholder="请输入创意文案"
            maxlength="30"
            show-word-limit
            clearable
          />
        </el-form-item>

        <el-form-item label="品牌名称" prop="brandName">
          <el-input
            v-model="formData.brandName"
            placeholder="请输入品牌名称"
            maxlength="20"
            show-word-limit
            clearable
          />
        </el-form-item>

        <el-form-item label="按钮文案" prop="buttonText">
          <el-input
            v-model="formData.buttonText"
            placeholder="请输入按钮文案"
            maxlength="20"
            show-word-limit
            clearable
          />
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="handleReCreate">预览</el-button>
      <el-table :data="plans"
      :preserve-expanded-content="true"
        row-key="adgroupName"
        :expand-row-keys="expandedRows"
      >
        <el-table-column type="expand">
        <template #default="props">
            <div m="4">
            <h3>创意</h3>
            <el-table :data="props.row.adCreatives" border>
                <el-table-column label="创意图片/视频" width="120">
                  <template #default="{ row }">
                    <el-image
                      v-if="row.creativeFileType === 'image' && row.creativeFileUrl"
                      :src="row.creativeFileUrl"
                      :preview-src-list="[row.creativeFileUrl]"
                      fit="cover"
                      style="width: 60px; height: 60px"
                      class="cursor-pointer rounded border"
                    />
                    <video
                      v-else-if="row.creativeFileType === 'video' && row.creativeFileUrl"
                      :src="row.creativeFileUrl"
                      controls
                      style="width: 60px; height: 60px"
                      class="cursor-pointer rounded border"></video>
                    <span v-else>-</span>
                  </template>
                </el-table-column>
                <el-table-column prop="imageId" label="资产ID" width="130">
                  <template #default="{ row }">
                    {{ row.imageId  || row.videoId}}
                  </template>
                  </el-table-column>
                <el-table-column prop="creativeName" label="创意名称" min-width="100" show-overflow-tooltip />
                <el-table-column prop="creativeText" label="创意文案" min-width="100" show-overflow-tooltip />
                <el-table-column prop="brandName" label="品牌名称" width="120" />
                <el-table-column label="品牌形象图片" width="120">
                  <template #default="{ row }">
                    <el-image
                      v-if="row.brandImageUrl"
                      :src="row.brandImageUrl"
                      :preview-src-list="[row.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="buttonText" label="按钮文案" width="120" />
                <el-table-column label="落地页IDs" prop="pageIds" min-width="150" show-overflow-tooltip />
            </el-table>
            </div>
        </template>
        </el-table-column>
        <el-table-column prop="adgroupName" label="计划名称" width="200" show-overflow-tooltip />
        <el-table-column prop="accountId" label="账号ID" width="120" show-overflow-tooltip />
        <el-table-column prop="bidAmount" label="出价金额" width="120">
          <template #default="{ row }">
            ¥{{ (row.bidAmount / 100).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="deepConversionWorthRate" label="期望ROI" width="120">
          <template #default="{ row }">
            {{ row.deepConversionWorthRate }}
          </template>
        </el-table-column>
        <el-table-column prop="assetType" label="资产类型" width="120" >
          <template #default="{ row }">
            {{ row.assetType === 1 ? '短剧' : row.assetType === 2 ? '小说' : '未知' }}
          </template>
        </el-table-column>
          <el-table-column prop="dramaId" label="资产ID" width="120" >
            <template #default="{ row }">
              {{ row.assetType === 1 ? row.dramaId : row.fictionId }}
            </template>
            </el-table-column>
        <el-table-column prop="dramaName" label="资产名称" width="120" show-overflow-tooltip >
          <template #default="{ row }">
            {{ row.assetType === 1 ? row.dramaName : row.fictionName }}
          </template>
          </el-table-column>
        <el-table-column prop="conversionId" label="转化ID" width="120" />
        <el-table-column prop="wxCorpid" label="企微主体ID" width="150" show-overflow-tooltip />
      </el-table>
      <template #footer>
        <!--生成计划按钮tip提示先进行预览操作-->
        <!-- ：1-待执行，2-执行中，3-失败，4-已结束 -->
        <el-tooltip
        v-if="formData.status === 1"
        class="box-item"
        effect="dark"
        :content="plans.length === 0 ? '请先进行预览操作' : ''"
        placement="top-start"
      >
        <el-button :loading="generatePlanBtnLoading" :disabled="plans.length === 0" @click="handleGeneratePlan" >生成计划</el-button>
      </el-tooltip>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          保存配置
        </el-button>
      </template>
    </el-dialog>

    <!-- 文件选择对话框 -->
    <el-dialog
      v-model="fileSelectorVisible"
      :title="fileSelectorTitle"
      width="70%"
    >
      <div class="mb-4 flex gap-4">
        <el-input
          v-model="fileSearchParams.fileName"
          placeholder="搜索文件名"
          clearable
          style="width: 200px"
        />
        <el-select
          @change="loadFileList"
          v-model="fileSearchParams.fileType"
          placeholder="选择文件类型"
          style="width: 120px"
        >
          <el-option label="图片" value="image" />
          <el-option label="视频" value="video" />
        </el-select>
        <el-button type="primary" @click="loadFileList">搜索</el-button>
      </div>

      <el-table
        :data="fileList"
        v-loading="fileLoading"
        @selection-change="handleFileSelectionChange"
        @sort-change="handleFileSortChange"
        :default-sort="{ prop: 'normalCnt', order: 'descending' }"
        stripe
        border
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="assetId" label="资产ID" width="120"></el-table-column>
        <el-table-column prop="normalCnt" label="审核通过数" width="120" sortable="custom"></el-table-column>
        <el-table-column prop="deniedCnt" label="审核拒绝数" width="120" sortable="custom"></el-table-column>
         <el-table-column prop="originalFileName" label="文件名" min-width="120" show-overflow-tooltip />
        <el-table-column prop="fileUrl" label="展示" max-width="100" show-overflow-tooltip >
          <template #default="{ row }">
            <el-image v-if="row.fileType === 'image'"
              :src="row.fileUrl"
              style="width: 120px; height: 100px"
              fit="cover"
            />
            <video v-else-if="row.fileType === 'video'"
              :src="row.fileUrl"
              style="width: 120px; height: 100px"
              controls
            />
          </template>
        </el-table-column>
        <el-table-column prop="fileType" label="类型" width="100" />

        <el-table-column label="业务分类" width="120">
          <template #default="{ row }">
            <el-tag v-if="row.businessType === 1" type="success">创意</el-tag>
            <el-tag v-else-if="row.businessType === 2" type="primary">品牌形象</el-tag>
            <el-tag v-else type="info">未分类</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="文件大小" width="100">
          <template #default="{ row }">
            {{ formatFileSize(row.fileSize) }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdTime) }}
          </template>
        </el-table-column>
        <el-table-column label="预览" width="100">
          <template #default="{ row }">
            <el-button
              v-if="row.fileType === 'image'"
              size="small"
              link
              @click="previewFile(row.fileUrl)"
            >
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="mt-4 flex justify-end">
        <el-pagination
          v-if="fileTotal > 0"
          v-model:current-page="fileSearchParams.page"
          v-model:page-size="fileSearchParams.size"
          :page-sizes="[10, 20, 50]"
          :total="fileTotal"
          layout="total, sizes, prev, pager, next"
          @current-change="loadFileList"
          @size-change="loadFileList"
        />
      </div>

      <template #footer>
        <el-button @click="fileSelectorVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmFileSelection">确定</el-button>
      </template>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="previewVisible" title="图片预览" width="60%">
      <img :src="previewUrl" style="width: 100%" />
    </el-dialog>
  </div>
</template>

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

import { ref, computed, onMounted, watch, toRaw } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getAdPlanConfList,
  createAdPlanConf,
  updateAdPlanConf,
  deleteAdPlanConf,
  reCreateAdPlanConf,
  generatePlan,
    getOneCreativeImage,
    getOneCreativeVideo,
    getOneBrandImage
} from '@/api/adPlanConf'
import { myDramaAssetList } from '@/api/drama'
import { getConversions } from '@/api/conversion'
import { getAccountGroupListAll } from '@/api/accountGroup'
import { getFileList } from '@/api/ossFile'
import { getAllLoadPageConf } from '@/api/loadPageConf'

import {
  Plus,
  Edit,
  Delete,
  CopyDocument,
  Close,
  Search
} from '@element-plus/icons-vue'
import router from '@/router'
import dayjs from 'dayjs'
import { de } from 'element-plus/es/locales.mjs'


// 数据
const loading = ref(false)
const submitting = ref(false)
const confList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 查询表单
const searchForm = ref({
  queryScope: 1,
  name: '',
  status: null,
  createTimeRange: []
})

const dramaSort = ref(1)
const dramaList = ref([])
const loadPageList = ref([])

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('创建配置')
const formRef = ref(null)
const editingId = ref(null)
const conversions = ref([])
const accountGroupList = ref([])
const plans = ref([])
const expandedRows = ref([])

// 文件选择
const fileSelectorVisible = ref(false)
const fileSelectorTitle = ref('')
const currentFileType = ref('') // 'creative' or 'brand'
const fileList = ref([])
const fileLoading = ref(false)
const fileTotal = ref(0)
const selectedFiles = ref([])
const fileSearchParams = ref({
  page: 1,
  size: 10,
  fileType: '',
  fileName: '',
  businessType: null,
  sortField: 'normalCnt',
  sortOrder: 'descending'
})

// 图片预览
const previewVisible = ref(false)
const previewUrl = ref('')

// 表单数据
const formData = ref({
  name: '',
  accountGroupId: null,
  adType: 2,
  bidAmount: 150,
  conversionId: null,
  wxCorpid: '',
  dramaId: null,
  imageIds: '',
  assetType: 1,
  assetModel: 1,
  dramaAmount: 0,
  fictionAmount: 0,
  pageIds: '',
  pageIdArr: [],
  creativeFileArr: [],
  creativeFileUrls: '',
  creativeFileNames: '',
  brandImageFile: null,
  brandImageUrl: '',
  creativeText: '',
  brandName: '',
  buttonText: '',
  jobNumber: ''
})

const valueDisabled = computed(() => {
  // 1-待执行，2-执行中，3-失败，4-已结束
  return formData.value.status  > 1
})

// 出价金额（元）
const bidAmountYuan = computed({
  get: () => formData.value.bidAmount / 100,
  set: (val) => {
    // 保留两位小数，然后转换为分
    formData.value.bidAmount = Math.round(val * 100)
  }
})
const sortedDramaList = computed(() => {
  if (dramaSort.value === 1) {
    return dramaList.value.sort((a, b) => b.marketingAssetId - a.marketingAssetId)
  } else {
    return dramaList.value.sort((a, b) => a.marketingAssetId - b.marketingAssetId)
  }
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入计划名称', trigger: 'blur' }
  ],
  accountGroupId: [
    { required: true, message: '请输入账号组ID', trigger: 'blur' }
  ],
  adType: [
    { required: true, message: '请选择广告类型', trigger: 'change' }
  ],
  bidAmount: [
    { required: true, message: '请输入出价金额', trigger: 'blur' }
  ],
  conversionId: [
    { required: true, message: '请输入转化ID', trigger: 'blur' }
  ],
  wxCorpid: [
    { required: true, message: '请输入企微主体ID', trigger: 'blur' }
  ],
  assetType: [
    { required: true, message: '请选择资产类型', trigger: 'change' }
  ],
  assetModel: [
    { required: true, message: '请选择资产模型', trigger: 'change' }
  ],
  dramaAmount: [
    { required: true, message: '请输入短剧每户几部剧', trigger: 'blur' }
  ],
  fictionAmount: [
    { required: true, message: '请输入小说每户几部剧', trigger: 'blur' }
  ],
  pageIdArr: [
    { required: true, message: '请选择落地页', trigger: 'change' }
  ],
  creativeFileArr: [
    { required: true, message: '请选择创意文件', trigger: 'blur' }
  ],
  creativeText: [
    { required: true, message: '请输入创意文案', trigger: 'blur' }
  ],
  brandImageUrl: [
    { required: true, message: '请选择品牌图片', trigger: 'blur' }
  ],
  brandName: [
    { required: true, message: '请输入品牌名称', trigger: 'blur' }
  ],
  buttonText: [
    { required: true, message: '请输入按钮文案', trigger: 'blur' }
  ],
}

const userInfo = ref(null)

// 加载用户信息
const loadUserInfo = () => {
  const storedUserInfo = localStorage.getItem('userInfo')
  if (storedUserInfo) {
    userInfo.value = JSON.parse(storedUserInfo)
  }
}

// 方法
const loadConfList = async () => {
  loading.value = true
  try {
    const params = {
      queryScope: searchForm.value.queryScope,
      name: searchForm.value.name || undefined,
      status: searchForm.value.status || undefined,
      createTimeStart: searchForm.value.createTimeRange?.[0] || undefined,
      createTimeEnd: searchForm.value.createTimeRange?.[1] || undefined
    }
    const res = await getAdPlanConfList(currentPage.value, pageSize.value, params)
    if (res.success) {
      confList.value = res.data?.records || []
      total.value = res.data?.total || 0
    } else {
      ElMessage.error(res.message || '加载配置列表失败')
    }
  } catch (error) {
    console.error('加载配置列表失败:', error)
    ElMessage.error('加载配置列表失败')
  } finally {
    loading.value = false
  }
}

// 查询
const handleSearch = () => {
  currentPage.value = 1
  loadConfList()
}

// 重置
const handleReset = () => {
  searchForm.value = {
    queryScope: 1,
    name: '',
    status: null,
    createTimeRange: []
  }
  currentPage.value = 1
  loadConfList()
}

const getAdTypeText = (type) => {
  const typeMap = {
    1: '企微',
    2: 'ROI'
  }
  return typeMap[type] || '未知'
}

const getAssetTypeText = (type) => {
  const typeMap = {
    1: '短剧',
    2: '小说',
    3: '混合'
  }
  return typeMap[type] || '未知'
}

const getAssetModelText = (type) => {
  const typeMap = {
    1: '随机',
    2: '最新'
  }
  return typeMap[type] || '未知'
}
const getAdTypeColor = (type) => {
  const colorMap = {
    1: 'success',
    2: 'warning'
  }
  return colorMap[type] || 'info'
}

//计划状态：1-待执行，2-执行中，3-失败，4-已结束
const getPlanStatusText = (status) => {
  const statusMap = {
    1: '待执行',
    2: '执行中',
    3: '失败',
    4: '已结束',
    5: '部分失败'
  }
  return statusMap[status] || '未知'
}

const getPlanStatusColor = (status) => {
  const colorMap = {
    1: 'info',
    2: 'success',
    3: 'danger',
    4: 'success',
    5: 'warning'
  }
  return colorMap[status] || 'info'
}

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

const handleAdTypeChange = () => {
  // 切换广告类型时清空相关字段
  if (formData.value.adType === 1) {
    formData.value.dramaId = null
  } else if (formData.value.adType === 2) {
    formData.value.wxCorpid = ''
  }
}

const addOneCreativeImage = async () => {
  const oldIds = formData.value.creativeFileArr.map(file => file.id)
  const creativeImage = await getOneCreativeImage(oldIds)
  if (creativeImage.success) {
    formData.value.creativeFileArr.push(creativeImage.data)
    const urls = formData.value.creativeFileArr.map(file => file.fileUrl).join(',')
    // 去除文件后缀
    const fileNames = formData.value.creativeFileArr.map(file => file.originalFileName.split('.').slice(0, -1).join('.')).join(',')
    formData.value.creativeFileUrls = urls
    formData.value.creativeFileNames = fileNames
  }
}

const addOneCreativeVideo = async () => {
  const oldIds = formData.value.creativeFileArr.map(file => file.id)
  const creativeVideo = await getOneCreativeVideo(oldIds)
  if (creativeVideo.success) {
    formData.value.creativeFileArr.push(creativeVideo.data)
    const urls = formData.value.creativeFileArr.map(file => file.fileUrl).join(',')
    // 去除文件后缀
    const fileNames = formData.value.creativeFileArr.map(file => file.originalFileName.split('.').slice(0, -1).join('.')).join(',')
    formData.value.creativeFileUrls = urls
    formData.value.creativeFileNames = fileNames
  }
}

const randomOneBrandImage = async () => {
  const brandImage = await getOneBrandImage()
  if (brandImage.success) {
    formData.value.brandImageFile = brandImage.data
    formData.value.brandImageUrl = brandImage.data.fileUrl
  }
}

const handleCreate = async () => {
  //1,2,3,4,5,6,7,8,9,10,11
  //随机一个1-11
  const name = userInfo.value.name + dayjs().format('MMDDHH')
  const createImage = await getOneCreativeImage([])
  console.log(createImage)
  let creativeFileArr = []
  let creativeFileUrls = ''
  let creativeFileNames = ''
  if (createImage.success) {
    creativeFileArr = [createImage.data]
    creativeFileUrls = createImage.data.fileUrl
    creativeFileNames = createImage.data.originalFileName
  }

  const brandImage = await getOneBrandImage()
  let brandImageFile = null
  let brandImageUrl = ''
  if (brandImage.success) {
    brandImageFile = brandImage.data
    brandImageUrl = brandImage.data.fileUrl
  }

  let myLoadPageList = toRaw(loadPageList.value).filter(page => page.createUserId === userInfo.value.id)
  console.log(myLoadPageList)
  let pageIdArr = []
  let pageIds = ''
  if (myLoadPageList.length > 0) {
    pageIdArr = [myLoadPageList[0].pageId]
    pageIds = myLoadPageList[0].pageId + ''
  }

  let accountGroupId = toRaw(accountGroupList.value)[0].id
  

  const site = Math.floor(Math.random() * 11) + 1
  dialogTitle.value = '创建配置'
  editingId.value = null
  formData.value = {
    name: name,
    accountGroupId: accountGroupId,
    adType: 2,
    bidAmount: 150,
    deepConversionWorthRate: 50.00,
    conversionId: null,
    targets: '1',
    sites: site + '',
    wxCorpid: '',
    dramaId: null,
    dramaAmount: 0,
    assetType: 1,
    assetModel: 1,
    fictionAmount: 0,
    imageIds: '',
    pageIds: pageIds,
    pageIdArr: pageIdArr,
    creativeFileArr: creativeFileArr,
    creativeFileUrls: creativeFileUrls,
    creativeFileNames: creativeFileNames,
    brandImageFile: brandImageFile,
    brandImageUrl: brandImageUrl,
    creativeText: '情感美文点点看',
    brandName: '情感美文',
    buttonText: '查看详情',
    jobNumber: '',
    status: 1
  }
  plans.value = []
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogTitle.value = '编辑配置'
  editingId.value = row.id
  formData.value = {
    name: row.name,
    accountGroupId: row.accountGroupId,
    adType: row.adType,
    bidAmount: row.bidAmount,
    deepConversionWorthRate: row.deepConversionWorthRate,
    conversionId: row.conversionId,
    targets: row.targets,
    sites: row.sites,
    wxCorpid: row.wxCorpid || '',
    dramaId: row.dramaId,
    dramaAmount: row.dramaAmount || 0,
    assetType: row.assetType || 1,
    assetModel: row.assetModel || 1,
    fictionAmount: row.fictionAmount || 0,
    imageIds: row.imageIds || '',
    pageIds: row.pageIds || '',
    pageIdArr: row.pageIds ? row.pageIds.split(',').map(Number) : [],
    creativeFileUrls: row.creativeFileUrls || '',
    creativeFileNames: row.creativeFileNames || '',
    creativeFileArr: row.creativeFiles ? JSON.parse(row.creativeFiles) : [],
    brandImageFile: row.brandImageFile ? JSON.parse(row.brandImageFile) : null,
    brandImageUrl: row.brandImageUrl || '',
    creativeText: row.creativeText || '',
    brandName: row.brandName || '',
    buttonText: row.buttonText || '',
    jobNumber: row.jobNumber || '',
    status: row.status
  }
  plans.value = []
  dialogVisible.value = true
}

const goToDetail = (row) => {
  // 跳转到详情页面
  router.push({ path: '/ad-plan-conf/detail', query: { id: row.id } })
}

const copyConf = (row) => {
  dialogTitle.value = '复制配置'
  editingId.value = null
  const conf = { ...row }
  conf.pageIdArr = row.pageIds ? row.pageIds.split(',').map(Number) : [],
    conf.creativeFileUrls = row.creativeFileUrls || '',
    conf.creativeFileNames = row.creativeFileNames || '',
    conf.creativeFileArr = row.creativeFiles ? JSON.parse(row.creativeFiles) : [],
    conf.brandImageFile = row.brandImageFile ? JSON.parse(row.brandImageFile) : null
  delete conf.id
  formData.value = {
    ...conf,
    name: row.name + ' (复制)'
  }
  plans.value = []
  dialogVisible.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除配置"${row.name}"吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    const res = await deleteAdPlanConf(row.id)
    if (res.success) {
      ElMessage.success('删除成功')
      await loadConfList()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  })
}


const handleReCreate = async () => {
  await formRef.value.validate()
  console.log(formData.value)
  const { adType, dramaId, dramaAmount } = formData.value
  const res = await reCreateAdPlanConf(formData.value)
  if (res.success) {
    ElMessage.success('预览成功')
    console.log(res.data)
    expandedRows.value = [res.data[0].adgroupName]
    plans.value = res.data
  } else {
    ElMessage.error(res.message || '预览失败')
  }
}

const generatePlanBtnLoading = ref(false)

const handleGeneratePlan = async () => {
    await formRef.value.validate()
    const { adType, dramaId, dramaAmount } = formData.value
    const data = { ...formData.value }
    data.id = editingId.value
    data.pageIds = data.pageIdArr.join(',')
    generatePlanBtnLoading.value = true
    const res = await generatePlan(data)
  if (res.success) {
    ElMessage.success('生成中')
    console.log(res.data)
    dialogVisible.value = false
    router.push({ path: '/ad-plan-conf/detail', query: { id: res.data.id } })
  } else {
    ElMessage.error(res.message || '生成失败')
  }
  generatePlanBtnLoading.value = false
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    const { adType, dramaId, dramaAmount } = formData.value
    if (adType === 2) {
      if (dramaId == null &&  dramaAmount < 1) {
        ElMessage.warning('请设置短剧配置')
        return
      }
    }
    submitting.value = true
    const data = { ...formData.value }
    data.pageIds = data.pageIdArr.join(',')

    let res
    if (editingId.value) {
      // 编辑
      data.id = editingId.value
      res = await updateAdPlanConf(data)
    } else {
      // 创建
      res = await createAdPlanConf(data)
    }

    if (res.success) {
      ElMessage.success(editingId.value ? '更新成功' : '创建成功')
      await loadConfList()
    } else {
      ElMessage.error(res.message || '操作失败')
    }
  } catch (error) {
    if (error !== false) {
      console.error('提交失败:', error)
      ElMessage.error('操作失败')
    }
  } finally {
    submitting.value = false
  }
}

const handleDialogClose = () => {
  formRef.value?.resetFields()
}

const loadConversions = async () => {
  const res = await getConversions()
  if (res.success) {
    conversions.value = res.data
  } else {
    ElMessage.error(res.message || '加载转化列表失败')
  }
}

const loadAccountGroupList = async () => {
  const res = await getAccountGroupListAll()
  if (res.success) {
    accountGroupList.value = res.data
  } else {
    ElMessage.error(res.message || '加载账号组列表失败')
  }
}

// 打开文件选择器
const openFileSelector = (type) => {
  currentFileType.value = type
  if (type === 'creative') {
    fileSelectorTitle.value = '选择创意图片/视频'
    fileSearchParams.value.businessType = 1
  } else if (type === 'brand') {
    fileSelectorTitle.value = '选择品牌形象图片'
    fileSearchParams.value.businessType = 2
  }
  fileSelectorVisible.value = true
  loadFileList()
}

// 加载文件列表
const loadFileList = async () => {
  fileLoading.value = true
  try {
    const res = await getFileList(fileSearchParams.value)
    if (res.success) {
      fileList.value = res.data.records || []
      fileTotal.value = res.data.total || 0
    } else {
      ElMessage.error(res.message || '加载文件列表失败')
    }
  } catch (error) {
    console.error('加载文件列表失败:', error)
    ElMessage.error('加载文件列表失败')
  } finally {
    fileLoading.value = false
  }
}

// 文件列表排序变化
const handleFileSortChange = ({ prop, order }) => {
  if (order) {
    fileSearchParams.value.sortField = prop
    fileSearchParams.value.sortOrder = order
  } else {
    fileSearchParams.value.sortField = 'normalCnt'
    fileSearchParams.value.sortOrder = 'descending'
  }
  loadFileList()
}

// 处理文件选择
const handleFileSelectionChange = (selection) => {
  selectedFiles.value = selection
}

// 确认文件选择
const confirmFileSelection = () => {
  if (selectedFiles.value.length === 0) {
    ElMessage.warning('请至少选择一个文件')
    return
  }

  if (currentFileType.value === 'brand' && selectedFiles.value.length > 1) {
    ElMessage.warning('品牌形象图片只能选择1张')
    return
  }

  const urls = selectedFiles.value.map(file => file.fileUrl).join(',')
  // 去除文件后缀
  const fileNames = selectedFiles.value.map(file => file.originalFileName.split('.').slice(0, -1).join('.')).join(',')

  if (currentFileType.value === 'creative') {
    formData.value.creativeFileUrls = urls
    formData.value.creativeFileNames = fileNames
    formData.value.creativeFileArr = selectedFiles.value
  } else if (currentFileType.value === 'brand') {
    formData.value.brandImageUrl = selectedFiles.value[0].fileUrl
    formData.value.brandImageFile = selectedFiles.value[0]
  }

  fileSelectorVisible.value = false
  selectedFiles.value = []
}

// 移除文件
const removeFile = (type, index) => {
  if (type === 'creative') {
    const arr = toRaw(formData.value.creativeFileArr)
    arr.splice(index, 1)
    debugger
    formData.value.creativeFileArr = [...arr]
    debugger
    formData.value.creativeFileUrls = arr.map(file => file.fileUrl).join(',')
    debugger
    formData.value.creativeFileNames = arr.map(file => file.originalFileName).join(',')
    debugger
  } else if (type === 'brand') {
    formData.value.brandImageUrl = ''
    formData.value.brandImageFile = null
  }
}

// 获取文件名
const getFileName = (url) => {
  if (!url) return ''
  const parts = url.split('/')
  return parts[parts.length - 1] || url.substring(0, 20) + '...'
}

// 预览文件
const previewFile = (url) => {
  previewUrl.value = url
  previewVisible.value = true
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (!bytes) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i]
}

const loadDramaList = async () => {
  try {
    const res = await myDramaAssetList()
    if (res.success) {
      dramaList.value = res.data
    } else {
      ElMessage.error(res.message || '加载短剧列表失败')
    }
  } catch (error) {
    console.error('加载短剧列表失败:', error)
    ElMessage.error('加载短剧列表失败')
  } finally {
  }
}

const loadLoadPageList = async () => {
  const res = await getAllLoadPageConf()
  if (res.success) {
    loadPageList.value = res.data
  } else {
    ElMessage.error(res.message || '加载落地页列表失败')
  }
}

// 监听分页变化
watch([currentPage, pageSize], () => {
  loadConfList()
})

// 生命周期
onMounted(() => {
  loadConfList()
  loadConversions()
  loadAccountGroupList()
  loadDramaList()
  loadLoadPageList()
  loadUserInfo()
})
</script>

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