<template>
  <div class="campaign-task-container">
    <!-- Filter section -->
    <div class="filter-section">
      <el-form :inline="true" :model="condition" class="filter-form">
        <el-form-item label="计划模板">
          <campaign-template-selector
            v-model="condition.campaignTemplateId"
            @change="handleTemplateChange"
          />
        </el-form-item>

        <el-form-item label="状态">
          <el-select
            v-model="condition.status"
            placeholder="请选择状态"
            clearable
            @change="handleStatusChange">
            <el-option label="未执行" :value="1"></el-option>
            <el-option label="执行中" :value="2"></el-option>
            <el-option label="执行成功" :value="3"></el-option>
            <el-option label="执行失败" :value="4"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="日期范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            @change="handleDateChange">
          </el-date-picker>
        </el-form-item>
      </el-form>
    </div>

    <el-divider></el-divider>

    <!-- Table Header actions -->
    <div class="header-actions">
      <el-button type="primary" @click="showAddDialog">创建任务</el-button>
      <div class="header-right">
        <el-button icon="el-icon-refresh" @click="fetchData">刷新</el-button>
      </div>
    </div>

    <!-- Main table -->
    <el-table
      :data="tableData"
      border
      style="width: 100%"
      v-loading="loading">
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="campaignTemplateId" label="计划模板" width="250">
        <template slot-scope="scope">
          {{ getTemplateName(scope.row.campaignTemplateId) }}
        </template>
      </el-table-column>

      <el-table-column prop="campaignNameList" label="计划名称" width="200">
        <template slot-scope="scope">
          <div v-if="scope.row.campaignNameList" class="campaign-names">
            <div 
              v-for="(name, index) in scope.row.campaignNameList.split(',')" 
              :key="index" 
              class="campaign-name-item">
              {{ name.trim() }}
            </div>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>

      <el-table-column prop="accountName" label="账户名称" width="150">
        <template slot-scope="scope">
          {{ scope.row.accountName || '-' }}
        </template>
      </el-table-column>

      <el-table-column prop="startTime" label="开始时间" width="180">
        <template slot-scope="scope">
          {{ scope.row.startTime ? moment(scope.row.startTime).format('YYYY-MM-DD HH:mm:ss') : '' }}
        </template>
      </el-table-column>
      <el-table-column prop="finishTime" label="结束时间" width="180">
        <template slot-scope="scope">
          {{ scope.row.finishTime ? moment(scope.row.finishTime).format('YYYY-MM-DD HH:mm:ss') : '' }}
        </template>
      </el-table-column>
      <el-table-column label="执行时间" width="150">
        <template slot-scope="scope">
          {{ calculateDuration(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" sortables>
        <template slot-scope="scope">
          <el-tag
            :type="getStatusType(scope.row.status)"
            :class="{'clickable-tag': scope.row.status === 3 || scope.row.status === 4}"
            @click="(scope.row.status === 3 || scope.row.status === 4) && showErrorMessage(scope.row)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <div class="operation-buttons">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              circle
              title="编辑"
              @click="handleEdit(scope.row)"></el-button>
            <el-button
              size="mini"
              type="info"
              icon="el-icon-view"
              circle
              title="详情"
              @click="handleDetail(scope.row)"></el-button>
            <el-button
              v-if="scope.row.status === 1 || scope.row.status === 4"
              size="mini"
              type="success"
              icon="el-icon-video-play"
              circle
              title="开始"
              :loading="startLoading"
              @click="handleStart(scope.row)"></el-button>
            <el-button
              v-else
              size="mini"
              type="success"
              icon="el-icon-video-play"
              circle
              title="开始"
              disabled></el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        :total="total"
        layout="total, prev, pager, next, sizes">
      </el-pagination>
    </div>

    <!-- Add/Edit Dialog -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="70%">
      <el-form :model="form" :rules="rules" ref="form" label-width="120px">
        <!-- 新增：选择模板类型 -->
        <el-form-item label="模板类型" prop="templateType">
          <el-radio-group v-model="form.templateType" @change="handleTemplateTypeChange">
            <el-radio :label="1">使用现有模板</el-radio>
            <el-radio :label="2">创建临时模板</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 选择现有模板 -->
        <el-form-item label="计划模板" prop="campaignTemplateId" v-if="form.templateType === 1">
          <campaign-template-selector
            v-model="form.campaignTemplateId"
            @change="handleTemplateSelectorChange"
          />
        </el-form-item>

        <!-- 模板详情展示区域 -->
        <div v-if="form.templateType === 1 && selectedTemplate" class="template-details">
          <el-divider content-position="left">模板详情（可修改）</el-divider>

          <el-form-item label="模板名称">
            <el-input v-model="form.tempName" :placeholder="selectedTemplate.name" disabled></el-input>
          </el-form-item>

          <el-form-item label="平台" prop="platform">
            <el-select v-model="form.platform" placeholder="请选择平台" @change="handlePlatformChange">
              <el-option label="Google" :value="1"></el-option>
              <el-option label="TikTok" :value="2"></el-option>
              <el-option label="Facebook" :value="3"></el-option>
            </el-select>
          </el-form-item>

          <!-- TikTok特定字段 -->
          <template v-if="form.platform === 2">
            <el-form-item label="智能创建" prop="tiktok_json.isSmart">
              <el-switch
                v-model="form.tiktok_json.isSmart"
                :active-text="'开启'"
                :inactive-text="'关闭'">
              </el-switch>
            </el-form-item>

            <el-form-item
              label="选择账户"
              prop="tiktok_json.advertiserId">
              <el-select
                v-model="form.tiktok_json.advertiserId"
                placeholder="请选择账户"
                filterable
                :loading="advertiserLoading"
                @change="handleAdvertiserChange">
                <el-option
                  v-for="item in advertiserOptions"
                  :key="item.advertiserId"
                  :label="item.advertiserName"
                  :value="item.advertiserId">
                  <span style="float: left">{{ item.advertiserName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.advertiserId }}</span>
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="优化目标" prop="tiktok_json.optimizationGoal">
              <el-select v-model="form.tiktok_json.optimizationGoal" placeholder="请选择优化目标" @change="handleOptimizationGoalChange">
                <el-option label="价值" value="VALUE"></el-option>
                <el-option label="安装" value="INSTALL"></el-option>
              </el-select>
            </el-form-item>

            <!-- 级联优化事件选择框 -->
            <el-form-item
              label="优化事件"
              prop="tiktok_json.optimizationEvent"
              v-if="form.tiktok_json.optimizationGoal === 'VALUE'">
              <el-select v-model="form.tiktok_json.optimizationEvent" placeholder="请选择优化事件">
                <el-option label="应用内购价值" value="ACTIVE_PAY"></el-option>
                <el-option label="广告收入价值" value="AD_REVENUE_VALUE"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item
              label="深度出价类型"
              prop="tiktok_json.deepBidType"
              v-if="form.tiktok_json.optimizationGoal === 'VALUE'">
              <el-select v-model="form.tiktok_json.deepBidType" placeholder="请选择深度出价类型" @change="handleDeepBidTypeChange">
                <el-option label="最小ROAS" value="VO_MIN_ROAS"></el-option>
                <el-option label="最高价值" value="VO_HIGHEST_VALUE"></el-option>
              </el-select>
            </el-form-item>

            <!-- ROAS目标值输入框 -->
            <el-form-item
              label="ROAS目标值"
              prop="tiktok_json.roasBid"
              v-if="form.tiktok_json.optimizationGoal === 'VALUE' && form.tiktok_json.deepBidType === 'VO_MIN_ROAS'">
              <el-input-number
                v-model="form.tiktok_json.roasBid"
                :min="0.01"
                :max="1000"
                :precision="2"
                placeholder="请输入ROAS目标值">
              </el-input-number>
            </el-form-item>

            <!-- 价值优化窗口期选择框 -->
<!--            <el-form-item -->
<!--              label="价值优化窗口期" -->
<!--              prop="tiktok_json.vboWindow"-->
<!--              v-if="form.tiktok_json.optimizationGoal === 'VALUE'">-->
<!--              <el-select v-model="form.tiktok_json.vboWindow" placeholder="请选择价值优化窗口期">-->
<!--                <el-option label="前7天" value="SEVEN_DAYS"></el-option>-->
<!--                <el-option label="第0天（当天）" value="ZERO_DAY"></el-option>-->
<!--              </el-select>-->
<!--            </el-form-item>-->

<!--            <el-form-item label="深度CPA出价" prop="tiktok_json.deepCpaBid">-->
<!--              <el-input-number v-model="form.tiktok_json.deepCpaBid" :min="0" :precision="2"></el-input-number>-->
<!--            </el-form-item>-->

<!--            <el-form-item label="投放位置" prop="tiktok_json.placements">-->
<!--              <el-select v-model="form.tiktok_json.placements" multiple placeholder="请选择投放位置">-->
<!--                <el-option label="TikTok" value="PLACEMENT_TIKTOK"></el-option>-->
<!--                <el-option label="Pangle" value="PLACEMENT_PANGLE"></el-option>-->
<!--                <el-option label="Global App Bundle" value="PLACEMENT_GLOBAL_APP_BUNDLE"></el-option>-->
<!--              </el-select>-->
<!--            </el-form-item>-->

            <el-form-item label="是否新建计划" prop="tiktok_json.isNewCampaign">
              <el-switch
                v-model="form.tiktok_json.isNewCampaign"
                active-text="是"
                inactive-text="否">
              </el-switch>
            </el-form-item>

            <template v-if="!form.tiktok_json.isNewCampaign">
              <el-form-item
                label="选择已有计划"
                prop="tiktok_json.campaignIdList"
                v-if="form.tiktok_json.advertiserId">
                <el-select
                  v-model="form.tiktok_json.campaignIdList"
                  multiple
                  filterable
                  placeholder="请输入计划名称搜索"
                  :loading="campaignListLoading"
                  @change="handleCampaignSelectionChange"
                  style="width: 100%">
                  <el-option
                    v-for="item in campaignOptions"
                    :key="item.campaignId"
                    :label="item.campaignName"
                    :value="item.campaignId">
                    <span style="float: left">{{ item.campaignName }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">{{ item.campaignId }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </template>

            <!-- 多计划独立配置区域 -->
            <div v-if="!form.tiktok_json.isNewCampaign && form.tiktok_json.campaignIdList && form.tiktok_json.campaignIdList.length > 0" class="multi-campaign-config">
              <el-divider content-position="left">计划独立配置</el-divider>
              <div class="campaign-config-list">
                <div 
                  v-for="(campaignId, index) in form.tiktok_json.campaignIdList" 
                  :key="campaignId" 
                  class="campaign-config-item">
                  <div class="campaign-config-header">
                    <h4>{{ getCampaignName(campaignId) }}</h4>
                    <el-button 
                      type="danger" 
                      size="mini" 
                      icon="el-icon-delete" 
                      @click="removeCampaignConfig(index)"
                      v-if="form.tiktok_json.campaignIdList.length > 1">
                      移除
                    </el-button>
                  </div>
                  
                  <el-form :model="campaignConfigs[index]" label-width="120px" size="small">
                    <!-- ROAS目标值 -->
                    <el-form-item label="ROAS目标值" v-if="form.tiktok_json.optimizationGoal === 'VALUE' && form.tiktok_json.deepBidType === 'VO_MIN_ROAS'">
                      <el-input-number
                        v-model="campaignConfigs[index].roasBid"
                        :min="0.01"
                        :max="1000"
                        :precision="2"
                        placeholder="请输入ROAS目标值"
                        style="width: 200px;">
                      </el-input-number>
                    </el-form-item>

                    <!-- 日预算 -->
                    <el-form-item label="日预算($)">
                      <el-input-number
                        v-model="campaignConfigs[index].dailyBudget"
                        :min="20"
                        placeholder="请输入日预算"
                        style="width: 200px;">
                      </el-input-number>
                    </el-form-item>


                    <!-- 地域组 -->
                    <el-form-item label="地域组">
                      <location-group-selector 
                        v-model="campaignConfigs[index].locationGroups" 
                        @change="handleCampaignLocationGroupsChange(index, $event)" />
                      <!-- 展示已选地域组列表 -->
                      <div v-if="campaignConfigs[index].locationGroups && campaignConfigs[index].locationGroups.length > 0" class="group-detail-container">
                        <div class="group-detail-title">已选地域组列表</div>
                        <el-table :data="getCampaignLocationGroupData(index)" size="mini" border style="width: 100%">
                          <el-table-column prop="name" label="地域组名称"></el-table-column>
                          <el-table-column prop="id" label="地域组ID"></el-table-column>
                          <el-table-column label="国家数量">
                            <template slot-scope="scope">
                              {{ getLocationGroupCountries(scope.row).length }} 个国家
                            </template>
                          </el-table-column>
                          <el-table-column label="计划数" width="200" align="center">
                            <template slot-scope="scope">
                              <el-input-number v-model="scope.row.campaignCount" :min="1" @change="updateCampaignLocationGroupCampaignCount(index, scope.row, $event)" size="mini"></el-input-number>
                            </template>
                          </el-table-column>
                        </el-table>
                      </div>
                    </el-form-item>

                    <!-- 标题组 -->
                    <el-form-item label="标题组">
                      <title-group-selector v-model="campaignConfigs[index].titleGroups" />
                    </el-form-item>

                    <!-- 素材组 -->
                    <el-form-item label="素材组">
                      <material-group-selector v-model="campaignConfigs[index].materialGroups" />
                    </el-form-item>

                    <!-- 资源组 -->
                    <el-form-item label="资源组">
                      <resource-group-selector v-model="campaignConfigs[index].resourceGroups" />
                    </el-form-item>
                  </el-form>
                </div>
              </div>
            </div>

            <el-form-item
              label="设备机型"
              prop="tiktok_json.deviceModels"
              v-if="form.tiktok_json.advertiserId">
              <el-select
                v-model="form.tiktok_json.deviceModels"
                multiple
                filterable
                placeholder="请选择设备机型"
                :loading="deviceModelLoading"
                style="width: 100%">
                <el-option
                  v-for="item in deviceModelOptions"
                  :key="item.device_model_id"
                  :label="item.device_model_name"
                  :value="item.device_model_id">
                  <span style="float: left">{{ item.device_model_name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.device_model_id }}</span>
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item
              label="最小安卓系统版本"
              prop="tiktok_json.minAndroidVersion">
              <el-select
                v-model="form.tiktok_json.minAndroidVersion"
                placeholder="请选择最小安卓系统版本"
                style="width: 100%">
                <el-option
                  v-for="item in androidVersionOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </template>

          <el-form-item label="广告系列类型" prop="campaign_type">
            <el-select v-model="form.campaign_type" placeholder="请选择">
              <el-option label="应用安装" :value="1"></el-option>
              <el-option label="应用互动" :value="2"></el-option>
              <el-option label="应用预注册" :value="3"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="移动应用平台" prop="appStore">
            <el-select v-model="form.appStore" placeholder="请选择">
              <el-option label="iOS" :value="2"></el-option>
              <el-option label="Android" :value="3"></el-option>
            </el-select>
          </el-form-item>

          <!-- 日预算（当没有多计划自定义时显示） -->
          <el-form-item label="日预算($)" prop="daily_budget" v-if="form.tiktok_json.isNewCampaign || !form.tiktok_json.campaignIdList || form.tiktok_json.campaignIdList.length === 0">
            <el-input-number v-model="form.daily_budget" :min="0"></el-input-number>
          </el-form-item>

          <el-form-item label="转化目标" prop="bidding_type" v-if="form.platform !== 2">
            <el-select v-model="form.bidding_type" placeholder="请选择">
              <el-option label="安装量" :value="2" :disabled="true"></el-option>
              <el-option label="应用内操作次数" :value="3" :disabled="true"></el-option>
              <el-option label="应用内操作价值" :value="5"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="目标考核ROAS(%)" prop="target_roas" v-if="form.platform !== 2">
            <el-input-number v-model="form.target_roas" :min="0"></el-input-number>
          </el-form-item>

          <el-form-item label="应用组" prop="app_groups">
            <app-group-selector v-model="form.app_groups" @change="handleAppGroupsChange" />
            <!-- 展示应用组下的所有应用 -->
            <div v-if="form.app_groups && form.app_groups.length > 0" class="group-detail-container">
              <div class="group-detail-title">
                应用组中的应用列表
                <el-button type="primary" size="mini" @click="showAddAppDialog" icon="el-icon-plus" style="float: right;">添加应用</el-button>
              </div>
              <el-table :data="appListData" size="mini" border style="width: 100%">
                <el-table-column prop="name" label="应用名称"></el-table-column>
                <el-table-column prop="appId" label="包名"></el-table-column>

                <el-table-column label="计划数" width="200" align="center">
                  <template slot-scope="scope">
                    <el-input-number v-model="scope.row.campaignCount" :min="1" @change="updateAppCampaignCount(scope.row, $event)" size="mini"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="80" align="center">
                  <template slot-scope="scope">
                    <el-button type="danger" size="mini" icon="el-icon-delete" circle @click="removeApp(scope.row)"></el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-form-item>

          <!-- 地域组（当没有多计划自定义时显示） -->
          <el-form-item label="地域组" prop="location_groups" v-if="form.tiktok_json.isNewCampaign || !form.tiktok_json.campaignIdList || form.tiktok_json.campaignIdList.length === 0">
            <location-group-selector v-model="form.location_groups" @change="handleLocationGroupsChange" />
            <!-- 展示已选地域组列表 -->
            <div v-if="form.location_groups && form.location_groups.length > 0" class="group-detail-container">
              <div class="group-detail-title">已选地域组列表</div>
              <el-table :data="selectedLocationGroups" size="mini" border style="width: 100%">
                <el-table-column prop="name" label="地域组名称"></el-table-column>
                <el-table-column prop="id" label="地域组ID"></el-table-column>
                <el-table-column label="国家数量">
                  <template slot-scope="scope">
                    {{ getLocationGroupCountries(scope.row).length }} 个国家
                  </template>
                </el-table-column>
                <el-table-column label="计划数" width="200" align="center">
                  <template slot-scope="scope">
                    <el-input-number v-model="scope.row.campaignCount" :min="1" @change="updateLocationGroupCampaignCount(scope.row, $event)" size="mini"></el-input-number>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-form-item>

          <!-- 素材组、标题组、描述组、资源组（当没有多计划自定义时显示） -->
          <template v-if="form.tiktok_json.isNewCampaign || !form.tiktok_json.campaignIdList || form.tiktok_json.campaignIdList.length === 0">
            <el-form-item label="素材组" prop="material_groups">
              <material-group-selector v-model="form.material_groups" />
            </el-form-item>

            <el-form-item label="标题组" prop="title_groups">
              <title-group-selector v-model="form.title_groups" />
            </el-form-item>

            <el-form-item label="描述组" prop="description_groups">
              <description-group-selector v-model="form.description_groups" />
            </el-form-item>

            <el-form-item label="资源组" prop="resource_groups">
              <resource-group-selector v-model="form.resource_groups" />
            </el-form-item>
          </template>
        </div>

        <!-- 临时模板表单 -->
        <template v-if="form.templateType === 2">
          <el-form-item label="模板名称" prop="tempTemplateName">
            <el-input v-model="form.tempTemplateName"></el-input>
          </el-form-item>

          <el-form-item label="广告系列类型" prop="campaign_type">
            <el-select v-model="form.campaign_type" placeholder="请选择">
              <el-option label="应用安装" :value="1"></el-option>
              <el-option label="应用互动" :value="2"></el-option>
              <el-option label="应用预注册" :value="3"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="移动应用平台" prop="appStore">
            <el-select v-model="form.appStore" placeholder="请选择">
              <el-option label="iOS" :value="2"></el-option>
              <el-option label="Android" :value="3"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="日预算" prop="daily_budget">
            <el-input-number v-model="form.daily_budget" :min="0"></el-input-number>
          </el-form-item>

          <el-form-item label="转化目标" prop="bidding_type" v-if="form.platform !== 2">
            <el-select v-model="form.bidding_type" placeholder="请选择">
              <el-option label="安装量" :value="2" :disabled="true"></el-option>
              <el-option label="应用内操作次数" :value="3" :disabled="true"></el-option>
              <el-option label="应用内操作价值" :value="5"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="目标考核ROAS" prop="target_roas" v-if="form.platform !== 2">
            <el-input-number v-model="form.target_roas" :min="0"></el-input-number>
          </el-form-item>

          <el-form-item label="应用组" prop="app_groups">
            <app-group-selector v-model="form.app_groups" @change="handleAppGroupsChange" />
          </el-form-item>

          <el-form-item label="地域组" prop="location_groups">
            <location-group-selector v-model="form.location_groups" @change="handleLocationGroupsChange" />
          </el-form-item>

          <el-form-item label="素材组" prop="material_groups">
            <material-group-selector v-model="form.material_groups" />
          </el-form-item>

          <el-form-item label="标题组" prop="title_groups">
            <title-group-selector v-model="form.title_groups" />
          </el-form-item>

          <el-form-item label="描述组" prop="description_groups">
            <description-group-selector v-model="form.description_groups" />
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 计划任务详情对话框 -->
    <el-dialog
      title="计划任务详情"
      :visible.sync="detailVisible"
      width="80%"
    >
      <div class="header-actions">
        <el-button type="primary" @click="showAddDialog">创建任务</el-button>
        <div class="header-right">
          <el-button icon="el-icon-refresh" @click="refreshDetail" :loading="detailLoading">刷新</el-button>
        </div>
      </div>
      <el-table :data="currentTaskDetail" border :loading="detailLoading">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="appName" label="产品" width="200" align="center" sortable></el-table-column>
        <el-table-column prop="advertiserId" label="账户ID" align="center" sortable></el-table-column>
        <el-table-column prop="campaignId" label="计划ID" align="center" sortable></el-table-column>
        <el-table-column prop="campaignName" label="计划名称" align="center" width="200" sortable></el-table-column>
        <el-table-column prop="adgroupId" label="广告组ID" align="center" sortable></el-table-column>
        <el-table-column label="投放国家" min-width="150" sortable>
          <template slot-scope="scope">
            <div class="table-countries-container">
              <template v-if="scope.row.countryCodes && scope.row.countryCodes.length > 0">
                <el-tag
                  v-for="(country, index) in typeof scope.row.countryCodes === 'string' ?
                    JSON.parse(scope.row.countryCodes) : scope.row.countryCodes"
                  :key="country"
                  v-if="index < 5"
                  size="mini"
                  class="country-tag"
                  type="primary"
                  effect="light">
                  {{ country }}
                </el-tag>
                <span v-if="(typeof scope.row.countryCodes === 'string' ?
                  JSON.parse(scope.row.countryCodes) : scope.row.countryCodes).length > 5"
                  class="more-countries">...</span>
              </template>
              <span v-else class="no-countries-text">无国家信息</span>
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="startTime" label="开始时间" sortable>
          <template slot-scope="scope">
          {{ scope.row.startTime ? moment(scope.row.startTime).format('YYYY-MM-DD HH:mm:ss') : '' }}
        </template>
        </el-table-column> -->
        <!-- <el-table-column prop="finishTime" label="结束时间" sortable>
          <template slot-scope="scope">
          {{ scope.row.finishTime ? moment(scope.row.finishTime).format('YYYY-MM-DD HH:mm:ss') : '' }}
        </template>
        </el-table-column> -->
        <el-table-column label="执行时间" width="150" sortable>
        <template slot-scope="scope">
          {{ calculateDuration(scope.row) }}
        </template>
      </el-table-column>
        <el-table-column prop="status" label="状态" sortables>
          <template slot-scope="scope">
            <el-tag
            :type="getStatusType(scope.row.status)"
            :class="{'clickable-tag': scope.row.status === 3 || scope.row.status === 4}"
            @click="(scope.row.status === 3 || scope.row.status === 4) && showErrorMessage(scope.row)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
          </template>
        </el-table-column>
        <!-- 新增操作列 -->
        <el-table-column label="操作" width="120" align="center">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-data-analysis"
              v-if="scope.row.adInfo"
              @click="showAdInfo(scope.row)">
              广告信息
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 广告信息抽屉 -->
    <el-drawer
      title="广告信息"
      :visible.sync="drawerVisible"
      direction="rtl"
      size="50%"
      :modal-append-to-body="false"
    >
      <div v-if="currentAdInfo" class="drawer-content">
        <!-- 国家信息 -->
        <div class="section-title">投放国家</div>
        <div class="countries-section">
          <template v-if="currentAdInfo.countries && currentAdInfo.countries.length > 0">
            <div v-for="(country, index) in currentAdInfo.countries.slice(0, 10)" :key="country.code" class="country-item">
              <el-tag
                size="small"
                class="country-tag"
                type="primary"
                effect="light">
                {{ country.code }}
              </el-tag>
              <span v-if="index < Math.min(currentAdInfo.countries.length, 10) - 1 && index < 9" class="country-separator">,</span>
            </div>
            <span v-if="currentAdInfo.countries.length > 10" class="more-countries">...</span>
          </template>
          <span v-else class="no-countries">无国家信息</span>
        </div>

        <!-- 标题部分 -->
        <div class="section-title">标题</div>
        <div class="headlines-section">
          <div v-for="(headline, index) in currentAdInfo.headlines" :key="'headline-'+index" class="headline-item">
            <div class="item-content">{{headline.text}}</div>
          </div>
        </div>

        <!-- 描述部分 -->
        <div class="section-title">描述</div>
        <div class="descriptions-section">
          <div v-for="(desc, index) in currentAdInfo.descriptions" :key="'desc-'+index" class="description-item">
            <div class="item-content">{{desc.text}}</div>
          </div>
        </div>

        <!-- 图片部分 -->
        <div class="section-title">图片</div>
        <div class="images-section">
          <div v-for="(imgUrl, index) in currentAdInfo.imageUrls" :key="'img-'+index" class="image-item">
            <img :src="imgUrl" @click="previewImage(imgUrl)" class="thumbnail">
          </div>
        </div>

        <!-- 视频部分 -->
        <div class="section-title">视频</div>
        <div class="videos-section">
          <div v-for="(video, index) in currentAdInfo.videoInfos" :key="'video-'+index" class="video-item">
            <video
              :src="video.url"
              class="video-thumbnail"
              preload="metadata"
              @click="playVideo(video.url)">
            </video>
            <div class="video-name">{{video.name}}</div>
          </div>
        </div>
      </div>
    </el-drawer>

    <!-- 图片预览 -->
    <el-dialog :visible.sync="previewVisible" append-to-body class="preview-dialog">
      <img :src="previewImageUrl" class="preview-image" alt="预览图片">
    </el-dialog>

    <!-- 视频播放 -->
    <el-dialog :visible.sync="videoPlayVisible" append-to-body width="70%" class="video-dialog">
      <video :src="currentVideoUrl" controls autoplay class="video-player"></video>
    </el-dialog>

    <!-- 添加错误信息对话框 -->
    <el-dialog
      title="失败原因"
      :visible.sync="errorMessageVisible"
      width="50%"
      center
    >
      <div class="error-message-content">
        <p v-if="currentErrorMsg">{{ currentErrorMsg }}</p>
        <p v-else class="no-error-message">未提供失败原因</p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="errorMessageVisible = false">关闭</el-button>
      </span>
    </el-dialog>

    <!-- 添加应用对话框 -->
    <el-dialog
      title="选择应用"
      :visible.sync="addAppDialogVisible"
      width="50%"
    >
      <div class="app-selector-container">
        <el-form label-width="120px">
          <el-form-item label="关联应用">
            <el-select
              v-model="selectedAppId"
              filterable
              placeholder="请选择关联应用"
              style="width: 100%"
            >
              <el-option
                v-for="item in selectApps"
                :key="item.id"
                :label="item.label"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addAppDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAddApp" :disabled="!selectedAppId">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getCampaignTaskDetailById, getCampaignTaskDetails, getCampaignTaskDetailList } from '@/api/campaignTaskDetail'
import CampaignTemplateSelector from '@/components/GroupSelectors/CampaignTemplateSelector'
import AppGroupSelector from '@/components/GroupSelectors/AppGroupSelector'
import LocationGroupSelector from '@/components/GroupSelectors/LocationGroupSelector'
import MaterialGroupSelector from '@/components/GroupSelectors/MaterialGroupSelector'
import TitleGroupSelector from '@/components/GroupSelectors/TitleGroupSelector'
import DescriptionGroupSelector from '@/components/GroupSelectors/DescriptionGroupSelector'
import ResourceGroupSelector from '@/components/GroupSelectors/ResourceGroupSelector'
import { getCampaignTaskList, createCampaignTask, updateCampaignTask, deleteCampaignTask, startCampaignTask } from '@/api/campaignTask'
import { getCampaignTemplateById } from '@/api/campaignTemplate'
import { getTikTokDeviceModels } from '@/api/tiktokDevice'
import axios from 'axios'
import moment from 'moment'
import {
  getSelectApps
} from "@/api/cloud";

// 设置moment语言为中文
moment.locale('zh-cn')

export default {
  name: 'CampaignTaskManage',
  components: {
    CampaignTemplateSelector,
    AppGroupSelector,
    LocationGroupSelector,
    MaterialGroupSelector,
    TitleGroupSelector,
    DescriptionGroupSelector,
    ResourceGroupSelector
  },
  data() {
    const end = moment()
    const start = end.clone().subtract(7, 'day')
    return {
      loading: false,
      startLoading: false, // 新增：任务启动loading状态
      condition: {
        templateId: null,
        status: null,
      },
      dateRange: [start.format('YYYY-MM-DD'), end.format('YYYY-MM-DD')],
      tableData: [],
      currentPage: 1,
      pageSize: 50,
      total: 0,
      dialogVisible: false,
      dialogTitle: '',
      form: {
        id: null,
        campaignTemplateId: null,
        templateType: 1,
        tempTemplateName: '',
        tempName: '',
        campaign_type: 1,
        appStore: 2,
        daily_budget: 100,
        bidding_type: 5,
        target_roas: 100,
        app_groups: [],
        location_groups: [],
        material_groups: [],
        title_groups: [],
        description_groups: [],
        resource_groups: [],
        accountName: '', // 新增：账户名称字段
        // 修改字段名为tiktok_json
        tiktok_json: {
          optimizationGoal: 'VALUE',
          optimizationEvent: '', // 新增优化事件字段
          deepBidType: 'VO_MIN_ROAS',
          deepCpaBid: 0,
          roasBid: 0, // 新增ROAS目标值字段
          vboWindow: '', // 新增价值优化窗口期字段
          placements: [],
          isSmart: false,  // 添加isSmart字段,默认为false
          isNewCampaign: true, // 是否新建计划
          advertiserId: '', // 选中的广告主ID
          campaignIdList: [], // 计划ID列表
          deviceModels: [], // 设备机型列表
          minAndroidVersion: 'NONE' // 最小安卓系统版本
        }
      },
      selectedTemplate: null,
      rules: {
        campaignTemplateId: [
          { required: true, message: '请选择计划模板', trigger: 'change' }
        ],
        templateType: [
          { required: true, message: '请选择模板类型', trigger: 'change' }
        ],
        tempTemplateName: [
          { required: true, message: '请输入模板名称', trigger: 'blur' }
        ],
        campaign_type: [
          { required: true, message: '请选择广告系列类型', trigger: 'change' }
        ],
        appStore: [
          { required: true, message: '请选择移动应用平台', trigger: 'change' }
        ],
        daily_budget: [
          { required: true, message: '请输入日预算', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (this.form.platform === 2 && value < 20) {
                callback(new Error('TikTok平台日预算必须大于等于20'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        bidding_type: [
          { required: true, message: '请选择转化目标', trigger: 'change' }
        ],
        target_roas: [
          { required: true, message: '请输入目标考核ROAS', trigger: 'blur' }
        ],
        app_groups: [
          { required: true, type: 'array', message: '请选择应用组', trigger: 'change' }
        ],
        location_groups: [
          { required: true, type: 'array', message: '请选择地域组', trigger: 'change' }
        ],
        // 修改TikTok特定字段的验证规则
        'tiktok_json.optimizationGoal': [
          { required: true, message: '请选择优化目标', trigger: 'change' }
        ],
        'tiktok_json.optimizationEvent': [
          {
            required: true,
            message: '请选择优化事件',
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (this.form.tiktok_json.optimizationGoal === 'VALUE' && !value) {
                callback(new Error('请选择优化事件'));
              } else {
                callback();
              }
            }
          }
        ],
        'tiktok_json.deepBidType': [
          {
            required: true,
            message: '请选择深度出价类型',
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (this.form.tiktok_json.optimizationGoal === 'VALUE' && !value) {
                callback(new Error('请选择深度出价类型'));
              } else {
                callback();
              }
            }
          }
        ],
        'tiktok_json.deepCpaBid': [
          { required: true, message: '请输入深度CPA出价', trigger: 'blur' },
          { type: 'number', min: 0, message: '深度CPA出价必须大于0', trigger: 'blur' }
        ],
        'tiktok_json.placements': [
          { required: true, message: '请选择投放位置', trigger: 'change' }
        ],
        'tiktok_json.roasBid': [
          {
            required: true,
            message: '请输入ROAS目标值',
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (this.form.tiktok_json.optimizationGoal === 'VALUE' &&
                  this.form.tiktok_json.deepBidType === 'VO_MIN_ROAS' &&
                  !value) {
                callback(new Error('请输入ROAS目标值'));
              } else if (value && (value < 0.01 || value > 1000)) {
                callback(new Error('ROAS目标值必须在0.01-1000之间'));
              } else {
                callback();
              }
            }
          }
        ],
        'tiktok_json.vboWindow': [
          {
            required: true,
            message: '请选择价值优化窗口期',
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (this.form.tiktok_json.optimizationGoal === 'VALUE' && !value) {
                callback(new Error('请选择价值优化窗口期'));
              } else {
                callback();
              }
            }
          }
        ],
        'tiktok_json.advertiserId': [
          {
            required: true,
            message: '请选择账户',
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (!this.form.tiktok_json.isNewCampaign && !value) {
                callback(new Error('请选择账户'));
              } else {
                callback();
              }
            }
          }
        ]
      },
      templateMap: new Map(),
      detailVisible: false,
      errorReasonVisible: false,
      currentTaskDetail: null,
      drawerVisible: false,
      currentAdInfo: null,
      previewVisible: false,
      previewImageUrl: '',
      videoPlayVisible: false,
      currentVideoUrl: '',
      errorMessageVisible: false,
      currentErrorMsg: '',
      currentTaskId: null,
      detailLoading: false,
      appGroupOptions: [],
      locationGroupOptions: [],
      materialGroupOptions: [],
      titleGroupOptions: [],
      descriptionGroupOptions: [],
      appListData: [],
      selectedLocationGroups: [],
      selectedLocationGroupId: null,
      addAppDialogVisible: false,
      selectedAppId: '',
      selectApps: [],
      appsLoading: false,
      campaignListLoading: false,
      // 设备机型相关数据
      deviceModelOptions: [],
      deviceModelLoading: false,
      campaignOptions: [], // 改为存储包含id和name的对象数组
      // 新增：账户相关数据
      advertiserOptions: [],
      advertiserLoading: false,
      // 新增：搜索相关数据
      campaignSearchKeyword: '',
      filteredCampaignOptions: [],
      // 安卓版本选项
      androidVersionOptions: [
        { value: 'NONE', label: '不限' },
        { value: '4.0', label: 'Android 4.0' },
        { value: '4.1', label: 'Android 4.1' },
        { value: '4.2', label: 'Android 4.2' },
        { value: '4.3', label: 'Android 4.3' },
        { value: '4.4', label: 'Android 4.4' },
        { value: '5.0', label: 'Android 5.0' },
        { value: '5.1', label: 'Android 5.1' },
        { value: '6.0', label: 'Android 6.0' },
        { value: '7.0', label: 'Android 7.0' },
        { value: '7.1', label: 'Android 7.1' },
        { value: '8.0', label: 'Android 8.0' },
        { value: '8.1', label: 'Android 8.1' },
        { value: '9.0', label: 'Android 9.0' },
        { value: '10.0', label: 'Android 10.0' },
        { value: '11.0', label: 'Android 11.0' },
        { value: '12.0', label: 'Android 12.0' },
        { value: '13.0', label: 'Android 13.0' }
      ],
      // 多计划配置数据
      campaignConfigs: [],
      // 每个计划的地域组数据
      campaignLocationGroups: [],
    }
  },
  created() {
    this.fetchData()
    this.initGroupOptions()
  },
  methods: {
    moment,
    async fetchData() {
      this.loading = true
      try {
        const [startDate, endDate] = this.dateRange || []
        const response = await getCampaignTaskList({
          page: this.currentPage,
          size: this.pageSize,
          ...this.condition,
          startDate,
          endDate
        })
        if (response.status === 200) {
          this.tableData = response.result.data.value
          this.total = response.result.data.count
        } else {
          this.$message.error(response.msg || '获取数据失败')
        }
      } catch (error) {
        console.error('获取数据失败:', error)
        this.$message.error('获取数据失败')
      }
      this.loading = false
    },

    getStatusText(status) {
      const statusMap = {
        1: '未执行',
        2: '执行中',
        3: '执行成功',
        4: '执行失败'
      }
      return statusMap[status] || status
    },

    getStatusType(status) {
      const typeMap = {
        1: 'info',
        2: 'warning',
        3: 'success',
        4: 'danger'
      }
      return typeMap[status] || ''
    },

    calculateDuration(row) {
      const startTime = moment(row.startTime)
      const endTime = row.finishTime ? moment(row.finishTime) : moment()
      const diff = endTime.diff(startTime)
      const duration = moment.duration(diff)

      if (duration.asHours() >= 1) {
        return Math.floor(duration.asHours()) + '小时'
      } else if (duration.asMinutes() >= 1) {
        return Math.floor(duration.asMinutes()) + '分钟'
      } else {
        return Math.floor(duration.asSeconds()) + '秒'
      }
    },

    async fetchTemplates() {
      try {
        const response = await axios.get(process.env.PUTIN_API + '/campaign-templates')
        if (response.data && response.data.result && response.data.result.data) {
          const templates = response.data.result.data.value || []
          this.templateMap = new Map(templates.map(t => [t.id, t.name]))
        }
      } catch (error) {
        console.error('Failed to fetch templates:', error)
      }
    },

    getTemplateName(id) {
      return this.templateMap.get(id) || id
    },

    handleTemplateChange() {
      this.fetchData()
    },

    handleStatusChange() {
      this.fetchData()
    },

    handleDateChange() {
      this.fetchData()
    },

    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.fetchData()
    },

    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    },

    showAddDialog() {
      this.dialogTitle = '创建任务'
      this.isEdit = false

      // 重置表单
      this.form = {
        id: null,
        campaignTemplateId: null,
        templateType: 1,
        tempTemplateName: '',
        tempName: '',
        campaign_type: 1,
        appStore: 2,
        daily_budget: 100,
        bidding_type: 5,
        target_roas: 100,
        app_groups: [],
        location_groups: [],
        material_groups: [],
        title_groups: [],
        description_groups: [],
        resource_groups: [],
        accountName: '', // 重置账户名称
        // 修改字段名为tiktok_json
        tiktok_json: {
          optimizationGoal: 'VALUE',
          optimizationEvent: '', // 新增优化事件字段
          deepBidType: 'VO_MIN_ROAS',
          deepCpaBid: 0,
          roasBid: 0, // 新增ROAS目标值字段
          vboWindow: '', // 新增价值优化窗口期字段
          placements: [],
          isSmart: false,  // 添加isSmart字段,默认为false
          isNewCampaign: true, // 是否新建计划
          advertiserId: '', // 选中的广告主ID
          campaignIdList: [], // 计划ID列表
          deviceModels: [], // 设备机型列表
          minAndroidVersion: 'NONE' // 最小安卓系统版本
        }
      }

      this.selectedTemplate = null
      this.dialogVisible = true

      // 初始化组选项
      this.initGroupOptions()

      // 如果表单有验证错误，清除它们
      if (this.$refs.form) {
        this.$refs.form.clearValidate()
      }
    },

    handleEdit(row) {
      this.dialogTitle = '编辑任务'
      this.isEdit = true

      this.form = {
        id: row.id,
        campaignTemplateId: row.campaignTemplateId,
        templateType: 1,
        tempTemplateName: '',
        tempName: '',
        campaign_type: 1,
        appStore: 2,
        daily_budget: 100,
        bidding_type: 5,
        target_roas: 100,
        app_groups: [],
        location_groups: [],
        material_groups: [],
        title_groups: [],
        description_groups: [],
        resource_groups: [],
        accountName: '', // 重置账户名称
        // 修改字段名为tiktok_json
        tiktok_json: {
          optimizationGoal: 'VALUE',
          optimizationEvent: '', // 新增优化事件字段
          deepBidType: 'VO_MIN_ROAS',
          deepCpaBid: 0,
          roasBid: 0, // 新增ROAS目标值字段
          vboWindow: '', // 新增价值优化窗口期字段
          placements: [],
          isSmart: false,  // 添加isSmart字段,默认为false
          isNewCampaign: true, // 是否新建计划
          advertiserId: '', // 选中的广告主ID
          campaignIdList: [], // 计划ID列表
          deviceModels: [], // 设备机型列表
          minAndroidVersion: 'NONE' // 最小安卓系统版本
        }
      }

      // 获取模板详情
      if (row.campaignTemplateId) {
        this.handleTemplateSelectorChange(row.campaignTemplateId)
      }

      this.dialogVisible = true

      // 初始化组选项
      this.initGroupOptions()
    },

    handleDetail(row) {
      this.detailVisible = true;
      this.detailLoading = true;
      this.currentTaskDetail = null;
      this.currentTaskId = row.id;

      getCampaignTaskDetails({taskId: row.id}).then(response => {
        if (response.status === 200) {
          this.currentTaskDetail = response.result.data;
        } else {
          this.$message.error(response.msg || '获取任务详情失败');
        }
      }).catch(error => {
        console.error('获取任务详情失败:', error);
        this.$message.error('获取任务详情失败: ' + error.message);
      }).finally(() => {
        this.detailLoading = false;
      });
    },

    refreshDetail() {
      this.detailLoading = true;
      getCampaignTaskDetails({taskId: this.currentTaskId}).then(response => {
        if (response.status === 200) {
          this.currentTaskDetail = response.result.data;
        } else {
          this.$message.error(response.msg || '获取任务详情失败');
        }
      }).catch(error => {
        console.error('获取任务详情失败:', error);
        this.$message.error('获取任务详情失败: ' + error.message);
      }).finally(() => {
        this.detailLoading = false;
      });
    },

    async handleStart(row) {
      if (this.startLoading) {
        return;
      }
      this.startLoading = true;
      try {
        const response = await axios.post(process.env.PUTIN_API + `/campaign-tasks/start?campaignTaskId=${row.id}`)
        if (response.status == 200) {
          const message = row.status === 4 ? '任务重试成功' : '任务开始成功'
          this.$message.success(message)
          this.fetchData()
        } else {
          this.$message.error('任务开始失败')
        }
      } catch (error) {
        console.error('Failed to start task:', error)
        const errorMessage = error.response && error.response.data && error.response.data.message ?
          error.response.data.message : error.message
        this.$message.error('任务开始失败：' + errorMessage)
      } finally {
        this.startLoading = false;
      }
    },

    submitForm() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '提交中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })

          try {
            let taskData = {}

            taskData = {
              id: this.form.id,
              campaign_type: this.form.campaign_type,
              app_store: this.form.appStore,
              daily_budget: this.form.daily_budget,
              bidding_type: this.form.bidding_type,
              target_roas: this.form.target_roas,
              resource_groups: this.form.resource_groups,
              accountName: this.form.accountName, // 添加账户名称
            }

            // 根据模板类型传递不同的字段
            if (this.form.templateType === 1) {
              // 使用现有模板
              taskData.campaignTemplateId = this.form.campaignTemplateId;
            } else {
              // 使用临时模板
              taskData.tempTemplateName = this.form.tempTemplateName;
            }

            // 如果是TikTok平台，添加特定字段
            if (this.form.platform === 2) {
              // 修改字段名
              taskData.tiktok_json = JSON.stringify(this.form.tiktok_json);
              
              // 添加计划名称列表字段
              if (this.form.tiktok_json.campaignIdList && this.form.tiktok_json.campaignIdList.length > 0) {
                // 根据选中的计划ID找到对应的计划名称
                const selectedCampaignNames = this.form.tiktok_json.campaignIdList.map(campaignId => {
                  const campaign = this.campaignOptions.find(item => item.campaignId === campaignId);
                  return campaign ? campaign.campaignName : campaignId;
                });
                taskData.campaignNameList = selectedCampaignNames.join(',');
              } else {
                taskData.campaignNameList = '';
              }
            }

            // 将应用列表数据转换为接口所需格式
            taskData.apps = this.appListData.map(app => ({
              pkg: app.appId,
              campaignCount: app.campaignCount || 1
            }));

            // 将地域组数据转换为接口所需格式
            taskData.locationGroups = this.selectedLocationGroups.map(group => ({
              locationGroupId: group.id,
              campaignCount: group.campaignCount || 1
            }));

            // 标题组、描述组、素材组保持数组格式
            taskData.titleGroups = this.form.title_groups;
            taskData.descriptionGroups = this.form.description_groups;
            taskData.materialGroups = this.form.material_groups;

            // 检查是否是多计划配置
            if (this.form.platform === 2 && !this.form.tiktok_json.isNewCampaign && this.campaignConfigs.length > 0) {
              // 多计划配置，为每个计划单独调用接口
              const results = [];
              for (let i = 0; i < this.campaignConfigs.length; i++) {
                const campaignConfig = this.campaignConfigs[i];
                const campaignTaskData = {
                  ...taskData,
                  // 使用计划特定的配置
                  daily_budget: campaignConfig.dailyBudget,
                  target_roas: campaignConfig.roasBid,
                  location_groups: campaignConfig.locationGroups,
                  title_groups: campaignConfig.titleGroups,
                  material_groups: campaignConfig.materialGroups,
                  resource_groups: campaignConfig.resourceGroups,
                  accountName: this.form.accountName, // 添加账户名称
                  // 更新tiktok_json中的campaignIdList为单个计划
                  tiktok_json: JSON.stringify({
                    ...this.form.tiktok_json,
                    campaignIdList: [campaignConfig.campaignId]
                  }),
                  // 设置单个计划名称
                  campaignNameList: this.getCampaignName(campaignConfig.campaignId)
                };

                // 使用计划特定的地域组数据
                if (this.campaignLocationGroups[i] && this.campaignLocationGroups[i].length > 0) {
                  campaignTaskData.locationGroups = this.campaignLocationGroups[i].map(group => ({
                    locationGroupId: group.id,
                    campaignCount: group.campaignCount || 1
                  }));
                }

                // 使用全局应用数据（所有计划共用）
                campaignTaskData.apps = this.appListData.map(app => ({
                  pkg: app.appId,
                  campaignCount: app.campaignCount || 1
                }));

                let response;
                if (this.isEdit) {
                  response = await updateCampaignTask(campaignTaskData);
                } else {
                  response = await createCampaignTask(campaignTaskData);
                }
                
                results.push({
                  campaignName: this.getCampaignName(campaignConfig.campaignId),
                  success: response.status === 200,
                  response: response
                });
              }

              // 检查所有结果
              const successCount = results.filter(r => r.success).length;
              const totalCount = results.length;

              if (successCount === totalCount) {
                this.$message.success(`所有计划创建成功 (${successCount}/${totalCount})`);
              } else {
                this.$message.warning(`部分计划创建成功 (${successCount}/${totalCount})`);
                // 显示失败的计划
                const failedCampaigns = results.filter(r => !r.success).map(r => r.campaignName);
                this.$message.error(`失败的计划: ${failedCampaigns.join(', ')}`);
              }

              this.dialogVisible = false;
              this.fetchData();
            } else {
              // 单计划或新建计划，使用原有逻辑
              let response;
              if (this.isEdit) {
                response = await updateCampaignTask(taskData);
              } else {
                response = await createCampaignTask(taskData);
              }
              console.log('提交结果:', response);

              if (response.status === 200) {
                this.$message.success(this.isEdit ? '更新成功' : '创建成功');
                this.dialogVisible = false;
                this.fetchData();
              } else {
                this.$message.error(response.msg || '操作失败');
              }
            }
          } catch (error) {
            console.error('提交失败:', error)
            this.$message.error('提交失败')
          } finally {
            loading.close()
          }
        }
      })
    },



    showErrorReason() {
      this.errorReasonVisible = true;
    },

    formatJson(jsonString) {
      try {
        // 如果是字符串，则解析为JSON对象
        const jsonObj = typeof jsonString === 'string' ? JSON.parse(jsonString) : jsonString;
        // 美化格式
        return JSON.stringify(jsonObj, null, 2);
      } catch (e) {
        return jsonString;
      }
    },

    showAdInfo(row) {
      if (row && row.adInfo) {
        try {
          // 如果adInfo是字符串，则解析为JSON对象
          this.currentAdInfo = typeof row.adInfo === 'string' ? JSON.parse(row.adInfo) : row.adInfo;

          // 确保countries字段可用
          if (row.countries) {
            this.currentAdInfo.countries = typeof row.countries === 'string' ?
              JSON.parse(row.countries) : row.countries;
          }

          this.drawerVisible = true;
        } catch (error) {
          console.error('解析广告信息失败:', error);
          this.$message.error('无法解析广告信息');
        }
      } else {
        this.$message.info('没有广告信息');
      }
    },

    previewImage(url) {
      this.previewImageUrl = url;
      this.previewVisible = true;
    },

    playVideo(url) {
      this.currentVideoUrl = url;
      this.videoPlayVisible = true;
    },

    showErrorMessage(row) {
      if (row && row.errorMsg) {
        this.currentErrorMsg = row.errorMsg;
        this.errorMessageVisible = true;
      } else {
        this.$message.info('没有失败原因');
      }
    },

    // 切换模板类型
    handleTemplateTypeChange(value) {
      this.form.templateType = value
      if (value === 1) {
        // 使用现有模板，清空临时模板数据
        this.form.tempTemplateName = ''
        // 保留其他表单数据，以便在修改时使用
      } else {
        // 使用临时模板，清空选择的现有模板
        this.form.campaignTemplateId = null
        this.selectedTemplate = null
        // 当切换到临时模板时，保留之前填写的数据（如果有）或使用默认值
        if (!this.form.tempTemplateName) {
          // 如果选择过模板后切换到临时模板，使用模板名称+"(临时)"作为默认名称
          if (this.form.tempName) {
            this.form.tempTemplateName = this.form.tempName + ' (临时)'
          }
        }
      }
    },

    // 选择模板后的处理
    async handleTemplateSelectorChange(templateId) {
      if (!templateId) {
        this.selectedTemplate = null;
        return;
      }

      // 确保模板ID被设置到form中
      this.form.campaignTemplateId = templateId;

      try {
        const response = await getCampaignTemplateById(templateId);
        console.log('模板详情响应:', response);
        if (response.result && response.status === 200) {
          const template = response.result.data;
          this.selectedTemplate = template;

          // 将模板数据填充到表单中（优先使用模板中的值，如果没有则使用默认值）
          this.form.tempName = template.name || '';
          this.form.platform = template.platform !== undefined ? template.platform : 1;
          this.form.campaign_type = template.campaign_type !== undefined ? template.campaign_type : 1;
          this.form.appStore = template.appStore !== undefined ? template.appStore : 2;
          this.form.daily_budget = template.daily_budget !== undefined ? template.daily_budget : 100;
          this.form.bidding_type = template.bidding_type !== undefined ? template.bidding_type : 5;
          this.form.target_roas = template.target_roas !== undefined ? template.target_roas : 100;
          this.form.app_groups = Array.isArray(template.app_groups) ? [...template.app_groups] : [];
          this.form.location_groups = Array.isArray(template.location_groups) ? [...template.location_groups] : [];
          this.form.material_groups = Array.isArray(template.material_groups) ? [...template.material_groups] : [];
          this.form.title_groups = Array.isArray(template.title_groups) ? [...template.title_groups] : [];
          this.form.description_groups = Array.isArray(template.description_groups) ? [...template.description_groups] : [];
          this.form.resource_groups = Array.isArray(template.resource_groups) ? [...template.resource_groups] : (template.resource_group_id ? [template.resource_group_id] : []);
          
          console.log('模板数据中的resource_group_id:', template.resource_group_id);
          console.log('设置后的form.resource_groups:', this.form.resource_groups);

          // 处理tiktok_json字段（所有平台都需要处理）
          try {
            let tiktokData;
            if (template.tiktok_json) {
              tiktokData = typeof template.tiktok_json === 'string' ?
                JSON.parse(template.tiktok_json) : template.tiktok_json;
            } else {
              // 如果没有tiktok_json，使用默认值
              tiktokData = {
                optimizationGoal: 'VALUE',
                optimizationEvent: '',
                deepBidType: 'VO_MIN_ROAS',
                deepCpaBid: 0,
                roasBid: 0,
                vboWindow: '',
                placements: [],
                isSmart: false,
                isNewCampaign: true,
                advertiserId: '',
                campaignIdList: [],
                deviceModels: [],
                minAndroidVersion: 'NONE'
              };
            }

            // 确保所有必要的字段都存在
            this.form.tiktok_json = {
              optimizationGoal: tiktokData.optimizationGoal || 'VALUE',
              optimizationEvent: tiktokData.optimizationEvent || '',
              deepBidType: tiktokData.deepBidType || 'VO_MIN_ROAS',
              deepCpaBid: tiktokData.deepCpaBid || 0,
              roasBid: tiktokData.roasBid || 0,
              vboWindow: tiktokData.vboWindow || '',
              placements: Array.isArray(tiktokData.placements) ? tiktokData.placements : [],
              isSmart: tiktokData.isSmart || false,
              isNewCampaign: tiktokData.isNewCampaign !== undefined ? tiktokData.isNewCampaign : true,
              advertiserId: tiktokData.advertiserId || '',
              campaignIdList: Array.isArray(tiktokData.campaignIdList) ? tiktokData.campaignIdList : [],
              deviceModels: Array.isArray(tiktokData.deviceModels) ? tiktokData.deviceModels : [],
              minAndroidVersion: tiktokData.minAndroidVersion || 'NONE'
            };

            console.log('设置TikTok配置:', this.form.tiktok_json);
            console.log('模板中的deviceModels:', tiktokData.deviceModels);
            console.log('设置后的deviceModels:', this.form.tiktok_json.deviceModels);
          } catch (error) {
            console.error('解析TikTok配置失败:', error);
            this.$message.warning('TikTok配置解析失败,使用默认值');
            // 设置默认值
            this.form.tiktok_json = {
              optimizationGoal: 'VALUE',
              optimizationEvent: '',
              deepBidType: 'VO_MIN_ROAS',
              deepCpaBid: 0,
              roasBid: 0,
              vboWindow: '',
              placements: [],
              isSmart: false,
              isNewCampaign: true,
              advertiserId: '',
              campaignIdList: [],
              deviceModels: [],
              minAndroidVersion: 'NONE'
            };
          }

          // 如果是TikTok平台，获取广告主列表
          if (template.platform === 2) {
            // 在模板回显时不设置默认账户，保持模板中的账户设置
            await this.fetchAdvertiserList(false);
            
            // 如果模板中有advertiserId，需要确保账户列表加载完成后再设置
            if (this.form.tiktok_json.advertiserId) {
              // 等待账户列表加载完成，然后设置对应的账户
              this.$nextTick(() => {
                const selectedAdvertiser = this.advertiserOptions.find(
                  item => item.advertiserId === this.form.tiktok_json.advertiserId
                );
                if (selectedAdvertiser) {
                  // 设置账户名称
                  this.form.accountName = selectedAdvertiser.advertiserName;
                  // 触发账户变化，加载对应的计划列表和设备机型列表，但保留设备机型数据
                  this.handleAdvertiserChange(this.form.tiktok_json.advertiserId, true);
                }
              });
            }
          }

          // 主动触发应用列表和地域组列表的查询
          this.$nextTick(() => {
            if (this.form.app_groups && this.form.app_groups.length > 0) {
              this.handleAppGroupsChange(this.form.app_groups);
            }

            if (this.form.location_groups && this.form.location_groups.length > 0) {
              this.handleLocationGroupsChange(this.form.location_groups);
            }
          });
        }
      } catch (error) {
        console.error('获取模板详情失败:', error);
        this.$message.error('获取模板详情失败');
      }
    },

    // 获取广告主列表
    async fetchAdvertiserList(shouldSetDefault = true) {
      this.advertiserLoading = true;
      try {
        const response = await axios.get(process.env.PUTIN_API + '/campaign-tasks/getTiktokAdvertiserId');
        if (response.data && response.data.status === 200) {
          this.advertiserOptions = response.data.result.data || [];
          
          // 只有在需要设置默认值且当前没有选择账户时才设置第一个
          if (shouldSetDefault && this.advertiserOptions.length > 0 && !this.form.tiktok_json.advertiserId) {
            this.form.tiktok_json.advertiserId = this.advertiserOptions[0].advertiserId;
            // 异步调用第一个账户的计划列表和设备机型列表，不等待完成
            this.fetchCampaignList(this.advertiserOptions[0].advertiserId);
            this.fetchDeviceModelList(this.advertiserOptions[0].advertiserId);
          }
        } else {
          this.$message.error(response.data.msg || '获取账户列表失败');
        }
      } catch (error) {
        console.error('获取账户列表失败:', error);
        this.$message.error('获取账户列表失败');
      } finally {
        this.advertiserLoading = false;
      }
    },

    // 处理广告主变化
    async handleAdvertiserChange(advertiserId, preserveDeviceModels = false) {
      if (!advertiserId) {
        this.campaignOptions = [];
        this.form.tiktok_json.campaignIdList = [];
        this.deviceModelOptions = [];
        this.form.tiktok_json.deviceModels = [];
        this.form.accountName = ''; // 清空账户名称
        return;
      }

      // 设置账户名称
      const selectedAdvertiser = this.advertiserOptions.find(item => item.advertiserId === advertiserId);
      if (selectedAdvertiser) {
        this.form.accountName = selectedAdvertiser.advertiserName;
      }

      // 只有在不保留设备机型的情况下才清空（用户主动切换账户时）
      if (!preserveDeviceModels) {
        this.form.tiktok_json.deviceModels = [];
      }

      await this.fetchCampaignList(advertiserId);
      await this.fetchDeviceModelList(advertiserId);
    },

    // 修改搜索处理方法
    handleCampaignSearch(query) {
      if (!query) {
        this.filteredCampaignOptions = this.campaignOptions;
      } else {
        this.filteredCampaignOptions = this.campaignOptions.filter(item =>
          item.toLowerCase().includes(query.toLowerCase())
        );
      }
    },

    // 修改获取计划列表的方法
    async fetchCampaignList(advertiserId) {
      if (!advertiserId) return;

      this.campaignListLoading = true;
      try {
        const response = await axios.get(process.env.PUTIN_API + '/campaign-tasks/getCampaignIdByAdvertiserId', {
          params: {
            advertiserId: advertiserId
          }
        });
        if (response.data && response.data.status === 200) {
          // 直接使用返回的数据结构
          this.campaignOptions = response.data.result.data || [];
          this.form.tiktok_json.campaignIdList = [];
        } else {
          this.$message.error(response.data.msg || '获取计划列表失败');
        }
      } catch (error) {
        console.error('获取计划列表失败:', error);
        this.$message.error('获取计划列表失败');
      } finally {
        this.campaignListLoading = false;
      }
    },

    // 获取设备机型列表
    async fetchDeviceModelList(advertiserId) {
      if (!advertiserId) return;

      this.deviceModelLoading = true;
      try {
        const response = await getTikTokDeviceModels(advertiserId);
         console.log('设备机型接口响应:', response);
         if (response.status === 200) {
           // 根据实际返回的数据结构，数据在 response.result.data.data.device_models 中
           this.deviceModelOptions = (response.result && response.result.data && response.result.data.data && response.result.data.data.device_models) || [];
           console.log('设备机型列表:', this.deviceModelOptions);
         } else {
           this.$message.error(response.msg || '获取设备机型列表失败');
         }
      } catch (error) {
        console.error('获取设备机型列表失败:', error);
        this.$message.error('获取设备机型列表失败');
      } finally {
        this.deviceModelLoading = false;
      }
    },

    // 处理平台变化
    async handlePlatformChange(value) {
      // 当平台改变时，重新验证日预算字段
      this.$nextTick(() => {
        this.$refs.form.validateField('daily_budget');
      });
      
      if (value === 2) {
        // 如果选择了TikTok平台，重置相关字段
        this.form.tiktok_json.isNewCampaign = true;
        this.form.tiktok_json.advertiserId = '';
        this.form.tiktok_json.campaignIdList = [];
        // 获取广告主列表
        await this.fetchAdvertiserList(true);
      }
    },

    // 处理优化目标变化
    handleOptimizationGoalChange(value) {
      // 当优化目标改变时，清空相关字段
      this.form.tiktok_json.optimizationEvent = '';
      this.form.tiktok_json.deepBidType = '';
      this.form.tiktok_json.roasBid = 0;
      this.form.tiktok_json.vboWindow = '';

      // 如果选择的是安装，则不需要优化事件和深度出价类型
      if (value === 'INSTALL') {
        this.form.tiktok_json.optimizationEvent = '';
        this.form.tiktok_json.deepBidType = '';
        this.form.tiktok_json.roasBid = 0;
        this.form.tiktok_json.vboWindow = '';
      }
    },

    // 处理深度出价类型变化
    handleDeepBidTypeChange(value) {
      // 当深度出价类型改变时，如果不是最小ROAS，则清空ROAS目标值
      if (value !== 'VO_MIN_ROAS') {
        this.form.tiktok_json.roasBid = 0;
      }
    },

    // 应用组名称获取
    getAppGroupName(id) {
      const group = this.appGroupOptions.find(item => item.id === id)
      return group ? group.name : id
    },

    // 地域组名称获取
    getLocationGroupName(id) {
      const group = this.locationGroupOptions.find(item => item.id === id)
      return group ? group.name : id
    },

    // 素材组名称获取
    getMaterialGroupName(id) {
      const group = this.materialGroupOptions.find(item => item.id === id)
      return group ? group.name : id
    },

    // 标题组名称获取
    getTitleGroupName(id) {
      const group = this.titleGroupOptions.find(item => item.id === id)
      return group ? group.name : id
    },

    // 描述组名称获取
    getDescriptionGroupName(id) {
      const group = this.descriptionGroupOptions.find(item => item.id === id)
      return group ? group.name : id
    },

    // 初始化模板选择相关数据
    async initGroupOptions() {
      // 初始化所有组选项
      this.appGroupOptions = []
      this.locationGroupOptions = []
      this.materialGroupOptions = []
      this.titleGroupOptions = []
      this.descriptionGroupOptions = []

      try {
        // 获取应用组数据
        const appGroupRes = await axios.get(process.env.PUTIN_API + '/app-groups')
        if (appGroupRes.data && appGroupRes.data.code === 200 && appGroupRes.data.data) {
          this.appGroupOptions = appGroupRes.data.data
        }

        // 获取地域组数据
        const locationGroupRes = await axios.get(process.env.PUTIN_API + '/location-groups')
        if (locationGroupRes.status === 200) {
          this.locationGroupOptions = locationGroupRes.data.result.data
        }

        // 获取素材组数据
        const materialGroupRes = await axios.get(process.env.PUTIN_API + '/material-groups')
        if (materialGroupRes.data && materialGroupRes.data.code === 200 && materialGroupRes.data.data) {
          this.materialGroupOptions = materialGroupRes.data.data
        }

        // 获取标题组数据
        const titleGroupRes = await axios.get(process.env.PUTIN_API + '/title-groups')
        if (titleGroupRes.data && titleGroupRes.data.code === 200 && titleGroupRes.data.data) {
          this.titleGroupOptions = titleGroupRes.data.data
        }

        // 获取描述组数据
        const descriptionGroupRes = await axios.get(process.env.PUTIN_API + '/description-groups')
        if (descriptionGroupRes.data && descriptionGroupRes.data.code === 200 && descriptionGroupRes.data.data) {
          this.descriptionGroupOptions = descriptionGroupRes.data.data
        }
      } catch (error) {
        console.error('获取组选项数据失败:', error)
        this.$message.warning('获取组选项数据失败，部分组信息可能无法正确显示')
      }
    },

    handleAppGroupsChange(value) {
      // 处理应用组变化后的逻辑
      if (value && value.length > 0) {
        this.fetchAppListData(value);
      } else {
        this.appListData = [];
      }
    },

    async fetchAppListData(appGroupIds) {
      try {
        // 使用新接口直接获取应用组对应的应用列表
        const response = await axios.post(process.env.PUTIN_API + '/apps/by-app-groups', {
          appGroupIds: appGroupIds
        });

        if (response.data && response.data.status === 200 && response.data.result && response.data.result.data) {
          // 处理返回的应用数据
          const apps = response.data.result.data;

          // 转换为组件需要的格式
          this.appListData = apps.map(app => ({
            name: app.appName,
            appId: app.pkg,
            id: app.id,
            description: app.description,
            operateType: app.operateType,
            campaignCount: 1 // 添加计划数字段，默认为1
          }));
        } else {
          console.error('获取应用组应用列表失败:', response);
          this.$message.error('获取应用组应用列表失败');
        }
      } catch (error) {
        console.error('获取应用组应用列表失败:', error);
        this.$message.error('获取应用组应用列表失败');
      }
    },

    // 更新应用的计划数
    updateAppCampaignCount(app, value) {
      // 验证输入值
      if (value < 1) {
        this.$message.warning('计划数最小为1');
        // 重置为1
        const index = this.appListData.findIndex(item => item.appId === app.appId);
        if (index !== -1) {
          this.appListData[index].campaignCount = 1;
        }
        return;
      }

      // 更新计划数
      const index = this.appListData.findIndex(item => item.appId === app.appId);
      if (index !== -1) {
        this.appListData[index].campaignCount = value;
      }
    },

    handleLocationGroupsChange(value) {
      // 处理地域组变化后的逻辑
      if (value && value.length > 0) {
        this.fetchSelectedLocationGroups(value);
      } else {
        this.selectedLocationGroups = [];
      }
    },

    async fetchSelectedLocationGroups(locationGroupIds) {
      try {
        // 打印地域组选项，便于调试
        console.log('地域组选项:', this.locationGroupOptions);



        this.selectedLocationGroups = locationGroupIds.map(id => {
          // 确保ID为数字类型进行比较
          const numId = Number(id);
          // 尝试在选项中找到对应的地域组
          const group = this.locationGroupOptions.find(item => Number(item.id) === numId);

          console.log(`查找地域组ID: ${id}, 找到: ${group}`);

          if (group) {
            return {
              id: group.id,
              name: group.name || `地域组 ${id}`, // 确保有名称，如果没有则使用ID
              campaignCount: 1,
              countryCodes: group.countryCodes || []
            };
          } else {
            return {
              id: id,
              name: `地域组 ${id}`,
              campaignCount: 1,
              countryCodes: []
            };
          }
        });

        // 打印选中的地域组，便于调试
        console.log('选中的地域组:', this.selectedLocationGroups);
      } catch (error) {
        console.error('获取地域组数据失败:', error);
        this.$message.error('获取地域组数据失败');
      }
    },

    // 更新地域组的计划数
    updateLocationGroupCampaignCount(group, value) {
      // 验证输入值
      if (value < 1) {
        this.$message.warning('计划数最小为1');
        // 重置为1
        const index = this.selectedLocationGroups.findIndex(item => item.id === group.id);
        if (index !== -1) {
          this.selectedLocationGroups[index].campaignCount = 1;
        }
        return;
      }

      // 更新计划数
      const index = this.selectedLocationGroups.findIndex(item => item.id === group.id);
      if (index !== -1) {
        this.selectedLocationGroups[index].campaignCount = value;
      }
    },

    viewLocationGroup(group) {
      // 实现查看地域组详情逻辑
      this.$alert(`地域组 "${group.name}" 详情`, '地域组详情', {
        dangerouslyUseHTMLString: true,
        customClass: 'location-group-detail-dialog'
      });
    },

    editLocationGroup(group) {
      // 实现编辑地域组逻辑
      this.$router.push(`/location-group/edit/${group.id}`);
    },

    removeLocationGroup(group) {
      this.$confirm(`确定要移除地域组 "${group.name}" 吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const index = this.form.location_groups.indexOf(Number(group.id));
        if (index !== -1) {
          this.form.location_groups.splice(index, 1);
          // 更新地域组列表
          this.handleLocationGroupsChange(this.form.location_groups);
          this.$message.success('已移除地域组');
        }
      }).catch(() => {
        // 取消操作
      });
    },

    getLocationGroupCountries(group) {
      // 获取地域组国家列表
      // 由于我们没有完整的API，这里返回一个模拟数据
      return group.countryCodes || [];
    },

    handleAppFilter(app) {
      // 实现针对特定应用的过滤逻辑
      this.$message.info(`已选择针对应用: ${app.name} (${app.appId})`);
      // 这里可以实现实际的过滤逻辑
    },

    showAddAppDialog() {
      // 显示一个带有应用选择列表的弹窗，而不是简单的输入框
      this.addAppDialogVisible = true;
      // 如果还没有加载应用列表，则加载
      if (!this.selectApps || this.selectApps.length === 0) {
        this.fetchAppsForSelector();
      }
    },

    async fetchAppsForSelector() {
      try {
        this.appsLoading = true; // 显示加载状态

        const params = {
          platformId: 5,
          menuCode: "game.Overview,android",
        };
        const response = await getSelectApps(params);
        if (response.status === 200) {
          this.selectApps = response.result.data || [];
        } else {
          console.error("获取应用列表失败:", response);
          this.$message.error("获取应用列表失败");
        }
      } catch (error) {
        console.error("获取应用列表失败:", error);
        this.$message.error("获取应用列表失败");
      } finally {
        this.appsLoading = false; // 隐藏加载状态
      }
    },


    removeApp(app) {
      this.$confirm(`确定要移除应用 "${app.name}" 吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const index = this.appListData.findIndex(item => item.appId === app.appId);
        if (index !== -1) {
          this.appListData.splice(index, 1);
          this.$message.success('已移除应用');
        }
      }).catch(() => {
        // 取消操作
      });
    },

    // 确认添加选中的应用
    confirmAddApp() {
      if (!this.selectedAppId) {
        this.$message.warning('请先选择一个应用');
        return;
      }

      // 查找选中的应用信息
      const appInfo = this.selectApps.find(app => app.id === this.selectedAppId);
      if (!appInfo) {
        this.$message.error('无法获取应用信息');
        return;
      }

      // 检查是否已经存在
      const exists = this.appListData.some(item => item.appId === appInfo.value || item.id === appInfo.id);
      if (exists) {
        this.$message.warning('该应用已经在列表中');
        return;
      }

      // 添加到应用列表
      this.appListData.push({
        name: appInfo.label || appInfo.appName,  // 显示名称
        appId: appInfo.value,                    // 包名
        id: appInfo.id,                          // 应用ID
        description: appInfo.description || '',  // 描述（如果有）
        operateType: appInfo.operateType || '',  // 操作类型（如果有）
        campaignCount: 1                         // 默认计划数为1
      });

      this.$message.success('添加应用成功');
      this.addAppDialogVisible = false;
      this.selectedAppId = '';
    },

    // 获取计划名称
    getCampaignName(campaignId) {
      const campaign = this.campaignOptions.find(item => item.campaignId === campaignId);
      return campaign ? campaign.campaignName : campaignId;
    },

    // 处理计划选择变化
    handleCampaignSelectionChange(selectedCampaignIds) {
      // 初始化每个计划的配置
      this.campaignConfigs = selectedCampaignIds.map(campaignId => {
        return {
          campaignId: campaignId,
          roasBid: this.form.tiktok_json.roasBid || 0,
          dailyBudget: this.form.daily_budget || 100,
          locationGroups: [...this.form.location_groups],
          titleGroups: [...this.form.title_groups],
          materialGroups: [...this.form.material_groups],
          resourceGroups: [...this.form.resource_groups]
        };
      });

      // 初始化每个计划的地域组数据，使用当前已选地域组的详细数据
      this.campaignLocationGroups = selectedCampaignIds.map(() => {
        // 复制当前已选地域组的详细数据
        return this.selectedLocationGroups.map(group => ({
          id: group.id,
          name: group.name,
          campaignCount: group.campaignCount || 1,
          countryCodes: group.countryCodes || []
        }));
      });
    },

    // 移除计划配置
    removeCampaignConfig(index) {
      this.form.tiktok_json.campaignIdList.splice(index, 1);
      this.campaignConfigs.splice(index, 1);
      this.campaignLocationGroups.splice(index, 1);
    },

    // 处理计划地域组变化
    handleCampaignLocationGroupsChange(campaignIndex, locationGroupIds) {
      if (locationGroupIds && locationGroupIds.length > 0) {
        this.fetchCampaignLocationGroups(campaignIndex, locationGroupIds);
      } else {
        this.campaignLocationGroups[campaignIndex] = [];
      }
    },

    // 获取计划地域组数据
    async fetchCampaignLocationGroups(campaignIndex, locationGroupIds) {
      try {
        this.campaignLocationGroups[campaignIndex] = locationGroupIds.map(id => {
          const numId = Number(id);
          const group = this.locationGroupOptions.find(item => Number(item.id) === numId);
          
          if (group) {
            return {
              id: group.id,
              name: group.name || `地域组 ${id}`,
              campaignCount: 1,
              countryCodes: group.countryCodes || []
            };
          } else {
            return {
              id: id,
              name: `地域组 ${id}`,
              campaignCount: 1,
              countryCodes: []
            };
          }
        });
      } catch (error) {
        console.error('获取计划地域组数据失败:', error);
        this.$message.error('获取计划地域组数据失败');
      }
    },

    // 获取计划地域组数据用于显示
    getCampaignLocationGroupData(campaignIndex) {
      return this.campaignLocationGroups[campaignIndex] || [];
    },

    // 更新计划地域组的计划数
    updateCampaignLocationGroupCampaignCount(campaignIndex, group, value) {
      // 验证输入值
      if (value < 1) {
        this.$message.warning('计划数最小为1');
        // 重置为1
        const index = this.campaignLocationGroups[campaignIndex].findIndex(item => item.id === group.id);
        if (index !== -1) {
          this.campaignLocationGroups[campaignIndex][index].campaignCount = 1;
        }
        return;
      }

      // 更新计划数
      const index = this.campaignLocationGroups[campaignIndex].findIndex(item => item.id === group.id);
      if (index !== -1) {
        this.campaignLocationGroups[campaignIndex][index].campaignCount = value;
      }
    },
  }
}
</script>

