<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 {
    .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">
        <div style="width: 100%;" class="chartBox">
            <a-spin :spinning="spinning">
                <a-card>
                    <div slot="title">
                        预览区
                    </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 && campaignList[0].campaignInfo">
                        <!-- <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">
                                    <h2 style="display: flex; justify-content: space-between;width: 100%">
                                        <span>账户id:{{ item.accountId }}</span
                                        ><span style="font-size: 14px; font-weight: 500"
                                            >广告计划数量：{{
                                                item.campaignCount
                                            }}&nbsp;&nbsp;&nbsp;&nbsp;广告组数量：{{ item.unitCount }}</span
                                        >
                                        <div>
                                            <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>
                                </template>
                                <div v-for="(items, indexUnit) in item.campaignInfo" :key="indexUnit">
                                    <h3 style="display: flex; justify-content: space-between; width: 113%">
                                        <span
                                            style="flex:1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap"
                                            >广告计划：{{ items.campaignName }}</span
                                        >
                                        <span
                                            style="flex:1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap"
                                            >营销目标：{{
                                                items.campaignType == 2 ? '提升应用安装' : '收集销售线索'
                                            }}</span
                                        >
                                        <span
                                            style="flex:1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap"
                                            >预算：{{ items.dayBudget ? items.dayBudget / 1000 + '元' : '不限' }}</span
                                        >
                                        <!-- <a-checkbox style="width: 10%" v-model="item.checkAll" @click.stop="setAll(item)"> 全选 </a-checkbox> -->
                                    </h3>
                                    <!-- :scroll="{ x: 2100 }" -->
                                    <a-table
                                        :columns="columns"
                                        :data-source="items.unitDetail"
                                        class="components-table-demo-nested"
                                        :pagination="false"
                                        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>
                                        </span>
                                        <div slot="target" slot-scope="text, records" style="    line-height: 30px;">
                                            <a-row :gutter="20">
                                                <a-col :sm="12" style="text-align:left">
                                                    <span>地域：</span>
                                                    <span>{{ records.regionGroupName }}</span>
                                                </a-col>
                                                <a-col :sm="12" style="text-align:left"
                                                    ><span>年龄：</span>
                                                    <!-- JSON.parse(records.agesRange)[0] | ageShow -->
                                                    <span v-if="records.ageGroupName">{{ records.ageGroupName }}</span>
                                                    <span v-else>不限</span>
                                                </a-col>
                                            </a-row>
                                            <a-row :gutter="20">
                                                <a-col :sm="12" style="text-align:left">
                                                    <span>性别：</span>
                                                    <span>{{
                                                        records.gender ? (records.gender == 1 ? '女' : '男') : '不限'
                                                    }}</span>
                                                </a-col>
                                                <a-col :sm="12" style="text-align:left"
                                                    ><span>行为意向：</span>
                                                    <span>{{
                                                        records.intentionTarget ? '系统优选' : '不限'
                                                    }}</span></a-col
                                                >
                                            </a-row>
                                            <a-row :gutter="20">
                                                <a-col :sm="12" style="text-align:left">
                                                    <span>APP行为：</span>
                                                    <span>{{
                                                        records.appIds ? JSON.parse(records.appIds) : '不限'
                                                    }}</span>
                                                </a-col>
                                                <a-col :sm="12" style="text-align:left"
                                                    ><span>智能扩量：</span>
                                                    <span>{{ records.isOpen == 0 ? '关闭' : '开启' }}</span></a-col
                                                >
                                            </a-row>
                                            <a-row :gutter="20">
                                                <a-col :sm="12" style="text-align:left">
                                                    <span>投放时段：</span>
                                                    <span>
                                                        {{ setItemDate(records.scheduleTime) }}
                                                    </span>
                                                </a-col>
                                            </a-row>
                                        </div>
                                        <span slot="bidType" slot-scope="text, records">
                                            {{ text | bidType }}
                                        </span>
                                        <span slot="dayBudget" slot-scope="text, records">
                                            <p>
                                                预算：{{
                                                    records.dayBudget || records.dayBudget > 0
                                                        ? records.dayBudget / 1000 + '元'
                                                        : '不限'
                                                }}
                                            </p>
                                            <p>
                                                出价：{{
                                                    records.bid
                                                        ? records.bid / 1000
                                                        : records.cpaBid
                                                        ? records.cpaBid / 1000
                                                        : ''
                                                }}元
                                            </p>
                                            <p v-if="records.deepConversionType">
                                                深度转化出价：{{
                                                    records.deepConversionBid ? records.deepConversionBid / 1000 : '无'
                                                }}
                                            </p>
                                        </span>

                                        <span slot="action" slot-scope="text, record">
                                            <a @click="lookCreative(record.id)">查看创意</a>
                                            <a-divider type="vertical" />
                                            <a-popconfirm
                                                :title="`确定要删除这项吗?`"
                                                @confirm="removeGroup(record.id)"
                                            >
                                                <a>删除</a>
                                                <span class="gap"></span>
                                            </a-popconfirm>
                                        </span>
                                    </a-table>
                                </div>
                            </el-collapse-item>
                        </el-collapse>
                    </div>
                </a-card>
            </a-spin>
            <a-modal
                title="查看创意"
                :width="1000"
                v-if="creativeVisible"
                :visible="creativeVisible"
                dialog-class="push-modal"
                :footer="null"
                @cancel="creativeVisible = false"
            >
                <a-table
                    :columns="creativeColumns"
                    :dataSource="creativeList"
                    :pagination="false"
                    :loading="dataLoading"
                    bordered
                    @change="tableChange"
                    size="middle"
                    style="word-break: break-all;font-size:16px;font-weight:600"
                    id="outTable"
                >
                    <span slot="coverUrl" slot-scope="text, records">
                        <img :src="text" alt="" style="width:100%" />
                    </span>
                    <span slot="creativeCategory" slot-scope="text, records">
                        <a-cascader
                            :options="createOptions"
                            v-model="text"
                            :fieldNames="fieldNames"
                            disabled
                            placeholder="请选择创意分类"
                            style="width:100%"
                        />
                    </span>
                    <span slot="creativeTag" slot-scope="text, records">
                        <span v-for="(item, index) in JSON.parse(text)"
                            >{{ item }}{{ index == JSON.parse(text).length - 1 ? '' : ',' }}</span
                        >
                    </span>
                </a-table>
            </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' // 停止除当前外的其他视频播放，及停止所有视频播放的方法

import { deleteAction } from '@/api/manage'
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)
}
var num = ['一', '二', '三', '四', '五', '六', '日']
var arr_hour = get_hour_arr()
//生成时间值数组
function get_hour_arr() {
    var arr_hour = []
    var oDate = new Date('2016/07/01 00:00:00') //实例一个时间对象；
    var oDate_hour = oDate.getHours()
    var oDate_minute = oDate.getMinutes()
    for (var i = 0; i < 24; i++) {
        if (oDate_minute < 10) {
            var oDate_minute = '0' + oDate_minute
        }
        if (i >= 1) {
            oDate.setMinutes(oDate.getMinutes() + 60)
            oDate_hour = oDate.getHours()
            oDate_minute = oDate.getMinutes()
            if (oDate_minute < 10) {
                var oDate_minute = '0' + oDate_minute
            }
        }
        arr_hour[i] = oDate_hour + ':' + oDate_minute
        // alert(oDate_hour + ':' + oDate.getMinutes());
    }
    return arr_hour
}
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 {
            spinning:false,
            fieldNames: {
                label: 'category_name',
                value: 'category_id',
                children: 'child'
            },
            creativeVisible: false,
            creativeList: [],
            dataLoading: false,
            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,
            createOptions: [],
            activeName: null,
            creativeColumns: [
                {
                    title: '封面',
                    dataIndex: 'coverUrl',
                    key: 'coverUrl',
                    align: 'center',
                    scopedSlots: { customRender: 'coverUrl' },
                    width: 200
                },
                {
                    title: '广告语',
                    dataIndex: 'description',
                    key: 'description',
                    align: 'center',
                    scopedSlots: { customRender: 'description' }
                },
                {
                    title: '行动号召',
                    dataIndex: 'actionBarText',
                    key: 'actionBarText',
                    scopedSlots: { customRender: 'actionBarText' },
                    align: 'center'
                },
                {
                    title: '创意标签',
                    dataIndex: 'creativeTag',
                    key: 'creativeTag',
                    scopedSlots: { customRender: 'creativeTag' },
                    align: 'center'
                },
                {
                    title: '创意分类',
                    dataIndex: 'creativeCategory',
                    key: 'creativeCategory',
                    align: 'center',
                    scopedSlots: { customRender: 'creativeCategory' }
                }
            ],
            columns: [
                {
                    title: '广告组名称',
                    dataIndex: 'unitName',
                    key: 'unitName',
                    align: 'center',
                    scopedSlots: { customRender: 'unitName' },
                    width: 200
                },
                {
                    title: '优化目标',
                    dataIndex: 'bidType',
                    key: 'bidType',
                    align: 'center',
                    scopedSlots: { customRender: 'bidType' },
                    width: 150
                },
                {
                    title: '预算与出价',
                    dataIndex: 'dayBudget',
                    key: 'dayBudget',
                    scopedSlots: { customRender: 'dayBudget' },
                    align: 'center',
                    width: 150
                },
                {
                    title: '定向',
                    dataIndex: 'target',
                    key: 'target',
                    scopedSlots: { customRender: 'target' },
                    align: 'center'
                },
                {
                    title: '操作',
                    dataIndex: 'action',
                    key: 'action',
                    align: 'center',
                    scopedSlots: { customRender: 'action' },
                    width: 150
                }
            ],
            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].unitCount
                }
            }
            return count
        }
    },
    watch: {},
    mounted() {
        this.getPreviewList()
    },
    filters: {
        ageShow(val) {
            let data = { 18: '18-23岁', 24: '24-30岁', 41: '41-49岁', 50: '50-100岁' }

            return data[val]
        }
    },
    methods: {
        setItemDate(external_binary) {
            //初始化周数数组
            if (external_binary) {
                var time_week_arr = []

                var date_html = ''
                var binary = external_binary

                for (var y = 0; y < 7; y++) {
                    //初始化小时数组
                    var time_hour_arr = []

                    for (var x = 0; x < 24; x++) {
                        //获取当前点击元素的位置
                        if (y == 0) {
                            var index = x
                        } else {
                            var index = y * 24 + x
                        }
                        //获取td对应的二进制值
                        var Selected_val = binary.charAt(index)

                        if (Selected_val == 1) {
                            //组装保存进数组里
                            if (time_hour_arr == []) {
                                //表格的第一个位置的值
                                time_hour_arr = arr_hour[x]
                            } else if (binary.charAt(index - 1) == 1 && binary.charAt(index - 2) == 1) {
                                //此位置（包含上一行）的前两个都为选中时

                                if (x == 0 && binary.charAt(index + 1) == 0) {
                                    //选中行里第一个，后一个表格没选中，加逗号
                                    time_hour_arr[time_hour_arr.length] = arr_hour[x] + ', '
                                } else if (x == 0 && binary.charAt(index + 1) == 1) {
                                    //选中行里第一个，后一个表格已选中，不加逗号
                                    time_hour_arr[time_hour_arr.length] = arr_hour[x]
                                } else if (x == 1 && binary.charAt(index - 1) == 0) {
                                    //选中行里第二个，上一个表格没选中，加逗号
                                    time_hour_arr[time_hour_arr.length] = arr_hour[x] + ', '
                                } else if (x == 1 && binary.charAt(index - 1) == 1) {
                                    //选中行里第二个，上一个表格已选中，前加-号，后加逗号
                                    time_hour_arr[time_hour_arr.length] = '-' + arr_hour[x] + ', '
                                } else {
                                    //选中行里除第一、二的表格以外，前一个表格已经选中，此元素前加- 后加逗号
                                    time_hour_arr[time_hour_arr.length - 1] = '-' + arr_hour[x] + ', '
                                }
                            } else if (binary.charAt(index - 1) == 1 && x > 0) {
                                //选中的前一个已选中，且此次选中的不是行里第一个，此次选中的元素前加-后加逗号
                                time_hour_arr[time_hour_arr.length] = '-' + arr_hour[x] + ', '
                            } else if (binary.charAt(index + 1) != 1 || x == 47) {
                                //选中的后一个没选中，或者此次选中的是行里最后一个，此次选中的元素加逗号
                                time_hour_arr[time_hour_arr.length] = arr_hour[x] + ', '
                            } else {
                                //选中的后一已选中，此次选中的元素不加逗号
                                time_hour_arr[time_hour_arr.length] = arr_hour[x]
                            }
                        }
                    }

                    time_week_arr[y] = time_hour_arr
                }
                //再次组装并输出数组
                var time_html = []
                for (var y = 0; y < 7; y++) {
                    for (var x = 0; x < time_week_arr[y].length; x++) {
                        if (!time_html[y]) {
                            time_html[y] = time_week_arr[y][x]
                        } else {
                            time_html[y] += time_week_arr[y][x]
                        }
                    }

                    if (time_html[y]) {
                        time_html[y] = time_html[y].substring(0, time_html[y].length - 1)

                        date_html += '星期' + num[y] + ' (' + time_html[y] + ')' + ', '
                    }
                }

                if (external_binary) {
                    return date_html
                }
                // console.info(time_html);
            } else {
                return '不限'
            }
        },
        next() {
            closeAllVideoFun()
        },
        prev() {
            closeAllVideoFun()
        },
        lookCreative(id) {
            this.creativeVisible = true
            this.dataLoading = true
            this.getAction('/dimension/kuaiShouDimensionCreative/getCreativeList', { unitTableId: id }).then(res => {
                if (res.success) {
                    this.creativeList = res.result.map(item => {
                        return {
                            ...item,
                            creativeCategory: item.creativeCategory
                                ? item.creativeCategory > 10000
                                    ? [
                                          parseInt(item.creativeCategory / 10000),
                                          parseInt(item.creativeCategory / 100),
                                          item.creativeCategory
                                      ]
                                    : item.creativeCategory > 100
                                    ? [parseInt(item.creativeCategory / 100), item.creativeCategory]
                                    : [item.creativeCategory]
                                : []
                        }
                    })
                    this.dataLoading = false
                } else {
                    this.dataLoading = false
                }
            })
        },
        createArr() {
            this.newBatch = true
            var params = {}
            this.newBatch = true
            var groupIds = []
            // for (let i = 0; i < this.campaignList.length; i++) {
            //     for (let j = 0; j < this.campaignList[i].campaignInfo.unitDetail.length; j++) {
            //         groupIds.push(this.campaignList[i].campaignInfo.unitDetail[j].id)
            //     }
            // }
            var params = {}
            params.submitStatus = 1
            params.ids = this.groupCheck
            params.strategyId = this.$route.query.id
            let that = this
            this.postDataAction('/dimension/kuaiShouDimensionUnit/editBatch', params).then(res => {
                let num = 0
                for (let i = 0; i < this.campaignList.length; i++) {
                    num += this.campaignList[i].campaignInfo.length
                }
                if (num == 0) {
                    this.$success({
                        title: '全部提交成功',
                        // JSX support
                        onOk: function() {
                            that.$router.replace('/autoLaunch/material-test')
                            that.$bus.$emit('remove', `/autoLaunch/lookPreview?id=${that.$route.query.id}`)
                        }
                    })
                } else {
                    this.getPreviewList()
                }
            })
        },
        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() {
            deleteAction('/dimension/kuaiShouDimensionUnit/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.spinning = true
            this.getAction('/dimension/kuaiShouDimensionUnit/previewByStrategyId', {
                strategyId: this.$route.query.id
            }).then(res => {
                if (res.success) {
                    if (res.result[0].campaignInfo) {
                        this.campaignList = res.result
                        this.getAction('/kuaishou/batch/getCreativeCategory', {
                            accountId: this.campaignList[0].accountId
                        }).then(result => {
                            if (result.success) {
                                //console.log(res)
                                this.createOptions = result.result
                                this.spinning = false
                            }
                        })
                    } else {
                        this.$message.error('没有可预览的值')
                        this.spinning = false
                    }

                    // this.activeName = this.campaignList[0].id
                } else {
                    this.$message.error('网络开小差了，请刷新后重试')
                    this.spinning = false
                }
            })
        },
        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) {
            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
                    }
                })
            }
        },
        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) {
            deleteAction('/dimension/kuaiShouDimensionUnit/deleteBatch', { ids: 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].campaignInfo.length; j++) {
                    for (let o = 0; o < this.campaignList[i].campaignInfo[j].unitDetail.length; o++) {
                        groupIds.push(this.campaignList[i].campaignInfo[j].unitDetail[o].id)
                    }
                }
            }
            var params = {}
            params.submitStatus = 1
            params.ids = groupIds
            params.strategyId = this.$route.query.id
            let that = this
            this.postDataAction('/dimension/kuaiShouDimensionUnit/editBatch', params).then(res => {
                this.$success({
                    title: '全部提交成功',
                    // JSX support
                    onOk: function() {
                        that.$router.replace('/autoLaunch/material-test')
                        that.$bus.$emit('remove', `/autoLaunch/lookPreview?id=${that.$route.query.id}`)
                    }
                })
            })
        }
    }
}
</script>

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