
3<template>
  <div class="app-container">
    <!-- 创建投放时 格式化你的表单 -->
    <el-row>
      <el-button
        @click="clearAllData()"
        type="primary"
        style="margin-bottom: 20px"
      >
        Google投放
      </el-button>
<!--      <el-button type="primary" @click="ks_drawerShow = true"-->
<!--        >快手平台投放</el-button-->
<!--      >-->
    </el-row>

    <el-select
      v-model="putinBaseInfo.pkg"
      filterable
      clearable
      placeholder="选择应用"
      style="width: 200px"
      @change="putinFetchPutinTasks"
    >
      <el-option
        v-for="item in pkgList"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      >
      </el-option>
    </el-select>

    <el-button
      @click="putinFetchPutinTasks"
      type="primary"
      style="margin-bottom: 20px"
    >
      刷新
    </el-button>

    <el-button
      v-if="timer === ''"
      @click="executeTask"
      type="primary"
      style="margin-bottom: 20px"
    >
      开启自动刷新
    </el-button>
    <el-button
      v-else
      @click="closeExecuteTask"
      type="primary"
      style="margin-bottom: 20px"
    >
      关闭自动刷新
    </el-button>

    <el-table :data="tableData" border stripe v-loading="loading">
      <el-table-column type="expand" label="展开" width="40" fixed="left">
        <template slot-scope="props">
          <el-table :data="props.row.advertisers" border stripe>
            <el-table-column
              align="center"
              label="账户ID"
              prop="accountId"
              width="200px"
            />
            <el-table-column
              align="center"
              label="广告主名"
              prop="advertiserName"
            />
            <el-table-column
              align="center"
              label="广告主ID"
              prop="advertiserId"
            />
            <el-table-column
              align="center"
              label="转化ID"
              prop="conversionId"
            />
            <el-table-column align="center" label="计划进度">
              <template slot-scope="scope">
                <el-progress
                  color="#409eff"
                  :text-inside="true"
                  :stroke-width="24"
                  :percentage="scope.row.currentPlanProcessRatio"
                  show-text
                  status="success"
                  >计划进度</el-progress
                >
              </template>
            </el-table-column>
            <el-table-column align="center" label="创意进度">
              <template slot-scope="scope">
                <el-progress
                  :text-inside="true"
                  :stroke-width="24"
                  :percentage="scope.row.currentCreativeProcessRatio"
                  show-text
                  status="success"
                  >创意进度</el-progress
                >
                <div>
                  {{
                    scope.row.currentCreativeProcess
                      ? scope.row.currentCreativeProcess
                      : 0
                  }}(当前) /
                  {{ scope.row.totalPlan ? scope.row.totalPlan : 0 }}(总共)
                </div>
              </template>
            </el-table-column>
            <el-table-column width="200px">
              <div slot-scope="scope">
                <el-switch
                  active-text="开启"
                  inactive-text="关闭"
                  :value="scope.row.status === 1"
                  @change="
                    scope.row.status === 1
                      ? (scope.row.status = 0)
                      : (scope.row.status = 1);
                    APIswitchPutinAdvertise(scope);
                  "
                ></el-switch>
              </div>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="投放ID"
        prop="id"
        width="70"
        fixed="left"
      />
      <el-table-column
        align="center"
        label="任务名"
        width="200"
        prop="taskName"
        fixed="left"
      />
      <el-table-column
        align="center"
        label="目标应用"
        prop="appName"
        width="100px"
      />
      <el-table-column
        align="center"
        label="素材状态"
        prop="materialUploadStatus"
        width="100px"
      >
        <template slot-scope="scope">
          <!--    素材上传状态 0. 未上传  1. 等待上传   2. 已经上传-->
          <Tag color="warning" v-if="scope.row.materialUploadStatus === 0">
            未上传
          </Tag>
          <Tag color="primary" v-else-if="scope.row.materialUploadStatus === 1">
            等待上传中
          </Tag>
          <Tag color="success" v-else-if="scope.row.materialUploadStatus === 2">
            上传成功
          </Tag>
          <Tag color="danger" v-else-if="scope.row.materialUploadStatus === 3">
            上传失败
          </Tag>
          <Tag
            color="info"
            effect="dark"
            v-else-if="scope.row.putinStatus === 4"
          >
            正在投放中
          </Tag>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="投放状态"
        prop="putinStatus"
        width="150px"
      >
        <template slot-scope="scope">
          <!--    0.未开启   1. 开启   2.完成   3.失败 -->
          <Tag color="warning" v-if="scope.row.putinStatus === 0"> 未开启 </Tag>
          <Tag
            color="info"
            effect="dark"
            v-else-if="scope.row.putinStatus === 1"
          >
            已开启-等待投放中
          </Tag>
          <Tag color="success" v-else-if="scope.row.putinStatus === 2">
            投放完成
          </Tag>
          <Tag color="danger" v-else-if="scope.row.putinStatus === 3">
            投放失败
          </Tag>
          <Tag
            color="info"
            effect="dark"
            v-else-if="scope.row.putinStatus === 4"
          >
            正在投放中
          </Tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="上传进度" min-width="50">
        <template slot-scope="scope">
          <el-progress
            :text-inside="true"
            :stroke-width="24"
            :percentage="scope.row.uploadProcess"
            :show-text="true"
            status="success"
          ></el-progress>
          <div>{{ scope.row.uploadProcessDesc }}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="投放进度" min-width="50">
        <template slot-scope="scope">
          <el-progress
            :text-inside="true"
            :stroke-width="24"
            :percentage="scope.row.process"
            :show-text="true"
            status="success"
          ></el-progress>
          <div>
            {{
              scope.row.currentTotalCreative
                ? scope.row.currentTotalCreative
                : 0
            }}(当前) /
            {{ scope.row.taskTotalPlan ? scope.row.taskTotalPlan : 0 }}(总共)
          </div>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="执行时间(s)"
        prop="executeTime"
        width="80px"
      ></el-table-column>
      <el-table-column align="center" label="操作" width="250" fixed="right">
        <template slot-scope="scope">
          <div class="operationBtn">
            <el-button
              size="mini"
              type="success"
              @click="APIopPutinTask(scope.row.id, 1)"
              v-if="scope.row.materialUploadStatus === 0"
              >上传素材</el-button
            >
            <el-button
              size="mini"
              type="success"
              @click="APIopPutinTask(scope.row.id, 2)"
              v-if="
                scope.row.materialUploadStatus === 2 &&
                scope.row.putinStatus === 0
              "
            >
              开启投放
            </el-button>
            <el-button
              size="mini"
              type="primary"
              @click="clickeEitor(scope.row)"
            >
              编辑
            </el-button>
            <el-popconfirm
              confirm-button-text="确定"
              confirm-button-type="danger"
              cancel-button-text="取消"
              cancel-button-type="primary"
              icon="el-icon-refresh"
              icon-color="red"
              title="确定重置吗？"
              @onConfirm="resetStatus('upload', scope.row.id)"
            >
              <el-button slot="reference" size="mini" type="danger">
                重置上传状态
              </el-button>
            </el-popconfirm>
            <el-button
              size="mini"
              type="primary"
              @click="clonePutinTask(scope.row)"
              >克隆</el-button
            >
            <el-popconfirm
              confirm-button-text="确定"
              confirm-button-type="danger"
              cancel-button-text="取消"
              cancel-button-type="primary"
              icon="el-icon-refresh"
              icon-color="red"
              title="确定重置吗？"
              @onConfirm="resetStatus('putin', scope.row.id)"
            >
              <el-button slot="reference" size="mini" type="danger">
                重置投放状态
              </el-button>
            </el-popconfirm>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- id分页 -->
    <el-pagination
      v-show="paginationInfo.total > 0"
      background
      layout="total, prev, pager, next, sizes"
      style="text-align: right; margin-top: 20px"
      :total="paginationInfo.total"
      :page-sizes="[10, 20, 50]"
      :page-size="paginationInfo.size"
      :current-page="paginationInfo.page"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
      @prev-click="prevPageData"
      @next-click="nextPageData"
    >
    </el-pagination>

    <el-drawer
      direction="rtl"
      size="88%"
      :visible.sync="drawer"
      :before-close="handleClose"
      :show-close="false"
    >
      <div class="row-center-center drawer-border">
        <div style="width: 20%">
          <div>
            <el-button
              @click="handleClose"
              style="margin-bottom: 20px; margin-right: 20px"
              type="primary"
              >&lt;&lt;返回</el-button
            >
            <span style="font-size: 16px">创建投放</span>
          </div>
          <el-steps class="zf-steps" direction="vertical" :active="3">
            <template v-for="(item, index) of stepList">
              <el-step :title="item.title" :key="index"></el-step>
            </template>
          </el-steps>
        </div>

        <div class="border-right"></div>

        <div class="drawer-list">
          <!-- 投放任务 -->
          <div class="drawer-item border-bottom">
            <div class="drawer-item-title">投放任务</div>

            <div class="drawer-item-con">
              <el-form ref="form">
                <el-form-item label="选择应用">
                  <el-select
                    v-model="putinTask.appInfo"
                    filterable
                    clearable
                    placeholder="请选择"
                    style="width: 200px"
                    @change="handleChangeApp"
                  >
                    <el-option
                      v-for="item in pkgList"
                      :key="item.value"
                      :label="item.label"
                      :value="item"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>

                <el-form-item label="任务名称">
                  <el-input
                    class="drawer-input"
                    style="width: 500px"
                    v-model="putinTask.taskName"
                  ></el-input>
                </el-form-item>


                <el-form-item label="选择投放账户">

                  <el-transfer
                    style="text-align: left; display: inline-block"
                    v-model="putinTask.putinAccounts"
                    filterable
                    width="100%"
                    height="360px"
                    :left-default-checked="[]"
                    :right-default-checked="[]"
                    :titles="['源列表', '目标列表']"
                    :button-texts="['', '']"
                    :format="{
                      noChecked: '${total}',
                      hasChecked: '${checked}/${total}'
                    }"
                    :data="generateData"
                    :filter-method="filterAccount"
                    @change="handleChange"


                    >
                    <span slot-scope="{ option }">{{ option.label }} - {{ option.key }}</span>
                  </el-transfer>

                </el-form-item>
              </el-form>
            </div>
          </div>

          <!-- 投放范围和位置 -->
          <div class="drawer-item">
            <div class="drawer-item-title" style="font-weight: 700">
              广告系列
            </div>
            <div class="drawer-item-title">选择广告系列类型</div>
            <div class="drawer-item-con">
              <el-form ref="form">
                <el-form-item label="选择广告系列子类型">
                  <el-select
                    v-model="putinTask.campaignType"
                    placeholder=""
                    default-first-option
                    style="width: 200px"
                  >
                    <el-option
                      v-for="item in [{'name': '应用安装', 'value': 1, 'disabled': false}, { 'name': '应用互动', 'value': 2 , 'disabled': true}, { 'name': '应用预注册', 'value': 3 , 'disabled': true}]"
                      :key="item.value"
                      :label="item.name"
                      :value="item.value"
                      :disabled="item.disabled"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>

                <el-form-item label="选择移动应用平台">

                  <el-select
                    v-model="putinTask.appStore"
                    placeholder=""
                    default-first-option
                    style="width: 200px"
                  >
                    <el-option
                      v-for="item in [{'label': 'Android', 'value': 3, 'disabled': false}, {'label': 'iOS', 'value': 2, 'disabled': true}]"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                      :disabled="item.disabled"
                    >
                    </el-option>
                  </el-select>

                </el-form-item>
              </el-form>
            </div>
          </div>

          <!-- 投放目标 -->
          <div class="drawer-item  border-bottom">
            <div class="drawer-item-title">广告系列名称</div>
            <div class="drawer-item-con">
              <el-input
                class="apk-input"
                v-model="putinTask.campaignName"
              ></el-input>
            </div>
          </div>


          <div class="drawer-item  border-bottom" style="padding-bottom: 20px">
            <div class="drawer-item-title">地理位置</div>
            <div class="drawer-item-con">
              <CountrySelector v-model="putinTask.locations" />
            </div>

            <div class="drawer-item-title">语言</div>
            <div class="drawer-item-con">
              <LanguageSelector v-model="putinTask.languages" />
            </div>

            <div class="drawer-item-title">开始日期和结束日期</div>
            <div class="drawer-item-con">
              <el-form ref="form">
                <el-form-item label="开始日期">
                  <el-date-picker
                    v-model="putinTask.startDate"
                    align="right"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="选择日期">
                  </el-date-picker>
                </el-form-item>

                <el-form-item label="结束日期">
                  <el-date-picker
                    v-model="putinTask.endDate"
                    align="right"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="选择日期">
                  </el-date-picker>
                </el-form-item>
              </el-form>
            </div>
          </div>

          <!-- 预算和出价 -->
          <div class="drawer-item border-bottom">
            <div class="drawer-item-title">预算</div>
            <el-form ref="form">
              <el-form-item label="广告预算" prop="budget">

                <el-input
                  v-model="putinTask.dailyBudget"
                  placeholder="请输入广告预算"
                  @blur="formatBudget"
                  style="width: 30%"
                >
                  <template slot="prepend">$</template>
                </el-input>
              </el-form-item>
            </el-form>
          </div>

          <!-- 出价 -->
          <div class="drawer-item border-bottom">
            <div class="drawer-item-title">出价</div>

            <div class="drawer-item-con">
              <el-form ref="form">
                <el-form-item label="转化目标">
                  <el-select
                    v-model="putinTask.biddingStrategyGoalType"
                    placeholder=""
                    default-first-option
                    style="width: 200px"
                  >
                    <el-option
                      v-for="item in [{'name': '安装量', 'value': 2, 'disabled': false}, {'name': '应用内操作次数', 'value': 3, 'disabled': true}, {'name': '应用内操作价值', 'value': 5, 'disabled': false}]"
                      :key="item.value"
                      :label="item.name"
                      :value="item.value"
                      :disabled="item.disabled"
                    >
                    </el-option>
                  </el-select>

                </el-form-item>
                <el-form-item v-if="putinTask.biddingStrategyGoalType == 2">
                  <el-checkbox v-model="putinTask.isSetTargetCpa" label="设置目标每次安装费用"/>
                </el-form-item>

                <el-form-item label="目标每次安装费用" v-if="putinTask.biddingStrategyGoalType == 2 && putinTask.isSetTargetCpa">
                  <el-input v-model="putinTask.targetCpa" style="width: 30%"/>
                  <template slot="prepend">$</template>
                </el-form-item>

                <el-form-item label="事件列表">
                  <el-button @click="getConversionAction">刷新</el-button>
                  <el-table :data="putinTask.conversionActions">
                    <el-table-column label="账户ID" prop="actId"/>
                    <el-table-column label="转化名称" prop="firebaseEventName"/>
                    <el-table-column label="转化类型" prop="actionCategory"/>
                  </el-table>

                </el-form-item>

                <el-form-item label="目标广告支出回报率">
                  <el-input v-model="putinTask.targetRoas" style="width: 30%"/>
                  <template slot="prepend">$</template>
                </el-form-item>



              </el-form>
            </div>
          </div>

          <div class="drawer-item border-bottom">
            <div class="drawer-item-title" style="font-weight: 700">
              广告组
            </div>

            <div class="drawer-item-title">广告组名称</div>
            <div class="drawer-item-con">
              <el-input
                class="apk-input"
                v-model="putinTask.adGroupName"
                />
            </div>

          </div>
          <!-- 制作创意 -->
          <div class="drawer-item border-bottom">
            <div class="drawer-item-title">制作创意</div>
            <div class="drawer-item-con">
              <el-form ref="form">
                <el-form-item label="选择图片">
                  <ImageUploader @change="handleUploadChange"/>
                </el-form-item>
                <el-form-item label="选择 Youtube 视频">
                  <el-button type="primary" @click="openVideoDialog">加载视频列表</el-button>
                  <el-input v-model="videoUrlsString" placeholder="YouTube 链接将自动填充" :disabled="true" type="textarea" :rows="3"></el-input>
                  <el-dialog title="选择视频" :visible.sync="videoDialogVisible" width="70%" :modal-append-to-body="true" :append-to-body="true" >
                    <el-button type="primary" @click="fetchVideoList" :loading="videoListLoading" style="margin-bottom: 10px;">刷新视频列表</el-button>
                    <div class="video-list" style="display: flex; flex-wrap: wrap;">
                      <div v-for="video in videoDataList" :key="video.videoId" class="video-item" @click="toggleVideoSelection(video)" style="margin: 10px; text-align: center; cursor: pointer;">
                        <video :src="video.ossUrl" controls width="200"></video>
                        <p>{{ video.materialName }}</p>
                        <el-checkbox v-model="selectedVideoId" :label="video.videoId"></el-checkbox>
                      </div>
                    </div>
                    <span slot="footer" class="dialog-footer">
                          <el-button @click="videoDialogVisible = false">取 消</el-button>
                          <el-button type="primary" @click="confirmVideoSelection">确 定</el-button>
                    </span>
                  </el-dialog>
                </el-form-item>
              </el-form>
            </div>
          </div>

          <div class="drawer-item border-bottom">
            <div class="drawer-item-title">标题</div>
            <div class="drawer-item-con">
              <TextInputList v-model="putinTask.headlines" :maxLength="30"/>

            </div>
          </div>

          <div class="drawer-item border-bottom">
            <div class="drawer-item-title">广告内容描述</div>
            <div class="drawer-item-con">
              <TextInputList v-model="putinTask.descriptions" :maxLength="90"/>
            </div>
          </div>


          <!-- 提交 -->
          <div class="row-center-end" style="padding-right: 100px">
            <el-button
              type="primary"
              @click="putinCreatePutinTask()"
              :loading="submitBtnState"
            >
              提交
            </el-button>
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<style src="./index.css" scoped></style>

