<template>
  <div class="campaign-template-container">
    <!-- Filter section -->
    <div class="filter-section">
      <el-form :inline="true" :model="condition" class="filter-form">
        <el-form-item label="模板名称">
          <el-input
            v-model="condition.name"
            placeholder="请输入模板名称"
            class="filter-input"
            @change="fetchData">
          </el-input>
        </el-form-item>

        <el-form-item label="应用组">
          <app-group-selector
            v-model="condition.appGroups"
            @change="handleAppGroupChange"
          />
        </el-form-item>

        <el-form-item label="地域组">
          <location-group-selector
            v-model="condition.locationGroups"
            @change="handleLocationGroupChange"
          />
        </el-form-item>

        <el-form-item label="素材组">
          <material-group-selector
            v-model="condition.materialGroups"
            @change="handleMaterialGroupChange"
          />
        </el-form-item>

        <el-form-item label="标题组">
          <title-group-selector
            v-model="condition.titleGroups"
            @change="handleTitleGroupChange"
          />
        </el-form-item>

        <el-form-item label="描述组">
          <description-group-selector
            v-model="condition.descriptionGroups"
            @change="handleDescriptionGroupChange"
          />
        </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="name" label="模板名称" width="250"></el-table-column>
      <el-table-column label="平台" width="120" align="center">
        <template slot-scope="scope">
          <el-tag :type="getPlatformTagType(scope.row.platform)">
            {{ getPlatformName(scope.row.platform) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="daily_budget" label="日预算($)" width="120">
        <template slot-scope="scope">
          {{ scope.row.daily_budget }}
        </template>
      </el-table-column>
      <el-table-column prop="target_roas" label="考核ROAS(%)" width="150">
        <template slot-scope="scope">
          {{ scope.row.target_roas }}
        </template>
      </el-table-column>
      <el-table-column label="应用组" width="200">
        <template slot-scope="scope">
          <el-tag
            v-for="group in scope.row.app_groups || []"
            :key="group"
            size="small"
            style="margin: 2px">
            {{ getAppGroupName(group) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="地域组" width="200">
        <template slot-scope="scope">
          <el-tag
            v-for="group in scope.row.location_groups || []"
            :key="group"
            size="small"
            style="margin: 2px">
            {{ getLocationGroupName(group) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="素材组" width="200">
        <template slot-scope="scope">
          <el-tag
            v-for="group in scope.row.material_groups || []"
            :key="group"
            size="small"
            style="margin: 2px">
            {{ getMaterialGroupName(group) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="标题组" width="200">
        <template slot-scope="scope">
          <el-tag
            v-for="group in scope.row.title_groups || []"
            :key="group"
            size="small"
            style="margin: 2px">
            {{ getTitleGroupName(group) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="描述组" width="200">
        <template slot-scope="scope">
          <el-tag
            v-for="group in scope.row.description_groups || []"
            :key="group"
            size="small"
            style="margin: 2px">
            {{ getDescriptionGroupName(group) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="资源组" width="200">
        <template slot-scope="scope">
          <div v-if="scope.row.resource_groups && scope.row.resource_groups.length > 0">
            <el-tag
              v-for="group in scope.row.resource_groups"
              :key="group"
              type="success"
              size="small"
              style="margin: 2px">
              {{ getResourceGroupName(group) }}
            </el-tag>
          </div>
          <div v-else-if="scope.row.resource_group_id">
            <el-tag type="success" size="small">
              {{ getResourceGroupName(scope.row.resource_group_id) }}
            </el-tag>
          </div>
          <span v-else style="color: #999; font-size: 12px;">未选择</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            @click="handleEdit(scope.row)">编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- Pagination -->
    <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="50%">
      <el-form :model="form" :rules="rules" ref="form" label-width="120px">
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="form.name"></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>

        <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>

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

           <el-form-item
             label="选择账户"
             prop="tiktok_json.advertiserId">
             <el-select
               v-model="tiktokAdvertiserId"
               placeholder="请选择账户"
               :loading="advertiserLoading"
               @change="handleAdvertiserChange"
               filterable>
               <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="tiktokOptimizationGoal" 
               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="tiktokOptimizationGoal === 'VALUE'">
             <el-select v-model="tiktokOptimizationEvent" 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="tiktokOptimizationGoal === 'VALUE'">
             <el-select 
               v-model="tiktokDeepBidType" 
               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="tiktokOptimizationGoal === 'VALUE' && tiktokDeepBidType === 'VO_MIN_ROAS'">
             <el-input-number
               v-model="tiktokRoasBid"
               :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="tiktokOptimizationGoal === 'VALUE'">-->
<!--             <el-select v-model="tiktokVboWindow" placeholder="请选择价值优化窗口期">-->
<!--               <el-option label="前7天" value="SEVEN_DAYS"></el-option>-->
<!--               <el-option label="第0天（当天）" value="ZERO_DAY"></el-option>-->
<!--             </el-select>-->
<!--           </el-form-item>-->

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

           <!-- 投放位置选择框 -->
<!--           <el-form-item label="投放位置" prop="tiktok_json.placements">-->
<!--             <el-select -->
<!--               v-model="tiktokPlacements" -->
<!--               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="tiktokIsNewCampaign"
               active-text="是"
               inactive-text="否">
             </el-switch>
           </el-form-item>

           <el-form-item
             label="选择已有计划"
             prop="tiktok_json.campaignIdList"
             v-if="!tiktokIsNewCampaign && tiktokAdvertiserId">
             <el-select
               v-model="tiktokCampaignIdList"
               multiple
               filterable
               placeholder="请输入计划名称搜索"
               :loading="campaignListLoading"
               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>

           <el-form-item
             label="设备机型"
             prop="tiktok_json.deviceModels"
             v-if="tiktokAdvertiserId">
             <el-select
               v-model="tiktokDeviceModels"
               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="tiktokMinAndroidVersion"
               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="app_groups">
          <app-group-selector v-model="form.app_groups" />
        </el-form-item>

        <el-form-item label="地域组" prop="location_groups">
          <location-group-selector v-model="form.location_groups" />
        </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>

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

<script>
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 axios from 'axios'
import { getCampaignTemplateList, createCampaignTemplate, updateCampaignTemplate, deleteCampaignTemplate } from '@/api/campaignTemplate'
import { getTikTokDeviceModels } from '@/api/tiktokDevice'

export default {
  name: 'CampaignTemplateManage',
  components: {
    AppGroupSelector,
    LocationGroupSelector,
    MaterialGroupSelector,
    TitleGroupSelector,
    DescriptionGroupSelector,
    ResourceGroupSelector
  },
  data() {
    return {
      condition: {
        name: '',
        appGroups: [],
        locationGroups: [],
        materialGroups: [],
        titleGroups: [],
        descriptionGroups: []
      },
      loading: false,
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      dialogTitle: '',
      form: {
        name: '',
        platform: 2, // 默认选择TikTok平台
        campaign_type: 1,
        appStore: 3,
        daily_budget: 0,
        bidding_type: 5,
        target_roas: 0,
        app_groups: [],
        location_groups: [],
        material_groups: [],
        title_groups: [],
        description_groups: [],
        resource_groups: [],
                 // 初始化tiktok_json为对象而不是null
         tiktok_json: {
           optimizationGoal: 'VALUE',
           optimizationEvent: 'AD_REVENUE_VALUE',
           deepBidType: 'VO_MIN_ROAS',
           // deepCpaBid: 0,
           roasBid: 0,
           // vboWindow: '',
           // placements: [],
           isSmart: false,
           isNewCampaign: true,
           advertiserId: '',
           campaignIdList: [],
           deviceModels: [],
           minAndroidVersion: 'NONE'
         }
      },
      rules: {
        name: [
          { required: true, message: '请输入模板名称', trigger: 'blur' }
        ],
        platform: [
          { required: true, message: '请选择平台', trigger: 'change' }
        ],
        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' }
        ],
        // 新增TikTok特定字段的验证规则
        'tiktok_json.optimizationGoal': [
          { required: true, message: '请选择优化目标', trigger: 'change' }
        ],
        'tiktok_json.deepBidType': [
          { required: true, message: '请选择深度出价类型', trigger: 'change' }
        ],
                 // '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.optimizationEvent': [
          {
            required: true,
            message: '请选择优化事件',
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (this.tiktokOptimizationGoal === 'VALUE' && !value) {
                callback(new Error('请选择优化事件'));
              } else {
                callback();
              }
            }
          }
        ],
                 'tiktok_json.roasBid': [
           {
             required: true,
             message: '请输入ROAS目标值',
             trigger: 'blur',
             validator: (rule, value, callback) => {
               if (this.tiktokOptimizationGoal === 'VALUE' &&
                   this.tiktokDeepBidType === '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.tiktokOptimizationGoal === 'VALUE' && !value) {
         //         callback(new Error('请选择价值优化窗口期'));
         //       } else {
         //         callback();
         //       }
         //     }
         //   }
         // ],
         'tiktok_json.advertiserId': [
           {
             required: true,
             message: '请选择账户',
             trigger: 'change'
           }
         ]
      },
             groupNameMaps: {
         app: new Map(),
         location: new Map(),
         material: new Map(),
         title: new Map(),
         description: new Map(),
         resource: new Map()
       },
       // 新增：账户相关数据
       advertiserOptions: [],
       advertiserLoading: false,
       campaignOptions: [],
       campaignListLoading: false,
       // 设备机型相关数据
       deviceModelOptions: [],
       deviceModelLoading: false,
       // 安卓版本选项
       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: '10.1', label: 'Android 10.1' },
         { value: '10.2', label: 'Android 10.2' },
         { value: '10.3', label: 'Android 10.3' },
         { value: '10.5', label: 'Android 10.5' },
         { value: '10.6', label: 'Android 10.6' },
         { value: '11.0', label: 'Android 11.0' },
         { value: '12.0', label: 'Android 12.0' },
         { value: '13.0', label: 'Android 13.0' }
       ]
    }
  },
  computed: {
    // TikTok字段的计算属性
    tiktokOptimizationGoal: {
      get() {
        return this.form.tiktok_json ? this.form.tiktok_json.optimizationGoal : 'VALUE'
      },
      set(value) {
        if (!this.form.tiktok_json) {
          this.form.tiktok_json = {}
        }
        this.form.tiktok_json.optimizationGoal = value
      }
    },
    tiktokDeepBidType: {
      get() {
        return this.form.tiktok_json ? this.form.tiktok_json.deepBidType : 'VO_MIN_ROAS'
      },
      set(value) {
        if (!this.form.tiktok_json) {
          this.form.tiktok_json = {}
        }
        this.form.tiktok_json.deepBidType = value
      }
    },
         // tiktokDeepCpaBid: {
     //   get() {
     //     return this.form.tiktok_json ? Number(this.form.tiktok_json.deepCpaBid) : 0
     //   },
     //   set(value) {
     //     if (!this.form.tiktok_json) {
     //       this.form.tiktok_json = {}
     //     }
     //     this.form.tiktok_json.deepCpaBid = Number(value)
     //   }
     // },
         // tiktokPlacements: {
     //   get() {
     //     return this.form.tiktok_json ? this.form.tiktok_json.placements : []
     //   },
     //   set(value) {
     //     if (!this.form.tiktok_json) {
     //       this.form.tiktok_json = {}
     //     }
     //     this.form.tiktok_json.placements = value
     //   }
     // },
    tiktokIsSmart: {
      get() {
        return this.form.tiktok_json ? this.form.tiktok_json.isSmart : false
      },
      set(value) {
        if (!this.form.tiktok_json) {
          this.form.tiktok_json = {}
        }
        this.form.tiktok_json.isSmart = value
      }
    },
    tiktokOptimizationEvent: {
      get() {
        return this.form.tiktok_json ? this.form.tiktok_json.optimizationEvent : ''
      },
      set(value) {
        if (!this.form.tiktok_json) {
          this.form.tiktok_json = {}
        }
        this.form.tiktok_json.optimizationEvent = value
      }
    },
    tiktokRoasBid: {
      get() {
        return this.form.tiktok_json ? Number(this.form.tiktok_json.roasBid) : 0
      },
      set(value) {
        if (!this.form.tiktok_json) {
          this.form.tiktok_json = {}
        }
        this.form.tiktok_json.roasBid = Number(value)
      }
    },
         // tiktokVboWindow: {
     //   get() {
     //     return this.form.tiktok_json ? this.form.tiktok_json.vboWindow : ''
     //   },
     //   set(value) {
     //     if (!this.form.tiktok_json) {
     //       this.form.tiktok_json = {}
     //     }
     //     this.form.tiktok_json.vboWindow = value
     //   }
     // },
    tiktokIsNewCampaign: {
      get() {
        return this.form.tiktok_json ? this.form.tiktok_json.isNewCampaign : true
      },
      set(value) {
        if (!this.form.tiktok_json) {
          this.form.tiktok_json = {}
        }
        this.form.tiktok_json.isNewCampaign = value
      }
    },
    tiktokAdvertiserId: {
      get() {
        return this.form.tiktok_json ? this.form.tiktok_json.advertiserId : ''
      },
      set(value) {
        if (!this.form.tiktok_json) {
          this.form.tiktok_json = {}
        }
        this.form.tiktok_json.advertiserId = value
      }
    },
    tiktokCampaignIdList: {
      get() {
        return this.form.tiktok_json ? this.form.tiktok_json.campaignIdList : []
      },
      set(value) {
        if (!this.form.tiktok_json) {
          this.form.tiktok_json = {}
        }
        this.form.tiktok_json.campaignIdList = value
      }
    },
    tiktokDeviceModels: {
      get() {
        return this.form.tiktok_json ? this.form.tiktok_json.deviceModels : []
      },
      set(value) {
        if (!this.form.tiktok_json) {
          this.form.tiktok_json = {}
        }
        this.form.tiktok_json.deviceModels = value
      }
    },
    tiktokMinAndroidVersion: {
      get() {
        return this.form.tiktok_json ? this.form.tiktok_json.minAndroidVersion : 'NONE'
      },
      set(value) {
        if (!this.form.tiktok_json) {
          this.form.tiktok_json = {}
        }
        this.form.tiktok_json.minAndroidVersion = value
      }
    }
  },
  created() {
    this.fetchData()
    this.fetchGroupNames()
  },
  methods: {
    async fetchData() {
      this.loading = true
      try {
        const response = await getCampaignTemplateList({
          page: this.currentPage,
          size: this.pageSize,
          ...this.condition
        })
        console.log(response)
        if (response.status === 200) {
          this.tableData = response.result.data.value
          this.total = response.result.total
        } else {
          this.$message.error(response.msg || '获取数据失败')
        }
      } catch (error) {
        console.error('获取数据失败:', error)
        this.$message.error('获取数据失败')
      }
      this.loading = false
    },

    async fetchGroupNames() {
      try {
        const [app, location, material, title, description, resource] = await Promise.all([
          axios.get(process.env.PUTIN_API + '/app-groups'),
          axios.get(process.env.PUTIN_API + '/location-groups'),
          axios.get(process.env.PUTIN_API + '/material-groups'),
          axios.get(process.env.PUTIN_API + '/title-groups'),
          axios.get(process.env.PUTIN_API + '/description-groups'),
          axios.get('http://localhost:8567/resource-groups/list')
        ])

        app.data.result.data.forEach(item => this.groupNameMaps.app.set(item.id, item.name))
        location.data.result.data.forEach(item => this.groupNameMaps.location.set(item.id, item.name))
        material.data.result.data.forEach(item => this.groupNameMaps.material.set(item.id, item.name))
        title.data.result.data.forEach(item => this.groupNameMaps.title.set(item.id, item.name))
        description.data.result.data.forEach(item => this.groupNameMaps.description.set(item.id, item.name))
        
        // 处理资源组数据
        if (resource.data && resource.data.result && resource.data.result.data) {
          resource.data.result.data.forEach(item => this.groupNameMaps.resource.set(item.id, item.name))
        }
      } catch (error) {
        console.error('获取组名称失败:', error)
      }
    },

    getAppGroupName(id) {
      return this.groupNameMaps.app.get(id) || id
    },
    getLocationGroupName(id) {
      return this.groupNameMaps.location.get(id) || id
    },
    getMaterialGroupName(id) {
      return this.groupNameMaps.material.get(id) || id
    },
    getTitleGroupName(id) {
      return this.groupNameMaps.title.get(id) || id
    },
    getDescriptionGroupName(id) {
      return this.groupNameMaps.description.get(id) || id
    },
    getResourceGroupName(id) {
      return this.groupNameMaps.resource.get(id) || id
    },

    // 根据平台类型获取标签类型
    getPlatformTagType(type) {
      switch (type) {
        case 1:
          return 'success'
        case 2:
          return 'warning'
        case 3:
          return 'info'
        default:
          return 'default'
      }
    },

    // 根据平台类型获取平台名称
    getPlatformName(type) {
      switch (type) {
        case 1:
          return 'Google'
        case 2:
          return 'TikTok'
        case 3:
          return 'Facebook'
        default:
          return '未知'
      }
    },

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

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

    showAddDialog() {
      this.dialogTitle = '新增模板'
      this.form = {
        name: '',
        platform: 2, // 默认选择TikTok平台
        campaign_type: 1,
        appStore: 3,
        daily_budget: 0,
        bidding_type: 5,
        target_roas: 0,
        app_groups: [],
        location_groups: [],
        material_groups: [],
        title_groups: [],
        description_groups: [],
        resource_groups: [],
                 // 初始化为对象而不是null
         tiktok_json: {
           optimizationGoal: 'VALUE',
           optimizationEvent: 'AD_REVENUE_VALUE',
           deepBidType: 'VO_MIN_ROAS',
           // deepCpaBid: 0,
           roasBid: 0,
           // vboWindow: '',
           // placements: [],
           isSmart: false,
           isNewCampaign: true,
           advertiserId: '',
           campaignIdList: [],
           deviceModels: [],
           minAndroidVersion: 'NONE'
         }
             }
       this.dialogVisible = true
       
       // 默认选择TikTok平台，获取广告主列表
       this.fetchAdvertiserList();
     },

         // 平台变化时的处理
     async handlePlatformChange(value) {
       // 当平台改变时，重新验证日预算字段
       this.$nextTick(() => {
         this.$refs.form.validateField('daily_budget');
         
         // 如果切换到TikTok平台，初始化tiktok_json
         if (value === 2) {
           // 使用Vue.set确保响应式
           this.$set(this.form, 'tiktok_json', {
             optimizationGoal: this.tiktokOptimizationGoal,
             optimizationEvent: this.tiktokOptimizationEvent,
             deepBidType: this.tiktokDeepBidType,
             // deepCpaBid: this.tiktokDeepCpaBid,
             roasBid: this.tiktokRoasBid,
             // vboWindow: this.tiktokVboWindow,
             // placements: this.tiktokPlacements,
             isSmart: this.tiktokIsSmart,
             isNewCampaign: this.tiktokIsNewCampaign,
             advertiserId: this.tiktokAdvertiserId,
             campaignIdList: this.tiktokCampaignIdList
           });
           
           // 获取广告主列表
           this.fetchAdvertiserList();
         } else {
           // 如果切换到其他平台，保存当前值但设置为null
           const currentValues = {
             optimizationGoal: this.tiktokOptimizationGoal,
             optimizationEvent: this.tiktokOptimizationEvent,
             deepBidType: this.tiktokDeepBidType,
             // deepCpaBid: this.tiktokDeepCpaBid,
             roasBid: this.tiktokRoasBid,
             // vboWindow: this.tiktokVboWindow,
             // placements: this.tiktokPlacements,
             isSmart: this.tiktokIsSmart,
             isNewCampaign: this.tiktokIsNewCampaign,
             advertiserId: this.tiktokAdvertiserId,
             campaignIdList: this.tiktokCampaignIdList
           };
           console.log('保存的TikTok配置:', currentValues);
           this.$set(this.form, 'tiktok_json', null);
         }
       });
     },

    // 修改编辑方法
    handleEdit(row) {
      this.dialogTitle = '编辑模板'
      console.log('编辑行数据:', row);

             // 处理tiktok_json字段
       let tiktokJsonData = {
         optimizationGoal: 'VALUE',
         optimizationEvent: 'AD_REVENUE_VALUE',
         deepBidType: 'VO_MIN_ROAS',
         // deepCpaBid: 0,
         roasBid: 0,
         // vboWindow: '',
         // placements: [],
         isSmart: false,
         isNewCampaign: true,
         advertiserId: '',
         campaignIdList: [],
         deviceModels: [],
         minAndroidVersion: '11.0'
       };

      if (row.platform === 2) {
        try {
          // 确保正确解析tiktok_json字段
          if (row.tiktok_json) {
            const parsedData = typeof row.tiktok_json === 'string' ? 
              JSON.parse(row.tiktok_json) : row.tiktok_json;
            
            console.log('解析后的TikTok数据:', parsedData);

                         // 使用解构赋值来合并默认值和已有数据，确保类型转换
             tiktokJsonData = {
               optimizationGoal: parsedData.optimizationGoal || 'VALUE',
               optimizationEvent: parsedData.optimizationEvent || '',
               deepBidType: parsedData.deepBidType || 'VO_MIN_ROAS',
               // deepCpaBid: parsedData.deepCpaBid !== undefined && parsedData.deepCpaBid !== null ? 
               //   Number(parsedData.deepCpaBid) : 0,
               roasBid: parsedData.roasBid !== undefined && parsedData.roasBid !== null ? 
                 Number(parsedData.roasBid) : 0,
               // vboWindow: parsedData.vboWindow || '',
               // placements: Array.isArray(parsedData.placements) ? [...parsedData.placements] : [],
               isSmart: typeof parsedData.isSmart === 'boolean' ? parsedData.isSmart : false,
               isNewCampaign: typeof parsedData.isNewCampaign === 'boolean' ? parsedData.isNewCampaign : true,
               advertiserId: parsedData.advertiserId || '',
               campaignIdList: Array.isArray(parsedData.campaignIdList) ? [...parsedData.campaignIdList] : [],
               deviceModels: Array.isArray(parsedData.deviceModels) ? [...parsedData.deviceModels] : [],
               minAndroidVersion: parsedData.minAndroidVersion || 'NONE'
             };
          }
        } catch (error) {
          console.error('解析TikTok配置失败:', error);
          // 保持默认值
        }
      }

      // 设置表单数据
      const formData = {
        ...row,
        app_groups: Array.isArray(row.app_groups) ? [...row.app_groups] : [],
        location_groups: Array.isArray(row.location_groups) ? [...row.location_groups] : [],
        material_groups: Array.isArray(row.material_groups) ? [...row.material_groups] : [],
        title_groups: Array.isArray(row.title_groups) ? [...row.title_groups] : [],
        description_groups: Array.isArray(row.description_groups) ? [...row.description_groups] : [],
        resource_groups: Array.isArray(row.resource_groups) ? [...row.resource_groups] : (row.resource_group_id ? [row.resource_group_id] : [])
      };

             // 使用Vue.set确保响应式更新
       this.$set(this, 'form', formData);
       this.$nextTick(() => {
         // 在下一个tick更新tiktok_json，确保响应式
         this.$set(this.form, 'tiktok_json', tiktokJsonData);
         console.log('设置后的表单数据:', this.form);
         
         // 如果是TikTok平台，获取广告主列表
         if (row.platform === 2) {
           this.fetchAdvertiserList();
         }
       });

       this.dialogVisible = true;
    },

    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该模板吗？', '提示', {
          type: 'warning'
        })

        const response = await deleteCampaignTemplate(row.id)
        if (response.status === 200) {
          this.$message.success('删除成功')
          this.fetchData()
        } else {
          this.$message.error(response.msg || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          this.$message.error('删除失败')
        }
      }
    },

    async submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          // 创建一个新的表单数据对象
          const formData = {
            ...this.form,
            app_groups: Array.isArray(this.form.app_groups) ? [...this.form.app_groups] : [],
            location_groups: Array.isArray(this.form.location_groups) ? [...this.form.location_groups] : [],
            material_groups: Array.isArray(this.form.material_groups) ? [...this.form.material_groups] : [],
            title_groups: Array.isArray(this.form.title_groups) ? [...this.form.title_groups] : [],
            description_groups: Array.isArray(this.form.description_groups) ? [...this.form.description_groups] : [],
            resource_groups: this.form.resource_groups
          };

          // 如果是TikTok平台，处理tiktok_json
          if (formData.platform === 2) {
                         const tiktokData = {
               optimizationGoal: this.tiktokOptimizationGoal,
               optimizationEvent: this.tiktokOptimizationEvent,
               deepBidType: this.tiktokDeepBidType,
               // deepCpaBid: this.tiktokDeepCpaBid,
               roasBid: this.tiktokRoasBid,
               // vboWindow: this.tiktokVboWindow,
               // placements: Array.isArray(this.tiktokPlacements) ? [...this.tiktokPlacements] : [],
               isSmart: this.tiktokIsSmart,
               isNewCampaign: this.tiktokIsNewCampaign,
               advertiserId: this.tiktokAdvertiserId,
               campaignIdList: Array.isArray(this.tiktokCampaignIdList) ? [...this.tiktokCampaignIdList] : [],
               deviceModels: Array.isArray(this.tiktokDeviceModels) ? [...this.tiktokDeviceModels] : [],
               minAndroidVersion: this.tiktokMinAndroidVersion
             };
            
            console.log('提交前的TikTok数据:', tiktokData);
            formData.tiktok_json = JSON.stringify(tiktokData);
          } else {
            formData.tiktok_json = null;
          }

          console.log('提交的表单数据:', formData);

          try {
            let response;
            if (formData.id) {
              response = await updateCampaignTemplate(formData);
            } else {
              response = await createCampaignTemplate(formData);
            }

            if (response.status === 200) {
              this.$message.success(formData.id ? '更新成功' : '创建成功');
              this.dialogVisible = false;
              this.fetchData();
            } else {
              this.$message.error(response.msg || (formData.id ? '更新失败' : '创建失败'));
            }
          } catch (error) {
            console.error(formData.id ? '更新失败:' : '创建失败:', error);
            this.$message.error(formData.id ? '更新失败' : '创建失败');
          }
        }
      });
    },

    handleAppGroupChange() {
      this.fetchData()
    },
    handleLocationGroupChange() {
      this.fetchData()
    },
    handleMaterialGroupChange() {
      this.fetchData()
    },
    handleTitleGroupChange() {
      this.fetchData()
    },
    handleDescriptionGroupChange() {
      this.fetchData()
    },

         // 处理优化目标变化
     handleOptimizationGoalChange(value) {
       // 当优化目标改变时，清空相关字段
       this.tiktokOptimizationEvent = '';
       this.tiktokDeepBidType = '';
       this.tiktokRoasBid = 0;
       // this.tiktokVboWindow = '';

       // 如果选择的是安装，则不需要优化事件和深度出价类型
       if (value === 'INSTALL') {
         this.tiktokOptimizationEvent = '';
         this.tiktokDeepBidType = '';
         this.tiktokRoasBid = 0;
         // this.tiktokVboWindow = '';
       }
     },

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

     // 获取广告主列表
     async fetchAdvertiserList() {
       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 (this.advertiserOptions.length > 0) {
             this.tiktokAdvertiserId = 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) {
      if (!advertiserId) {
        this.campaignOptions = [];
        this.tiktokCampaignIdList = [];
        this.deviceModelOptions = [];
        this.tiktokDeviceModels = [];
        return;
      }

      // 保存当前选中的设备机型
      const currentDeviceModels = [...this.tiktokDeviceModels];

      await this.fetchCampaignList(advertiserId);
      await this.fetchDeviceModelList(advertiserId);
      
      // 如果之前有选中的设备机型，且新账户的设备机型列表中包含这些机型，则保持选中状态
      if (currentDeviceModels.length > 0) {
        this.$nextTick(() => {
          const availableDeviceModels = this.deviceModelOptions.map(item => item.device_model_id);
          const validDeviceModels = currentDeviceModels.filter(modelId => 
            availableDeviceModels.includes(modelId)
          );
          
          if (validDeviceModels.length > 0) {
            this.tiktokDeviceModels = validDeviceModels;
            console.log('保持设备机型选择:', validDeviceModels);
          } else {
            // 如果之前的设备机型在新账户中不可用，则设置默认值
            this.setDefaultDeviceModels();
            console.log('设备机型在新账户中不可用，已设置默认值');
          }
        });
      } else {
        // 如果是新增模板且没有之前的设备机型选择，设置默认值
        if (!this.form.id) {
          this.setDefaultDeviceModels();
        }
      }
    },

     // 获取计划列表
     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.tiktokCampaignIdList = [];
         } 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);
           
           // 如果是新增模板（没有ID），设置默认选中的设备机型
           if (!this.form.id) {
             this.setDefaultDeviceModels();
           }
         } else {
           this.$message.error(response.msg || '获取设备机型列表失败');
         }
       } catch (error) {
         console.error('获取设备机型列表失败:', error);
         this.$message.error('获取设备机型列表失败');
       } finally {
         this.deviceModelLoading = false;
       }
     },

     // 设置默认设备机型
     setDefaultDeviceModels() {
       // 默认全选所有可用的安卓设备机型
       if (this.deviceModelOptions.length > 0) {
         const allDeviceModelIds = this.deviceModelOptions.map(device => device.device_model_id);
         this.tiktokDeviceModels = allDeviceModelIds;
         console.log('设置默认全选设备机型:', allDeviceModelIds);
       }
     },
  }
}
</script>

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

.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 {
  margin-top: 20px;
  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;
}
</style>