<style lang="scss" scoped>
.campaign-task-container {
  padding: 20px;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.filter-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
}

.filter-input {
  width: 200px;
}

.header-actions {
  margin: 20px 0;
  display: flex;
  justify-content: space-between;
}

.header-right {
  display: flex;
  gap: 10px;
}

.el-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}

.el-table--enable-row-hover .el-table__body tr:hover > td {
  background-color: #f5f7fa;
}

.el-button--primary {
  background-color: #1890ff;
  border-color: #1890ff;
}

.el-button--primary:hover,
.el-button--primary:focus {
  background-color: #40a9ff;
  border-color: #40a9ff;
}

.el-link {
  color: #1890ff;
}

.el-link:hover {
  color: #40a9ff;
}

.el-select .el-input__inner,
.el-input__inner {
  border-radius: 2px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  padding: 10px 0;
}

.el-pagination {
  font-weight: normal;
}

.el-pagination .el-select .el-input {
  width: 110px;
}

.el-pagination .el-select .el-input__inner {
  padding-right: 25px;
}

.el-pagination .btn-prev,
.el-pagination .btn-next {
  background: transparent;
}

.el-pagination .el-pager li {
  background: transparent;
  border: none;
}

.el-pagination .el-pager li.active {
  color: #1890ff;
  background-color: #e6f7ff;
  border-radius: 2px;
}