<style>
.el-form-item__content {
  padding-left: 70px;
  box-sizing: border-box;
}

.el-drawer__header {
  margin-bottom: 0;
}

.el-input-group__prepend {
  background-color: #fff;
}
</style>

<script>
import {
  putinFetchPutinTasks,
  getEnums,
  getBusinTextAdd,
  getBusinText,
  getBusinTextEdit,
} from "@/api/cloud";
import {
  opPutinTask,
  switchPutinAdvertise,
  resetPutinStatus,
} from "@/api/air_center";
import {
  menuSelectApps,
  materialGroupList,
  putinFetchAccount,
  putinFetchConvertIds,
  putinUpdateAdvertiseConversion,
  putinCreatePutinTask,
  getAdvList,
  getAdvertiseCount,
  fetchConversionAction,
  getYoutubeUploadDetaillist
} from "@/api/report";
import { dateOptions } from "@/assets/js/dateOptions";
import moment from "moment";
import treeTransfer from "el-tree-transfer"; // 引入

/* 引入快手投放子组件 */
import ksDrawer from "./KSPlat";

import SelectText from "./childComponents/SelectText";
import AddAdvGroup from "./childComponents/AddAdvGroup";
import TextTextarea from "./childComponents/TextTextarea";
import CountrySelector from "./childComponents/CountrySelector";
import LanguageSelector from "./childComponents/LanguageSelector";
import TextInputList from "./childComponents/TextInputList";
import ImageUploader from "./childComponents/ImageUploader.vue";
import YouTubeVideoInput from "./childComponents/YouTubeVideoInput.vue";

