<style scoped lang="scss">
.slick-prev {
  z-index: 1000000;
}
.slick-next {
  z-index: 1000000;
}
.chouzhen {
  border-style: solid;
  border-width: 1px;
  border-color: #e4e4e4;
  width: calc(20% - 10px);
  padding: 10px;
  margin-right: 10px;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  background: #fff;
  position: relative;
  z-index: 99;
  float: left;
}

li.chouzhen.first:before {
  font-size: 12px;
  content: '首帧';
  position: absolute;
  top: 7px;
  left: 5px;
  width: 36px;
  height: 20px;
  color: rgb(255, 255, 255);
  line-height: 20px;
  text-align: center;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 2px;
  z-index: 1000;
}
.display-none-selset {
  display: none !important;
}
.logo {
  padding-left: 24px;
  img {
    height: 32px !important;
  }
  .name {
    font-size: 14px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #CED2D9;
    // line-height: 22px;
    margin-left: 20px;
    padding-left: 21px;
    position: relative;
  }
  .name::before {
    content: '';
    width: 1px;
    height: 18px;
    background: rgba(255, 255, 255, 0.31);
    position: absolute;
    left: 0;
    top: 50%;
    margin-top: -9px;
  }
}
.chartBox {
  margin-top: 80px;
  .chartBody {
    display: flex;
    justify-content: space-around;
    flex-wrap: wrap;
  }
  .search-box {
    margin-bottom: 20px;
  }
}
</style>
<style lang="scss">
.hide-checkbox .ant-table-thead .ant-table-selection {
  display: none;
}
.look-preview .ant-card-head-title {
  font-weight: 700;
}
// .look-preview textarea {
//   resize: none;
//   border: none;
//   outline: 0;
//   box-shadow: none;
// }
.create-info .ant-form-item {
  margin-bottom: 0 !important;
}
.fengmian .ant-checkbox-wrapper:first-child {
  margin-left: 8px;
}
@media screen and (max-width: 1200px) {
  // 这里写对应要修改的样式如：
  .look-preview .el-step__title {
    font-size: 12px;
  }
}
.line-height-one .ant-form-item-control {
  line-height: inherit;
}
.creat-all-info .ant-form-item-control {
  width: 60%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.display-none-selset {
  display: none !important;
}
</style>
<template>
  <div ref="questionnaireBox" class="look-preview">
    <a-layout-header
      class="ant-header-fixedHeader ant-header-side-opened"
      :style="{ padding: '0' }"
      style="background: #0b2040 !important; position: fixed; top: 0; z-index: 100; width: 100%"
    >
      <div :class="['top-nav-header-index', theme]">
        <div class="header-index-wide">
          <div class="header-index-left" :style="topMenuStyle.headerIndexLeft">
            <div class="logo">
              <img src="~@/assets/logoNew1.png" alt="logo" />
              <span class="name">有腾投放管家</span>
            </div>
          </div>
        </div>
      </div>
    </a-layout-header>
    <div style="width: 100%; padding: 0 20px" class="chartBox">
      <a-card>
        <div slot="title">
          <a-button style="margin: 0 15px 0 0" @click="backNewBatch" :disabled="newBatch"> 返回 </a-button>
          预览区
        </div>
        <div slot="extra">
          预估生成<span style="color: #409EFF">{{ groupCount }}</span
          >个广告组
          <a-button type="primary" style="margin: 0 15px" @click="createAll" :disabled="groupCount == 0">
            全部提交审核
          </a-button>
        </div>
        <div v-if="campaignList">
          <h2 style="display: flex; justify-content: space-between">
            <span>账户id:{{ accountId }}</span
            ><span style="font-size: 14px; font-weight: 500"
              >广告计划数量：{{ campaignList.length }}&nbsp;&nbsp;&nbsp;&nbsp;广告组数量：{{ groupCount }}</span
            >
            <div>
              <a-dropdown>
                <a-menu slot="overlay" @click="handleMenuClick">
                  <a-menu-item key="1" :disabled="groupCheck.length == 0">批量修改预算与出价 </a-menu-item>
                  <a-menu-item key="2" :disabled="groupCheck.length == 0"> 批量修改监测链接 </a-menu-item>
                </a-menu>
                <a-button style="margin: 0 15px"> 批量修改 <a-icon type="down" /> </a-button>
              </a-dropdown>
              <a-popconfirm :title="`确定要删除这 ${groupCheck.length} 项吗?`" @confirm="handleConfirmDelete">
                <a-button style="margin: 0 15px" :disabled="groupCheck.length == 0"> 批量删除广告组 </a-button>
              </a-popconfirm>

              <a-button type="primary" style="margin: 0 15px" :disabled="groupCheck.length == 0" @click="createArr">
                提交审核
              </a-button>
            </div>
          </h2>
          <!-- <div v-for="(item, index) in campaignList" :key="index"></div> -->
          <el-collapse v-model="activeName" accordion>
            <el-collapse-item v-for="(item, index) in campaignList" :key="index" :name="item.id">
              <template slot="title">
                <h3 style="display: flex; justify-content: space-between; width: 80%">
                  <span style="width: 50%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap"
                    >广告计划：{{ item.campaignName }}</span
                  >
                  <span style="width: 20%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap"
                    >营销目标：{{ item.campaignType == 2 ? '提升应用安装' : item.campaignType == 5?'收集销售线索' :'提高应用活跃'}}</span
                  >
                  <span style="width: 10%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap"
                    >预算：{{ item.dayBudget ? item.dayBudget / 1000 + '元' : '不限' }}</span
                  >
                  <!-- <a-checkbox style="width: 10%" v-model="item.checkAll" @click.stop="setAll(item)"> 全选 </a-checkbox> -->
                </h3>
              </template>
              <a-table
                :columns="columns"
                :data-source="item.kuaishouBatchGroupPreviews"
                class="components-table-demo-nested"
                :pagination="false"
                :scroll="{ x: 2100 }"
                bordered
                tableLayout="fixed"
                :row-selection="{ selectedRowKeys: groupCheck, onChange: onSelectChange }"
                rowKey="id"
              >
                <span slot="unitName" slot-scope="text, records">
                  <p style="text-align: left">
                    {{ text }}
                  </p>
                  <a-icon
                    type="edit"
                    style="float: left; color: #409EFF; margin-top: 5px"
                    class="count"
                    @click.stop="editUnitName(records)"
                  />
                </span>
                <span slot="bidType" slot-scope="text, records">
                  {{ text | bidType }}
                </span>
                <span slot="sceneId" slot-scope="text, records">
                  <p v-for="(item, index) in JSON.parse(text)" :key="index" style="text-align: left">
                    {{ item | kuaishouSceneId }}{{ index == JSON.parse(text).length - 1 ? '' : ',' }}
                  </p>
                </span>
                <span slot="materialArr" slot-scope="text, records">
                  <p style="color: #409EFF; cursor: pointer" @click="lookVideo(text)">
                    已选{{ text ? text.length : 0 }}个素材
                  </p>
                </span>
                <span slot="dayBudget" slot-scope="text, records">
                  <p style="text-align: left">
                    预算：{{ records.dayBudget || records.dayBudget > 0 ? records.dayBudget / 1000 + '元' : '不限' }}
                  </p>
                  <p style="text-align: left">
                    出价：{{ records.bid ? records.bid / 1000 : records.cpaBid ? records.cpaBid / 1000 : '' }}元
                  </p>
                  <p style="text-align: left" v-if="records.deepConversionType">
                    深度转化出价：{{ records.deepConversionBid ? records.deepConversionBid / 1000 : '无' }}
                  </p>
                  <a-icon
                    type="edit"
                    style="float: left; color: #409EFF"
                    class="count"
                    @click.stop="editBid(records, records.bidType==2 ? 'bid' : 'cpaBid')"
                  />
                </span>
                <span slot="appId" slot-scope="text, records">
                  <div style="width: 100%" v-if="text">
                    <p style="text-align: left">
                      {{ setAppName(text) }}
                    </p>
                    <a-icon
                      type="edit"
                      style="float: left; color: #409EFF; margin-top: 5px"
                      class="count"
                      @click="editAppAndSite(records)"
                    />
                  </div>
                  <p style="text-align: left">
                    {{ records.url }}
                  </p>
                </span>
                <span slot="action" slot-scope="text, record">
                  <a-popconfirm :title="`确定要删除这项吗?`" @confirm="removeGroup(record.id)">
                    <a>删除</a>
                    <span class="gap"></span>
                  </a-popconfirm>

                  <!-- <a-divider type="vertical" />
                  <a>Delete</a> -->
                </span>
                <span slot="descriptionArr" slot-scope="text, records">
                  <p
                    v-for="(item, index) in new Set(text)"
                    :key="index"
                    style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: left"
                    :title="item"
                  >
                    {{ item }}
                  </p>
                </span>

                <span slot="clickTrackUrl" slot-scope="text, records">
                  <p style="text-align: left">{{ text }}</p>

                  <a-icon
                    type="edit"
                    style="float: left; color: #409EFF"
                    class="count"
                    @click.stop="editClickTrackUrl(records)"
                  />
                </span>
                <span slot="isSuccess" slot-scope="text, records">{{ text == 0 ? '待提交' : '提交成功' }}</span>
                <span slot="siteId" slot-scope="text, records">
                  {{ text ? text : '无' }}
                </span>
              </a-table>
            </el-collapse-item>
          </el-collapse>
        </div>
      </a-card>
      <a-modal
        title="修改广告组名称"
        v-model="unitNameEditVisible"
        :width="500"
        @ok="okUnitName"
        @cancel="unitNameEditVisible = false"
        :destroyOnClose="true"
      >
        <!-- <a-form-model
          ref="materialForm"
          :hideRequiredMark="true"
        >
          <a-row :gutter="16"> -->
        <div style="display: flex; width: 100%">
          <span>广告组名称:</span>
          <a-input
            v-model="unitName"
            style="width: 70%; margin-left: 10px; position: relative; top: -4px"
            placeholder="请输入广告组名称"
          />
        </div>

        <!-- </a-row>
        </a-form-model> -->
      </a-modal>
      <a-modal
        title="修改出价预算"
        v-model="bidEditVisible"
        :width="500"
        @ok="okUnitBid"
        @cancel="bidEditVisible = false"
        :destroyOnClose="true"
      >
        <a-form :form="ruleConfigForm" layout="horizontal" hide-required-mark v-bind="formItemLayout">
          <a-form-item label="预算">
            <a-input-number
              v-decorator="['dayBudget']"
              style="width: 100%"
              :min="500"
              :precision="0"
              :max="100000000"
              placeholder="不小于500,不超过100000000,仅支持输入自然数"
            />
          </a-form-item>
          <a-form-item label="出价">
            <a-input-number
              v-decorator="['bid']"
              style="width: 100%"
              :max="getData('dayBudget', 'ruleConfigForm') ? getData('dayBudget', 'ruleConfigForm') : 3000"
              :min="0"
              :precision="2"
            />
          </a-form-item>
          <a-form-item label="深度转化出价" v-if="deepConversionType">
            <a-input-number v-decorator="['deepConversionBid']" style="width: 100%" />
          </a-form-item>
        </a-form>
      </a-modal>

      <a-modal
        title="修改应用"
        v-model="appIdEditVisible"
        :width="700"
        @ok="okAppId"
        @cancel="appIdEditVisible = false"
        :destroyOnClose="true"
      >
        <a-form :form="appIdConfigForm" layout="horizontal" hide-required-mark v-bind="formItemLayout">
          <a-form-item label="应用">
            <a-select v-decorator="['appId']" style="width: 100%" allowClear @change="setSiteId">
              <a-select-option v-for="appModel in appListArr" :key="appModel.appId" :value="appModel.appId">
                {{ appModel.appName }}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{ appModel.appVersion }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="应用下载详情页">
            <a-select
              v-decorator="['siteId']"
              style="width: 100%"
              allowClear
              :disabled="
                getData('appId', 'appIdConfigForm') == undefined ||
                getData('appId', 'appIdConfigForm') == null ||
                getData('appId', 'appIdConfigForm') == ''
              "
            >
              <a-select-option v-for="appModel in siteList" :key="appModel.siteId" :value="appModel.siteId">
                {{ appModel.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
      </a-modal>

      <a-modal
        title="修改监测链接"
        v-model="clickTrackUrlEditVisible"
        :width="700"
        @ok="okClickTrackUrl"
        @cancel="clickTrackUrlEditVisible = false"
        :destroyOnClose="true"
      >
        <h4 style="text-align: center">不填则保持原样</h4>
        <a-form :form="clickTrackUrlConfigForm" layout="horizontal" hide-required-mark v-bind="formItemLayout">
          <a-form-item label="监测链接">
            <a-input v-decorator="['clickTrackUrl']" placeholder="请输入监测链接" />
          </a-form-item>
          <a-form-item label="点击监测链接">
            <a-input v-decorator="['actionbarClickUrl']" placeholder="请输入点击监测链接" />
          </a-form-item>
        </a-form>
      </a-modal>

      <a-modal title="素材预览" v-model="coverPreviewVisible" :width="1000" :footer="null">
        <a-carousel arrows class="cover_carousel_con" v-if="videoData.length > 0" @next="next" @prev="prev">
          <div v-for="(item, index) in videoData" :key="index" class="content">
            <div style="display: flex !important; justify-content: space-around">
              <div style="display: flex; flex-direction: column; align-items: center" v-if="!!item.videoUrl.url">
                <!-- <video :src="item.videoUrl.coverUrl" :width="300" /> -->
                <video class="video" :src="item.videoUrl.url" controls="controls" style="width: 300px">
                  您的浏览器不支持 video 标签。
                </video>
                <span style="font-size: 20px; margin-top: 15px">视频素材</span>
              </div>
              <div style="display: flex; flex-direction: column; align-items: center">
                <img :src="item.imageUrl" v-if="item.imageUrl" :width="300" />
                <img :src="item.videoUrl.coverUrl" v-else :width="300" />
                <span style="font-size: 20px; margin-top: 15px">封面素材</span>
              </div>
            </div>
          </div>
          <a-icon
            type="left-circle"
            slot="prevArrow"
            slot-scope
            style="left: 10px; zindex: 9; font-size: 30px; color: black"
          />
          <a-icon
            type="right-circle"
            slot="nextArrow"
            slot-scope
            style="right: 10px; zindex: 9; font-size: 30px; color: black"
          />
        </a-carousel>
      </a-modal>
    </div>
  </div>
</template>

<script>
//   import UserMenu from '../tools/UserMenu'
//   import SMenu from '../menu/'
import Logo from '@/components/tools/Logo.vue'
import pick from 'lodash.pick'
import { mixin } from '@/utils/mixin.js'
import Treeselect from '@/views/modules/Statistics/components/Treeselect.vue'
import moment from 'moment'
import selectCheckAll from '@/components/formComponents/toutiaoTime'
import checkBoxGroup from '@/components/formComponents/checkBoxGroup'
import { stopOtherVideo, closeAllVideoFun } from '@/utils/videoControl' // 停止除当前外的其他视频播放，及停止所有视频播放的方法
function tqFun(qcArr1) {
  var tempArr = []
  function bbFun(qcArr) {
    for (var i = 0; i < qcArr.length; i++) {
      if (qcArr[i] instanceof Array) {
        bbFun(qcArr[i])
      } else {
        tempArr.push(qcArr[i])
      }
    }
    return tempArr
  }
  return bbFun(qcArr1)
}

export default {
  name: 'GlobalHeader',
  components: {
    //   UserMenu,
    //   SMenu,
    Logo,
    Treeselect,
    selectCheckAll,
    checkBoxGroup,
  },
  mixins: [mixin],
  props: {
    mode: {
      type: String,
      // sidemenu, topmenu
      default: 'sidemenu',
    },
    theme: {
      type: String,
      required: false,
      default: 'dark',
    },
    collapsed: {
      type: Boolean,
      required: false,
      default: false,
    },
    device: {
      type: String,
      required: false,
      default: 'desktop',
    },
  },
  data() {
    return {
      newBatch: false,
      videoData: [],
      coverPreviewVisible: false,
      clickTrackUrlEditVisible: false,

      appIdEditVisible: false,
      ruleConfigForm: this.$form.createForm(this),
      appIdConfigForm: this.$form.createForm(this),
      clickTrackUrlConfigForm: this.$form.createForm(this),
      formItemLayout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 19 },
      },
      unitNameEditVisible: false, //广告组模态框
      bidEditVisible: false,

      topMenuStyle: {
        headerIndexLeft: {},
        topNavHeader: {},
        headerIndexRight: {},
        topSmenuStyle: {},
      },
      accountId: '',
      batchId: null,
      campaignList: null,
      activeName: null,
      columns: [
        {
          title: '广告组名称',
          dataIndex: 'unitName',
          key: 'unitName',
          width: 200,
          align: 'center',
          scopedSlots: { customRender: 'unitName' },
          fixed: 'left',
        },
        {
          title: '优化目标',
          dataIndex: 'bidType',
          key: 'bidType',
          width: 100,
          align: 'center',
          scopedSlots: { customRender: 'bidType' },
        },
        {
          title: '预算与出价',
          dataIndex: 'dayBudget',
          key: 'dayBudget',
          scopedSlots: { customRender: 'dayBudget' },
          width: 150,
          align: 'center',
        },
        {
          title: '广告位',
          dataIndex: 'sceneId',
          key: 'sceneId',
          width: 140,
          scopedSlots: { customRender: 'sceneId' },
          align: 'center',
        },
        {
          title: '快手应用/落地页',
          dataIndex: 'appId',
          key: 'appId',
          width: 150,
          scopedSlots: { customRender: 'appId' },
          align: 'center',
        },
        {
          title: '定向包',
          dataIndex: 'templateName',
          key: 'templateName',
          width: 150,
          align: 'center',
          scopedSlots: { customRender: 'templateName' },
        },
        {
          title: '广告语',
          dataIndex: 'descriptionArr',
          key: 'descriptionArr',
          width: 350,
          align: 'center',
          scopedSlots: { customRender: 'descriptionArr' },
          ellipsis: true,
        },
        {
          title: '创意素材',
          dataIndex: 'materialArr',
          key: 'materialArr',
          width: 150,
          align: 'center',
          scopedSlots: { customRender: 'materialArr' },
        },
        {
          title: '监测链接',
          dataIndex: 'clickTrackUrl',
          key: 'clickTrackUrl',
          width: 350,
          align: 'center',
          scopedSlots: { customRender: 'clickTrackUrl' },
        },
        {
          title: '应用下载详情页',
          dataIndex: 'siteId',
          key: 'siteId',
          width: 150,
          align: 'center',
          scopedSlots: { customRender: 'siteId' },
        },
        {
          title: '状态',
          dataIndex: 'isSuccess',
          key: 'isSuccess',
          width: 100,
          fixed: 'right',
          align: 'center',
          scopedSlots: { customRender: 'isSuccess' },
        },
        {
          title: '操作',
          dataIndex: 'action',
          key: 'action',
          width: 100,
          fixed: 'right',
          align: 'center',
          scopedSlots: { customRender: 'action' },
        },
      ],
      appListArr: [],
      groupCheck: [],
      groupCheckRow: [],
      unitId: '',
      unitName: '',
      bidType: 'cpaBid',
      bid: null,
      dayBudget: null,
      deepConversionBid: null,
      deepConversionType: false,
      siteList: [],
      allData: null,
      editAll: false,

      groupIds: [],
      campaignIds: [],
    }
  },
  computed: {
    groupCount() {
      var count = 0
      if (this.campaignList) {
        for (let i = 0; i < this.campaignList.length; i++) {
          count += this.campaignList[i].kuaishouBatchGroupPreviews.length
        }
      }
      return count
    },
  },
  watch: {},
  mounted() {
    this.accountId = this.$route.query.accountId
    this.batchId = this.$route.query.batchId
    this.getPreviewList()
    // this.$nextTick(() => {
    let params = {}
    params.accountId = this.accountId
    this.getAction('/kuaishou/batch/getAppList', params).then((res) => {
      if (res.success) {
        this.appListArr = res.result.map((item, index) => {
          return {
            ...item,
            key: item.appId + '',
            title: item.appName,
            siteId: null,
            siteList: [],
          }
        })
      }
    })
    // })
  },
  methods: {
    next() {
      closeAllVideoFun()
    },
    prev() {
      closeAllVideoFun()
    },
    createArr() {
      this.newBatch = true
      var params = {}
      params.accountId = this.accountId
      params.dataList = {
        campaigns: this.groupCheckRow.map((item) => {
          return item.planId
        }),
        groups: this.groupCheck,
      }
      this.postDataAction('/kuaishouBatch/creativePreview/createAdcampaignAndGroups', params).then((res) => {
        if (res.success) {
          this.getAction('/kuaishouBatch/groupPreview/deleteBatch', {
            ids: this.groupCheck.join(),
          }).then((res) => {
            if (res.success) {
              this.groupCheck = []
              this.getPreviewList()
              setTimeout(() => {
                var dataConunt = this.campaignList.filter((a) => {
                  return a.kuaishouBatchGroupPreviews.length > 0
                })
                if (dataConunt.length > 0) {
                } else {
                  localStorage.removeItem('lookPreview')
                  window.close()
                }
              })
            }
          })
        }
      })
    },
    setAll(item) {
      //  groupIds:[],
      // campaignIds:[]
      setTimeout(() => {
        if (item.checkAll) {
          this.groupCheck.push(
            ...item.kuaishouBatchGroupPreviews.map((i) => {
              return i.id
            })
          )
          this.groupCheckRow = JSON.parse(JSON.stringify(item.kuaishouBatchGroupPreviews))
        } else {
          for (let i = 0; i < item.kuaishouBatchGroupPreviews.length; i++) {
            var index = this.groupCheck.findIndex((c) => c == item.kuaishouBatchGroupPreviews[i].id)
            var indexTwo = this.groupCheckRow.findIndex((c) => c.id == item.kuaishouBatchGroupPreviews[i].id)
            if (index > -1) {
              this.groupCheck.splice(index, 1)
            }
            if (indexTwo > -1) {
              this.groupCheckRow.splice(indexTwo, 1)
            }
          }
        }
      })
    },
    handleConfirmDelete() {
      this.getAction('/kuaishouBatch/groupPreview/deleteBatch', {
        ids: this.groupCheck.join(),
      }).then((res) => {
        if (res.success) {
          this.groupCheck = []
          this.$message.success('删除成功')
          this.getPreviewList()
        }
      })
    },
    handleMenuClick(e) {
      if (e.key == '1') {
        this.bidEditVisible = true
        this.bidType = this.campaignList[0].kuaishouBatchGroupPreviews[0].bidType==2?'bid':'cpaBid'
      } else {
        this.clickTrackUrlEditVisible = true
      }

      this.editAll = true
    },
    setSiteId(e) {
      this.appIdConfigForm.setFieldsValue({ siteId: undefined })
      this.getSiteList(e)
    },
    getData(className, formName) {
      return this[formName].getFieldValue(className)
    },
    getSiteList(item) {
      this.getAction('/kuaishou/batch/getPageList', {
        accountId: this.accountId,
        appId: item,
        viewComp: 7,
      }).then((res) => {
        if (res.success) {
          console.log(item)
          this.siteList = res.result
        } else {
        }
      })
    },
    //rules
    handleConfirmValue(rule, value, callback) {
      if (value == 0) {
        callback()
      } else if (value == '' || (value > 0 && value < 500) || value >= 100000000) {
        callback('不小于500， 不超过100000000，仅支持输入自然数')
      }
      callback()
    },

    getPreviewList() {
      this.getAction('/kuaishouBatch/campaignPreview/queryByBatchId', {
        accountId: this.accountId,
        batchId: this.batchId,
      }).then((res) => {
        if (res.success) {
          this.campaignList = res.result.campaignList.map((item) => {
            return {
              ...item,
              checkAll: false,
            }
          })

          // this.activeName = this.campaignList[0].id
        } else {
          this.$message.error('网络开小差了，请刷新后重试')
        }
      })
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.groupCheck = selectedRowKeys
      this.groupCheckRow = selectionRows
      console.log(this.groupCheck, this.groupCheckRow)
    },
    setAppName(appId) {
      // this.$nextTick(() => {
      var data = this.appListArr.filter((item) => {
        return item.appId == appId
      })
      if (data.length > 0) {
        return data[0].appName
      }
      // })
    },
    setSiteName(appId, siteId) {
      var data = []

      this.getAction('/kuaishou/batch/getPageList', {
        accountId: this.accountId,
        appId: appId,
        viewComp: 7,
      }).then((res) => {
        if (res.success) {
          data = res.result.filter((item) => {
            return item.siteId == siteId + ''
          })
        } else {
        }
      })
    },
    editUnitName(item) {
      this.unitNameEditVisible = true
      this.unitName = item.unitName
      this.unitId = item.id
    },
    okUnitName() {
      this.postDataAction('/kuaishouBatch/groupPreview/edit', { id: this.unitId, unitName: this.unitName }).then(
        (res) => {
          if (res.success) {
            this.getPreviewList()
            this.unitNameEditVisible = false
          }
        }
      )
    },
    editBid(item, type) {
      console.log(type)
      this.editAll = false
      this.unitId = item.id
      this.bidEditVisible = true
      this.bidType = type
      this.bid = item[type] / 1000
      this.dayBudget = item.dayBudget / 1000
      this.deepConversionBid = item.deepConversionBid ? item.deepConversionBid / 1000 : null
      this.deepConversionType = item.deepConversionType ? true : false
    },
    okUnitBid() {
      this.ruleConfigForm.validateFields((err, values) => {
        if (!err) {
          var params = {}
          if (this.bidType == 'cpaBid') {
            params.cpaBid = values.bid == undefined ? null : values.bid * 1000
          } else {
            params.bid = values.bid == undefined ? null : values.bid * 1000
          }
          params.dayBudget = values.dayBudget == undefined ? null : values.dayBudget * 1000
          params.deepConversionBid = values.deepConversionBid == undefined ? null : values.deepConversionBid * 1000
          if (!this.editAll) {
            params.id = this.unitId

            this.postDataAction('/kuaishouBatch/groupPreview/edit', params).then((res) => {
              if (res.success) {
                this.getPreviewList()
                this.bidEditVisible = false
              }
            })
          } else if (this.editAll) {
            params.groupIds = this.groupCheck
            this.postDataAction('/kuaishouBatch/groupPreview/batchEdit', params).then((res) => {
              if (res.success) {
                this.groupCheck = []
                this.getPreviewList()
                this.bidEditVisible = false
              }
            })
          }
        }
      })
    },
    editAppAndSite(item) {
      // /\{{([^}]+)\}}/g;
      this.unitId = item.id
      this.appIdEditVisible = true
      this.allData = item
      this.$nextTick(() => {
        this.appIdConfigForm.setFieldsValue({ appId: item.appId, siteId: item.siteId ? item.siteId + '' : undefined })
        this.getSiteList(item.appId)
      })

      // var pattern = /\{{应用名称}}/g
      // console.log(item.unitNameFormat.replace(pattern, '*'))
    },
    okAppId() {
      this.appIdConfigForm.validateFields((err, values) => {
        if (!err) {
          var appPattern = /\{{应用名称}}/g
          var templatePattern = /\{{定向包}}/g
          var timePattern = /\{{日期}}/g
          var versionPattern = /\{{渠道号}}/g
          var typePattern = /\{{创意制作方式}}/g
          var positionPattern = /\{{广告位置}}/g

          var data = []
          if (values.appId != undefined) {
            data = this.appListArr.filter((item) => {
              return item.appId == values.appId
            })
          } else {
            data = this.appListArr.filter((item) => {
              return item.appId == this.allData.appId
            })
          }
          var params = {}
          params.appId = values.appId == undefined ? null : values.appId
          params.siteId = values.siteId == undefined ? null : values.siteId
          // params.unitName = this.allData.unitNameFormat.replace(pattern, '*')
          if (appPattern.test(this.allData.unitNameFormat)) {
            this.allData.unitNameFormat = this.allData.unitNameFormat.replace(appPattern, data[0].appName)
          }
          if (templatePattern.test(this.allData.unitNameFormat)) {
            this.allData.unitNameFormat = this.allData.unitNameFormat.replace(
              templatePattern,
              this.allData.templateName
            )
          }
          if (timePattern.test(this.allData.unitNameFormat)) {
            this.allData.unitNameFormat = this.allData.unitNameFormat.replace(timePattern, this.allData.beginTime)
          }
          if (versionPattern.test(this.allData.unitNameFormat)) {
            this.allData.unitNameFormat = this.allData.unitNameFormat.replace(versionPattern, data[0].appVersion)
          }
          if (typePattern.test(this.allData.unitNameFormat)) {
            this.allData.unitNameFormat = this.allData.unitNameFormat.replace(typePattern, '自定义')
          }
          if (positionPattern.test(this.allData.unitNameFormat)) {
            this.allData.unitNameFormat = this.allData.unitNameFormat.replace(
              positionPattern,
              JSON.parse(this.allData.sceneId)[0] == 1
                ? '优选'
                : JSON.parse(this.allData.sceneId)[0] == 5
                ? '联盟'
                : '按场景'
            )
          }
          params.unitName = this.allData.unitNameFormat
          params.id = this.unitId

          this.postDataAction('/kuaishouBatch/groupPreview/edit', params).then((res) => {
            if (res.success) {
              this.getPreviewList()
              this.appIdEditVisible = false
            }
          })
        }
      })
    },
    editClickTrackUrl(item) {
      this.editAll = false
      this.clickTrackUrlEditVisible = true
      this.unitId = item.id
    },
    okClickTrackUrl() {
      this.clickTrackUrlConfigForm.validateFields((err, values) => {
        var params = {}
        params.clickTrackUrl =
          values.clickTrackUrl == null || values.clickTrackUrl == undefined ? null : values.clickTrackUrl
        params.actionbarClickUrl =
          values.actionbarClickUrl == null || values.actionbarClickUrl == undefined ? null : values.actionbarClickUrl

        if (!this.editAll) {
          params.id = this.unitId
          this.postDataAction('/kuaishouBatch/groupPreview/edit', params).then((res) => {
            if (res.success) {
              this.getPreviewList()
              this.clickTrackUrlEditVisible = false
            }
          })
        } else if (this.editAll) {
          params.groupIds = this.groupCheck
          this.postDataAction('/kuaishouBatch/groupPreview/batchEdit', params).then((res) => {
            if (res.success) {
              this.groupCheck = []
              this.getPreviewList()
              this.clickTrackUrlEditVisible = false
            }
          })
        }
      })
    },
    lookVideo(item) {
      if(!!item[0].photoId){
        this.videoData = []
        for (let i = 0; i < item.length; i++) {
          this.setVideUrl(item[i].photoId).then((res) => {
            item[i].videoUrl = res
            this.videoData.push(item[i])
            if (this.videoData.length == item.length) {
              this.coverPreviewVisible = true
            }
          })
        }
      }else if(!!item[0].imageTokens){
        var num = 1
        for (let i = 0; i < item.length; i++) {
          this.setImageUrl(item[i].imageTokens).then((res) => {
            item[i].videoUrl = ''
            this.videoData.push(...res)
            num++
            if (this.videoData.length == item.length*6) {
              this.coverPreviewVisible = true
            }
          })
        }
      }else if(!!item[0].photoIds){
        this.videoData = []
        for (let i = 0; i < item.length; i++) {
         
            this.setManyVideoUrl(item[i].photoIds).then((res) => {
              // item[i].videoUrl = res
              this.videoData.push(...res)
              if (this.videoData.length == item.length*4) {
                this.coverPreviewVisible = true
              }
            })
        }
      }
      
    },
    setManyVideoUrl(photoId){
      
      return new Promise((resolve, reject) => {
        this.postDataAction('/batch/kuaiShouGroupTemplate/getUrlByPhotoIds', { photoIds: JSON.parse(photoId),accountId: this.accountId}).then((res) => {
          if (res.success) {
            resolve(res.result.map(item=>{
              return {
                imageUrl:item.coverUrl,
                videoUrl:{
                  url:item.url
                }
              }
            }))
          }
        })
      })
    },
    setImageUrl(photoId){
      return new Promise((resolve, reject) => {
        this.postDataAction('/batch/kuaiShouGroupTemplate/queryUrlByImageTokens', { imageTokens: photoId,accountId: this.accountId}).then((res) => {
          if (res.success) {
            resolve(res.result.map(item=>{
              return {
                imageUrl:item.url,
                videoUrl:{
                  url:''
                }
              }
            }))
          }
        })
      })
    },
    setVideUrl(photoId) {
      this.videoList = []
      return new Promise((resolve, reject) => {
        this.getAction('/batch/kuaiShouGroupTemplate/getUrlByPhotoId', { photoId: photoId }).then((res) => {
          if (res.success) {
            resolve({ ...res.result, photoId: photoId })
          }
        })
      })
      // this.getAction('/batch/kuaiShouGroupTemplate/getUrlByPhotoId', { photoId: photoId }).then((res) => {
      //   if (res.success) {
      //     this.videoList.push({ url: res.result.url, photoId: photoId, coverUrl: res.result.coverUrl })
      //     return res.result.url
      //   } else {
      //   }
      // })
    },
    removeGroup(id) {
      this.getAction('/kuaishouBatch/groupPreview/delete', { id: id }).then((res) => {
        if (res.success) {
          this.$message.success('删除成功')
          this.getPreviewList()
        }
      })
    },
    popstateFun() {
      //监听浏览器回退的回调
      window.history.pushState(null, null, document.URL) //想浏览器跳转记录中添加一条空记录
    },
    backNewBatch() {
      var that = this
      this.$confirm({
        title: '返回不会保存你修改的信息，是否确定？',

        onOk() {
          window.open('/user/new-batch?accountId=' + that.accountId + '&batchId=' + that.batchId, '_self')
          // window.close()
        },
        onCancel() {
          console.log('Cancel')
        },
        class: 'test',
      })
    },
    createAll() {
      this.newBatch = true
      var groupIds = []
      for (let i = 0; i < this.campaignList.length; i++) {
        for (let j = 0; j < this.campaignList[i].kuaishouBatchGroupPreviews.length; j++) {
          groupIds.push(this.campaignList[i].kuaishouBatchGroupPreviews[j].id)
        }
      }
      var params = {}
      params.accountId = this.accountId
      params.dataList = {
        campaigns: this.campaignList.map((item) => {
          return item.id
        }),
        groups: groupIds,
      }
      console.log(params)
      this.postDataAction('/kuaishouBatch/creativePreview/createAdcampaignAndGroups', params).then((res) => {
        this.$success({
          title: '全部提交成功',
          // JSX support
          onOk: function () {
            localStorage.removeItem('lookPreview')
            window.close()
          },
        })
      })
    },
  },
}
</script>

<style lang="scss" scoped>
</style>