.el-pagination__total {
  margin-right: 10px;
}

.el-pagination__sizes {
  margin-left: 10px;
}

.mt-3 {
  margin-top: 1rem;
}

/* 抽屉内容样式 */
.drawer-content {
  padding: 20px;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  margin: 20px 0 10px 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.headlines-section,
.descriptions-section {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.headline-item,
.description-item {
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
}

.item-title {
  font-weight: bold;
  margin-bottom: 5px;
  color: #666;
}

.item-content {
  word-break: break-all;
}

.images-section,
.videos-section {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-top: 10px;
}

.image-item,
.video-item {
  width: calc(33.333% - 15px);
  margin-bottom: 15px;
}

.thumbnail,
.video-thumbnail {
  width: 100%;
  height: 120px;
  object-fit: cover;
  border-radius: 4px;
  cursor: pointer;
  transition: transform 0.3s;
}

.thumbnail:hover,
.video-thumbnail:hover {
  transform: scale(1.05);
}

.video-name {
  font-size: 12px;
  margin-top: 5px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.preview-image {
  max-width: 100%;
  max-height: 80vh;
}

.video-player {
  width: 100%;
}

/* 大型屏幕上的响应式布局 */
@media (min-width: 1200px) {
  .image-item,
  .video-item {
    width: calc(25% - 15px);
  }
}

/* 小型屏幕上的响应式布局 */
@media (max-width: 768px) {
  .image-item,
  .video-item {
    width: calc(50% - 15px);
  }
}

.countries-section {
  margin: 0 0 25px 0;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  background-color: #f8f9fc;
  padding: 15px;
  border-radius: 6px;
}

.country-item {
  display: inline-flex;
  align-items: center;
  margin-right: 5px;
}

.country-tag {
  border-radius: 4px;
  font-weight: 500;
  letter-spacing: 0.5px;
  transition: all 0.3s ease;
  padding: 0 8px;
  height: 26px;
  line-height: 24px;
  margin-bottom: 5px;
}

.country-tag:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.country-separator {
  margin: 0 3px;
  color: #909399;
}

.no-countries {
  color: #909399;
  font-style: italic;
}

.table-countries-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

.no-countries-text {
  color: #909399;
  font-size: 12px;
}

/* 调整标签在表格中的样式 */
.el-table .country-tag {
  margin-bottom: 3px;
  font-size: 11px;
  height: 22px;
  line-height: 20px;
  padding: 0 5px;
}

.clickable-tag {
  cursor: pointer;
}

.clickable-tag:hover {
  opacity: 0.85;
}

.error-message-content {
  padding: 15px;
  background-color: #fef0f0;
  border-radius: 4px;
  border-left: 4px solid #f56c6c;
  word-break: break-all;
  max-height: 300px;
  overflow-y: auto;
}

.no-error-message {
  color: #909399;
  font-style: italic;
}

.operation-buttons {
  display: flex;
  justify-content: center;
  align-items: center;
}

.operation-buttons .el-button {
  margin: 0 3px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.operation-buttons .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

// 模板详情样式
.template-details {
  margin: 15px 0;
  padding: 15px;
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  background-color: #f9f9f9;

  .el-divider {
    margin-top: 0;
  }

  .el-form-item {
    margin-bottom: 12px;
  }

  .group-tags {
    display: flex;
    flex-wrap: wrap;

    .el-tag {
      margin: 2px 5px 2px 0;
    }
  }
}

.group-detail-container {
  margin-top: 10px;
  padding: 10px;
  background-color: #fff;
  border: 1px solid #EBEEF5;
  border-radius: 4px;
}

.group-detail-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
}

/* 应用选择器样式 */
.app-selector-container {
  padding: 10px;
}

.app-selector-container .el-select {
  width: 100%;
}

.campaign-select-container {
  .campaign-search-input {
    margin-bottom: 10px;
  }

  .campaign-select {
    width: 100%;
  }
}

/* 计划名称换行显示样式 */
.campaign-names {
  max-height: 80px;
  overflow-y: auto;
}

.campaign-name-item {
  padding: 2px 4px;
  margin: 1px 0;
  background-color: #f0f9ff;
  border: 1px solid #bae6fd;
  border-radius: 3px;
  font-size: 12px;
  color: #0369a1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  transition: all 0.2s ease;
}

.campaign-name-item:hover {
  background-color: #e0f2fe;
  border-color: #7dd3fc;
  transform: translateX(2px);
}

/* 多计划配置样式 */
.multi-campaign-config {
  margin-top: 20px;
  padding: 20px;
  background-color: #f8f9fc;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
}

.campaign-config-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.campaign-config-item {
  background-color: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.campaign-config-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e4e7ed;
}

.campaign-config-header h4 {
  margin: 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.campaign-config-item .el-form-item {
  margin-bottom: 15px;
}

.campaign-config-item .el-form-item__label {
  font-weight: 500;
  color: #606266;
}

.campaign-config-item .el-input-number {
  width: 200px;
}

.campaign-config-item .el-select {
  width: 100%;
}

/* 共用配置信息样式 */
.shared-config-info {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px 12px;
  background-color: #f0f9ff;
  border: 1px solid #bae6fd;
  border-radius: 4px;
}

.config-detail {
  color: #0369a1;
  font-size: 13px;
}
</style>