import { stepList } from "./childComponents/util";

import { trim } from "@/utils/utils";

export default {
  components: {
    LanguageSelector,
    treeTransfer,
    SelectText,
    ksDrawer,
    AddAdvGroup,
    TextTextarea,
    CountrySelector,
    TextInputList,
    ImageUploader,
    YouTubeVideoInput
  }, // 注册
  watch: {
    selectedVideoId: {
      handler(newVal) {
        this.putinTask.videoUrls = newVal.map(videoId => `https://www.youtube.com/watch?v=${videoId}`);
        this.updateVideoUrlsString();
      },
      deep: true
    }
  },
  data() {
    return {
      tagId: "",
      textList: [], // 文案库列表 前50个
      paginationInfo: {
        total: 0,
        size: 10,
        page: 1,
      }, // 分页信息

      loading: false,
      isTargetCpaShow: true, // 是否展示设置安装单价的表单
      tryItOut: 0, //试玩搭配，默认不启用
      tryMaterialList: [], //试玩素材列表
      submitBtnState: false, //防止重复提交控制
      ks_drawerShow: false, // 快手抽屉控制
      exclude_audience: [], // 排除人群
      childTags: [
        { label: "定向", type: 0 },
        { label: "排除", type: 1 },
      ], // 同时定向和排除的选择
      childTagsChecked: "定向",
      custom_audienc: [], // 人群定向包数据
      /* 同时定向排除 */
      together_id1: [],
      together_id2: [],
      custom_audienc_id: [], // 人群定向包id
      isShow: true, // 是否显示选择框
      is_show_bid: false,
      indexValue: null, // 显示哪一个选择框
      advOptions: [], // 广告主下的广告组列表
      indexAdv: null, // 是否显示选择框
      activeName: "first",
      /* 自定义人群做限制 */
      crowd: [
        { label: "不限", type: 0 },
        { label: "自定义人群", type: 1 },
      ],
      countries: [],
      languages: [],
      startDate: '',
      endDate: '',
      dailyBudget: '1.00',
      crowdValue: "不限", // 自定义人群的值
      crowdAdvertiserId: "",
      /* 测试假数据 使用 */
      shamDataTest: "同时定向排除",
      shamDataTestArr: ["定向", "排除", "同时定向排除"],
      logicShow: false, // 控制定向逻辑是否显示

      directPkg: [], // 历史定向包
      directId: "", // 历史定向包id

      appId: "",
      ifDoublePrice: false,
      bid_type: "only",
      uploadAction: "http://api.putin.zhangxindiet.com/v1/oe/upload",
      dateOptions: dateOptions,
      materialGroupDesc: "",
      callActionList: [], //行动号召列表
      arrays: {
        creativeTags: [], // 创意标签
        allowAge: [""], // 用户定向: 年龄
        allowNetwork: [""], // 用户定向: 网络
        allowCarrier: [""], // 用户定向: 运营商
        textGroup: [], // 制作创意: 添加文案,
        productSellingPoints: [], // 推广卡片 商品卖点
      },

      allowDirect: "Both", // 定向、排除、同时定向排除 默认是同时定向排除

      putinBaseInfo: {
        id: "",
        taskName: "",
        selectAdvertisers: [], // 投放账户
        landingType: "APP", // 选择投放目的
        budgetMode: "BUDGET_MODE_INFINITE", // 广告组预算
        budget: "", // 广告组预算(值)
        campaignNum: "1", // 广告组数量
        planNum: "", // 计划数量/组
        creativeNum: "1", // 创意数量/计划
        putinTarget: "0",
        landMethod: 1, // 下载
        pkg: "", // 投放目标: 选择应用
        landUrl: "",
        webUrl: "",
        deliveryRange: "DEFAULT", // 投放范围
        unionVideoType: "", // 投放形式
        smartBidType: "SMART_BID_CUSTOM",
        flowControlMode: "FLOW_CONTROL_MODE_FAST",
        planBudgetMode: "BUDGET_MODE_DAY",
        planBudget: "",
        scheduleType: "SCHEDULE_START_END", // 投放时间

        scheduleTime: "", // 选择时段
        pricing: "PRICING_OCPM",
        cpaBid: "",
        deepBidType: "DEEP_BID_MIN",
        deepCpabid: "",
        advertCampaigns: [], // 广告主下的广告组选择
        adjustCpa: 0, // 是否调整自动出价
        openLadder: 0, // 判断是否是阶梯出价
        ladderPriceLow: 0, // 阶梯价低位
        ladderPriceHigh: 0, // 阶梯价高位
        ladderStep: 0, // 阶梯价步长
        putinStrag: 'default', //
      },
      // 任务保存数据
      putinTask: {
        taskName: '',
        putinAccounts: [],
        campaignName: '',
        campaignType: 1,
        biddingStrategyGoalType: 2,
        dailyBudget: 0.0,
        isSetTargetCpa: true,
        targetCpa: 0.0,
        targetRoas: 0,
        appInfo: "",
        appId: "",
        appStore: 3,
        startDate: '',
        endDate: '',
        locations: [],
        languages: [],
        adGroupName: '',
        headlines: [],
        descriptions: [],
        imageAssets: [],
        videoAssets: [],
        videoUrls: [],
        conversionActions: []
      },


      // 用户定向
      orientation: {
        id: "",
        allowCity: "", // 城市
        allowGender: "NONE", // 性别(默认: 不限)
        allowAge: "", // 年龄
        interestActionMode: "RECOMMEND", // 行为兴趣(默认： 系统推荐)
        allowNetwork: "", // 网络
        allowCarrier: "", // 运营商
        selectHisPack: "", // 这个字段是用来标识你是否是使用历史定向包的
        retargetingTagsInclude: "", // 定向
        retargetingTagsExclude: "", // 排除
      },

      makeCreative: {
        id: "",
        adSource: "",
        materialGroupId: "",
        creativeComposeMethod: 2,

        verticalVideo: "",
        horizontalVideo: "",
        bigImage: "",
        smallImage: "",
        verticalBigImage: "",

        textGroup: "", // 制作创意: 添加文案
        textNum: 5, //文案数

        promotionCardImg: "",
        productImageId: "", // 商品卡片图片（主图）
        productDescription: "", // 推广卡片 标题(描述)
        productSellingPoints: "", // 推广卡片 商品卖点
        enablePersonalAction: 1, // 是否使用智能优选，1为使用，0为不使用
        actionText: "",
        subTitle: "", // 制作创意: 副标题

        adComment: 0,
        advanceCreative: 0,
        isPresentedVideo: 1,
        bestCreativeDerivePlan: 1,
        brandMainPage: 1,

        creativeCategory: "", // 创意分类
        creativeFullCategory: "", // 创意分类所有id, 便于回显
        creativeCategoryGroup: [], // 创意分类多选
        creativeTags: "", // 创意标签

        creativeMaterialMode: "STATIC_ASSEMBLE", // 默认程序化创意
        creativeShowMode: 1, // 创意展现方式， 默认优选模式

        gdtMonitorUrl: "",
        putinInventoryType: "smartInventory", // 投放位置的类型
        putinInventory: "", // 投放位置的值
        kuaishouMonitorUrl: "",

        smartInventory: 1,
        openPlay: "no", //开启试玩素材选择yes否则是no

        // toutiaoMonitorUrl: "https://report.zhangxinhulian.com/" // 检测链接: 点击
      },
      is_card: true,
      promotionCard: "",
      uploadData: {
        accountId: "",
        advertiserId: "",
        resType: "image", // 1：视频，2：图片
        pkg: "",
      },

      mode: "transfer", // 切换模式, 现有树形穿梭框模式transfer 和通讯录模式addressList
      title: ["全选", "取消全选"],
      generateData: [], // 投放账户源数据
      toData: [], // 投放账户已选中数据
      targetList: [],

      platformId: 1, // 平台（默认：巨量引擎）
      globalEnums: {}, // 全局配置数据
      tableData: [],
      tableDatacon: [],
      drawer: false,

      stepList: stepList,

      pkgList: [],
      materialList: [],
      portfolioValue: 1,
      portfolioList: [
        {
          value: 1,
          label: "系统随机",
        },
        {
          value: 2,
          label: "自定义",
        },
      ],

      putinTarget: [
        {
          name: "不限",
          value: 1,
        },
        {
          name: "指定时段",
          value: 2,
        },
      ],

      targetItemList: [], // 转化目标列表
      targetData: "",
      bidPrice: "", // 目标价格
      changeBtnItem: {},

      inputVisible: false,
      inputValue: "",

      inputVisible2: false,
      inputValue2: "",

      inputValue5: "",

      inputVisibleTag: false,
      inputValueTag: "",

      inputVisible3: false,
      inputValue3: "",

      creativeCategoryDefault: [],
      creativeCategoryList: [], // 创意分类
      timer: "",
      activePutin: "newPutin",
      advGroupSelect: [],
      checkedAdvId: "", // 点击户时，选中的id
      videoDataList: [], // 存储通过 getYoutubeUploadDetaillist 获取的视频列表
      selectedVideoId: [], // 存储用户选择的视频的 videoId
      videoDialogVisible: false,
      videoListLoading: false
    };
  },

  computed: {
    showGroupBudget() {
      return this.putinBaseInfo.budgetMode === "BUDGET_MODE_DAY";
    },
    videoUrlsString() {
      return this.putinTask.videoUrls.join('\n');
    },
  },
  created() {
    this.putinTask.startDate = moment().subtract(0, "days").format("YYYY-MM-DD");

    this._menuSelectApps(); // 获取App名称配置列表
    this.APIGetEnums(); // 获取公共下拉框参数
    this.materialGroupList(); // 获取创建的素材组列表
    this.putinFetchPutinTasks(); // 获取投放任务列表
    // this.executeTask()
    this.APIGetBusinText();
  },
  mounted() {},
  destroyed() {
    // console.log("清除定时器：", this.timer);
    clearInterval(this.timer);
  },

  methods: {
    //创建投放重置数据
    clearAllData() {
      this.drawer = true; // 打开抽屉
      this.tryItOut = 0;
      this.tryMaterialList = []; //试玩素材列表
      //去除残留数据，重新格式化表单数据
      this.putinBaseInfo = {
        id: "",
        taskName: "",
        selectAdvertisers: [], // 投放账户
        landingType: "APP", // 选择投放目的
        budgetMode: "BUDGET_MODE_INFINITE", // 广告组预算
        budget: "", // 广告组预算(值)
        campaignNum: "1", // 广告组数量
        planNum: "", // 计划数量/组
        creativeNum: "1", // 创意数量/计划
        putinTarget: 1,
        landMethod: 1, // 下载
        pkg: "", // 投放目标: 选择应用
        landUrl: "",
        webUrl: "",
        deliveryRange: "DEFAULT", // 投放范围
        unionVideoType: "", // 投放形式
        smartBidType: "SMART_BID_CUSTOM",
        flowControlMode: "FLOW_CONTROL_MODE_FAST",
        planBudgetMode: "",
        planBudget: "",
        scheduleType: "SCHEDULE_FROM_NOW", // 投放时间

        scheduleTime: "", // 选择时段
        pricing: "PRICING_OCPM",
        cpaBid: "",
        deepBidType: "DEEP_BID_MIN",
        deepCpabid: "",
        advertCampaigns: [],
        adjustCpa: 0,
        openLadder: 0, // 判断是否是阶梯出价
        ladderPriceLow: 0, // 阶梯价低位
        ladderPriceHigh: 0, // 阶梯价高位
        ladderStep: 0, // 阶梯价步长
        putinStrag: 'default'
      };

    },

    executeTask() {
      this.timer = setInterval(() => {
        this.putinFetchPutinTasks();
      }, 10000);
      // console.log("开启定时器：", this.timer);
    },
    closeExecuteTask() {
      // console.log("清除定时器：", this.timer);
      clearInterval(this.timer);
      this.timer = "";
    },

    APIswitchPutinAdvertise(scope) {
      switchPutinAdvertise({ id: scope.row.mapId }).then((resp) => {});
    },
    // 上传图片成功
    imgSuccess(res, file, fileList) {
      this.makeCreative.promotionCardImg = res.result.data.url.url;
      this.makeCreative.productImageId = res.result.data.url.materialId;
    },

    change_putinInventory: function () {
      if (
        this.makeCreative.putinInventory.indexOf("INVENTORY_AWEME_FEED") != -1
      ) {
        this.is_card = true;
      } else {
        this.is_card = false;
      }
    },

    APIopPutinTask(taskId, action) {
      opPutinTask({ taskId: taskId, action: action }).then((res) => {
        if (res.status === 200) {
          this.$message({
            message: `操作:${taskId}成功`,
            type: "success",
          });
          this.putinFetchPutinTasks();
        } else {
          this.$message({
            message: `${res.msg}`,
            type: "warning",
          });
        }
      });
    },

    /* 获取文案库列表 这里只获取前50个 提供修改删除的操作 */
    APIGetBusinText() {
      let params = {
        appId: this.appId,
        size: 50,
      };
      getBusinText(params).then((res) => {
        // console.log("文案库列表111", res);
        this.textList = res.result.data.content;
      });
    },

    /* 修改文案 */
    APIGetBusinTextEdit(id, text) {
      let params = {
        id,
        text,
      };
      getBusinTextEdit(params).then((res) => {
        if (res.status === 200) {
          this.$message({
            message: "修改成功",
            type: "success",
          });
          this.tagId = "";
          this.APIGetBusinText(); // 修改成功重新获取列表
        }
      });
    },


    handleChange(value) {
      // console.log("创意分类改变：", value);
      this.makeCreative.creativeCategory = value[2];
      this.makeCreative.creativeFullCategory = JSON.stringify(value);
      console.log("huix", this.makeCreative.creativeFullCategory);
    },

    // 创建投放任务
    putinCreatePutinTask: function () {
      this.putinTask.appId = this.putinTask.appInfo.value
      this.loading = true
      this.putinTask.videoAssets = this.putinTask.videoUrls.map(obj => ({ url: obj, name: moment().format("YYYY-MM-DD HH:mm:ss")}));
      putinCreatePutinTask(this.putinTask)
        .then((res) => {
          if (res.status === 200) {
            this.putinFetchPutinTasks(); // 获取投放任务列表
            this.drawer = false; // 关闭抽屉
          }
          this.submitBtnState = false;
          this.loading = false;
        })
        .catch((res) => {
          this.$message.warning("提交失败!");
          this.submitBtnState = false;
          this.loading = false;
        });
    },

    // 获取转化ID列表
    changeBtn: function (item, index) {
      this.changeBtnItem = item;
      this.targetData = "";

      // 显示选择框
      this.isShow = true;
      this.is_show_bid = true;
      this.$refs.selectTarget.forEach((s, i) => {
        if (i === index) {
          this.indexValue = index;
        }
      });

      this.uploadData.accountId = item.pid;
      this.uploadData.advertiserId = item.id;

      putinFetchConvertIds({
        accountId: item.pid,
        advertiserId: item.id,
      }).then((res) => {
        this.targetItemList = res.result.data.content;
      });
    },

    visibleChangeTarget: function (callback) {
      // console.log("保存转化ID检查参数：", this);
      if (!callback) {
        putinUpdateAdvertiseConversion({
          advertiserId: this.changeBtnItem.id,
          conversionId: this.targetData,
          conversionName: this.changeBtnItem.nameTag,
        }).then((res) => {
          console.log("保存回调");
        });
      }
    },

    /* 当选择框失去焦点时 隐藏表单 */
    hiddenForm() {
      this.isShow = false;
    },

    // 转化目标中的target 改变
    changeTarget: function () {
      this.isShow = false; // 当表单里面的数据改变时 隐藏表单
      // 给targetList 拼接字段 nameTag
      for (let i = 0; i < this.targetList.length; i++) {
        if (this.targetList[i].id === this.changeBtnItem.id) {
          for (let j = 0; j < this.targetItemList.length; j++) {
            if (this.targetItemList[j].value === this.targetData) {
              this.targetList[i].nameTag = this.targetItemList[j].label;
            }
          }
          return;
        }
      }
    },

    // 价格输入框失去焦点的回调
    handleBidPrice(item) {
      if (this.bidPrice != "" && this.bidPrice * 1 > 0) {
        item.bidPrice = parseFloat(trim(this.bidPrice)).toFixed(2); // 给targetList 中添加的bidPrice字段设置值 用来显示
        putinUpdateAdvertiseConversion({
          advertiserId: this.changeBtnItem.id,
          conversionId: this.targetData,
          conversionName: this.changeBtnItem.nameTag,
          bidPrice: item.bidPrice,
        });
      }
      this.bidPrice = "";
      this.is_show_bid = false;
    },

    gettoData: function (toData) {
      // console.log("gettoData", JSON.stringify(toData, null, 4));
      for (let i = 0; i < toData.length; i++) {
        for (let j = 0; j < toData[i].children.length; j++) {
          // console.log("selectAdvertisers", toData[i].children[j].id)
          this.putinBaseInfo.selectAdvertisers.push(toData[i].children[j].id);
          this.targetList.push(toData[i].children[j]); // 组装投放目标列表
        }
      }
      for (let i = 0; i < this.targetList.length; i++) {
        this.targetList[i].advName = null;
        this.targetList[i].bidPrice = null;
      }
      console.log("targetList", this.targetList);
      // console.log("组装投放目标列表", this.targetList);
      // console.log("targetList回显:", JSON.stringify(this.targetList, null, 4));
    },


    // 获取投放账号列表
    putinFetchAccount: function () {
      putinFetchAccount({
        pkg: this.putinTask.appInfo.value,
      }).then((res) => {
        this.generateData = res.result.data;
        this.generateData  = this.generateData .map(obj => ({ key: obj, label: obj.advertiserName}));
        this.materialGroupList();
      });
    },

    // 关闭弹窗
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          this.putinBaseInfo = {};
          this.orientation = {};
          this.makeCreative = {};
          this.drawer = false;
          done();
        })
        .catch((_) => {});
    },

    // 获取App名称配置列表
    _menuSelectApps: function () {
      menuSelectApps({
        platformId: 5,
        menuCode: "game.Overview,android",
      }).then((res) => {
        this.pkgList = res.result.data;
      });
    },

    // 获取创建的素材组列表
    materialGroupList: function () {
      materialGroupList({
        pkg: this.putinTask.appInfo.value,
      }).then((res) => {
        this.materialList = res.result.data.content;
      });
    },

    // 获取公共下拉框参数
    APIGetEnums() {
      getEnums().then((res) => {
        this.globalEnums = res.result.data;
        this.globalEnums.gender = Object.values(this.globalEnums.gender);
        this.globalEnums.directLogic = Object.values(
          this.globalEnums.directLogic
        );
        // console.log("cccc", this.globalEnums.directLogic);
        this.globalEnums.deepBidType = Object.values(
          this.globalEnums.deepBidType
        );
        this.globalEnums.groupBudgetMode = Object.values(
          this.globalEnums.budgetMode
        ).filter((i) => i.value !== "BUDGET_MODE_TOTAL");
        this.globalEnums.age = Object.values(this.globalEnums.age);
        this.globalEnums.interestActionMode = Object.values(
          this.globalEnums.interestActionMode
        );
        this.globalEnums.smartBidType = Object.values(
          this.globalEnums.smartBidType
        );
        this.globalEnums.planBudgetMode = Object.values(
          this.globalEnums.budgetMode
        );
        this.globalEnums.flowControlMode = Object.values(
          this.globalEnums.flowControlMode
        );
        this.globalEnums.scheduleType = Object.values(
          this.globalEnums.scheduleType
        );
        this.globalEnums.putinLocation = Object.values(
          this.globalEnums.putinLocation
        );
        this.globalEnums.putinMediaLocation = Object.values(
          this.globalEnums.putinMediaLocation
        );
        this.globalEnums.sceneInventory = Object.values(
          this.globalEnums.sceneInventory
        );
        this.globalEnums.unionVideoType = Object.values(
          this.globalEnums.unionVideoType
        );
      });
    },

    // 获取投放任务列表
    putinFetchPutinTasks() {
      // this.loading = true;
      putinFetchPutinTasks({
        listData: true,
        pkg: this.putinBaseInfo.pkg,
        size: this.paginationInfo.size,
        page: this.paginationInfo.page,
      }).then((res) => {
        this.tableData = res.result.data.content;
        this.paginationInfo.total = res.result.data.total;
        this.loading = false;
      });
    },


    /* 克隆 */
    clonePutinTask(item) {
      this.clickeEitor(item);
      this.putinBaseInfo.taskName =
        `克隆_${this.putinBaseInfo.id}_` + this.putinBaseInfo.taskName;
      this.putinBaseInfo.id = "";
      this.orientation.id = "";
      this.makeCreative.id = "";
    },



    resetStatus(action, id) {
      resetPutinStatus({ action: action, id: id }).then((resp) => {
        if (resp.status === 200) {
          this.putinFetchPutinTasks();
          this.$message.success(`${action}状态重置成功`);
        }
      });
    },

    // 编辑
    clickeEitor: function (item) {
      console.log(123, JSON.stringify(item));
      this.drawer = true;
      this.putinBaseInfo = { ...item.putinBaseInfo };
      this.orientation = { ...item.orientation };
      this.makeCreative = { ...item.makeCreative };
      this.putinBaseInfo.advertCampaigns = [...item.advertCampaigns];
      if (this.putinBaseInfo.advertCampaigns == null) {
        this.putinBaseInfo.advertCampaigns = [];
      }

      // 获取人群包
      this.APIGetCreatedDirectPkg(this.putinBaseInfo.pkg);

      // 定向回传
      if (
        item.orientation.allowAge != null &&
        item.orientation.allowAge.length > 2
      ) {
        this.arrays.allowAge = item.orientation.allowAge.split(",");
      }

      if (
        item.orientation.allowNetwork != null &&
        item.orientation.allowNetwork.length > 0
      ) {
        this.arrays.allowNetwork = item.orientation.allowNetwork.split(",");
      }

      this.toData = [item.selectAdvs];
      this.putinBaseInfo.selectAdvertisers = [];
      this.targetList = [];
      this.gettoData(this.toData);

      //编辑时获取到应用对应的账户列表
      this.putinFetchAccount();

      // 广告组回显
      this.advGroupVisible(item.advertisers || []);

      // 双出价回显
      if (item.putinBaseInfo.deepCpabid * 1 > 0) {
        this.bid_type = "double";
      } else if (item.putinBaseInfo.openLadder == 1) {
        this.bid_type = "ladder";
      } else {
        this.bid_type = "only";
      }

      /* 通过拿到的toData 获取人群包数据 */
      this.crowdAdvertiserId = this.toData[0].children[0].id;
      this.APIGetCrowdList(this.crowdAdvertiserId);

      // 回显投放位置
      let pi = item.makeCreative.putinInventory;
      if (pi != null && pi.length > 0) {
        let pa = pi.split(",");
        this.makeCreative.putinInventory = pa;
      }
      //回显试完素材的选项
      if (item.makeCreative.openPlay && item.makeCreative.openPlay === "yes") {
        this.tryItOut = 1; //启用
        //获取试玩素材列表
        this.getAdvertiseCount();
      }

      // 推广卡片图片
      this.promotionCard = "";

      // 推广文案回显
      let texts = item.makeCreative.textGroup;
      this.putinTask.headlines = JSON.parse(texts);

      // 推广卖点回显
      let psp = item.makeCreative.productSellingPoints;
      this.arrays.productSellingPoints = JSON.parse(psp);

      // 创意分类回显
      let cts = item.makeCreative.creativeFullCategory;
      let tags = item.makeCreative.creativeTags;
      this.creativeCategoryDefault = this.backCreative(
        item.makeCreative.creativeCategoryGroup
      );

      let arr = tags.split(",");
      this.arrays.creativeTags = [...arr];

      this.crowdValue = "自定义人群";
      this.logicShow = true;

      /* 选择媒体时的回显 */
      this.change_putinInventory();

      /* appId 回显 */
      for (let i = 0; i < this.pkgList.length; i++) {
        if (this.pkgList[i].value == this.putinBaseInfo.pkg) {
          this.appId = this.pkgList[i].id + "";
          break;
        }
      }
    },

    // 广告组名称回显
    advGroupVisible(arrData) {
      if (arrData && arrData.length > 0) {
        this.activePutin = "selectHad";
        arrData.forEach((item) => {
          for (let i = 0; i < this.targetList.length; i++) {
            if (this.targetList[i].id - 0 == item.advertiserId - 0) {
              // 显示已选中的广告组id
              this.targetList[i].advName = item.campaignId;
              this.targetList[i].bidPrice = item.bidPrice;
            }
          }
        });
      } else {
        this.activePutin = "newPutin";
      }
    },

    // 回显多选创意分类
    backCreative(str) {
      let arr = str.split(",");
      let finalArr = [];
      let tempArr = [];
      arr.forEach((item) => {
        tempArr = [];
        tempArr.push(item.substring(0, 4));
        tempArr.push(item.substring(0, 6));
        tempArr.push(item);
        finalArr.push(tempArr);
      });
      return finalArr;
    },

    /* 分页 */
    // 当页面改变时触发
    handleCurrentChange(val) {
      this.paginationInfo.page = val;
      this.putinFetchPutinTasks();
    },
    // 当每页条数发生改变时触发
    handleSizeChange(val) {
      this.paginationInfo.size = val;
      this.putinFetchPutinTasks();
    },
    prevPageData() {
      this.paginationInfo.page--;
    },
    nextPageData() {
      this.paginationInfo.page++;
    },


    // 点击目标户，获取广告组下拉参数
    clickBtnGetData(item, index) {
      this.checkedAdvId = item.id;
      this.advGroupSelect = []; // 清空已选择的广告组列表
      // 获取广告主下的广告组列表
      getAdvList({ advertiserId: item.id }).then((res) => {
        this.advOptions = res.result.data;
      });

      this.indexAdv = index;
    },

    // 确认某个广告主是否被选中过
    handleAdvChecked(id) {
      let tempArr = this.putinBaseInfo.advertCampaigns;
      if (tempArr && tempArr.length > 0) {
        for (let i = 0; i < tempArr.length; i++) {
          if (tempArr[i].advertiserId == id) {
            return "true";
          }
        }
      } else {
        return "false";
      }
    },

    // 广告组下拉列表显示与隐藏
    visibleChangeTarget2(status) {
      if (!status) {
        // 隐藏下拉列表
        if (this.handleAdvChecked(this.checkedAdvId) == "true") {
          this.putinBaseInfo.advertCampaigns.forEach((item, index) => {
            if (this.checkedAdvId - 0 == item.advertiserId - 0) {
              this.putinBaseInfo.advertCampaigns[
                index
              ].campaignId = this.advGroupSelect.join(",");
            }
          });
        } else {
          if (this.advGroupSelect !== []) {
            this.putinBaseInfo.advertCampaigns.push({
              advertiserId: this.checkedAdvId + "",
              campaignId: this.advGroupSelect.join(","),
            });
          }
        }
        // 隐藏选择框
        this.indexAdv = null;
      }
    },

    // 处理显示选中广告组名称
    handleAdvName() {
      let tempArr = [];
      this.advGroupSelect.forEach((item) => {
        this.advOptions.forEach((innerItem) => {
          if (innerItem.id - 0 == item - 0) {
            tempArr.push(innerItem.label);
          }
        });
      });
      return tempArr;
    },

    // 选择框数据改变 给targetList 添加名称字段
    changeAdvSelect(curAccount) {
      // let advNameArr = await this.handleAdvName();
      let advNameArr = this.handleAdvName();
      for (let i = 0; i < this.targetList.length; i++) {
        if (this.targetList[i].id - 0 == curAccount.id - 0) {
          this.targetList[i].advName = advNameArr.join(",");
          return;
        }
      }
    },

    /* 启用试玩素材，同时获取列表 */
    onpenMetr(status) {
      if (status) {
        this.getAdvertiseCount();
      }
    },

    /* 获取试玩素材列表 */
    getAdvertiseCount() {
      let params = this.targetList
        .map(({ id }) => {
          return id;
        })
        .toString();
      getAdvertiseCount({ advertiserIds: params }).then((res) => {
        if (res.status == 200) {
          if (res.result.data.length == 0) {
            this.tryMaterialList = [];
          } else {
            this.tryMaterialList = res.result.data;
          }
        } else {
          this.$message.error(`错误：${res}`);
          console.error(res);
        }
      });
    },

    /* 获取转化行为列表 */
    getConversionAction() {
      let params = this.putinTask.putinAccounts.map(obj => (obj.advertiserId));
      fetchConversionAction(params).then((res) => {
        if (res.status == 200) {``
          if (res.result.data.length == 0) {
            this.putinTask.conversionActions = [];
          } else {
            this.putinTask.conversionActions = res.result.data;
          }
        } else {
          this.$message.error(`错误：${res}`);
          console.error(res);
        }
      });
    },


    test() {
      console.log(222, this.putinBaseInfo.deepBidType);
    },

    validateBudget(rule, value, callback) {
      alert(rule, value)
      if (value === '') {
        callback(new Error('必填'));
      } else if (isNaN(Number(value))) {
        callback(new Error('请输入有效数字'));
      } else {
        callback();
      }
    },
    formatBudget() {
      if (this.dailyBudget !== '' && !isNaN(Number(this.dailyBudget))) {
        this.dailyBudget = Number(this.dailyBudget).toFixed(2);
      }
    },
    handleChangeApp(item){
      this.putinFetchAccount()
      if(this.putinTask.taskName == ''){
        this.putinTask.taskName = `${item.label}-${moment().format("YYYY-MM-DD HH:mm:ss")}`
      }

      if(this.putinTask.campaignName == ''){
        this.putinTask.campaignName = `${item.label}-${moment().format("YYYY-MM-DD HH:mm:ss")}`
      }

      if(this.putinTask.adGroupName == ''){
        this.putinTask.adGroupName = `adGroup -${moment().format("YYYY-MM-DD HH:mm:ss")}`
      }

    },

    filterAccount(query, item){
      query = query.toLowerCase()
      return item.key.toString().toLowerCase().includes(query)||item.label.toString().toLowerCase().includes(query)
    },
    handleUploadChange(files){
      console.log("aabbccddeeff", files)
      this.putinTask.imageAssets = files
    },
    fetchVideoList() {
      this.videoListLoading = true;
      getYoutubeUploadDetaillist().then(res => {
        this.videoDataList = res.result.data;
        this.$nextTick(() => {
          console.log('视频列表已更新');
        })
          }).finally(() => {
        this.videoListLoading = false;
      });
    },
    toggleVideoSelection(video) {
      const index = this.selectedVideoId.indexOf(video.videoId);
      if (index > -1) {
        this.selectedVideoId.splice(index, 1); // 取消选中
      } else {
        this.selectedVideoId.push(video.videoId); // 选中
      }
    },
    openVideoDialog() {
      this.videoDialogVisible = true;
      if (this.videoDataList.length === 0) {
        this.fetchVideoList();
      }
    },
    confirmVideoSelection() {
      this.videoDialogVisible = false;
    },
    updateVideoUrlsString() {
      this.videoUrlsString = this.putinTask.videoUrls.join('\n');
    },
  },
};
</script>
