<style lang="scss" scoped>
.search-bar {
    display: flex;
    align-items: center;
}
.search-box p {
    display: inline-block;
    border: 1px solid #f2f2f2;
    border-radius: 5px;
    margin-right: 10px;
    padding: 5px 10px;
    cursor: pointer;
}
.card-person-drawer {
    width: 100%;
    height: 90%;
    overflow: hidden;
    padding: 10px 0px;
    display: flex;
    flex-wrap: wrap;
    margin-right: -10px;
    ::v-deep .ant-card-body {
        padding: 0;
    }
    ::v-deep .ant-card-head {
        padding: 0 5px;
    }
    .card-item {
        width: calc(20% - 10px);
        margin: 10px 5px;
        float: left;
    }
    .card-item-else {
        width: calc(20% - 10px);
        margin: 10px 5px;
        float: left;
    }
}
</style>
<style scoped>
.showNumBox {
    margin: 10px 0;
}
.showNumBox .ant-card-body {
    display: flex;
    justify-content: center;
}
.showNumBox p,
.showNumBox span {
    text-align: center;
    line-height: 40px;
    font-size: 30px;
    font-weight: 600;
    color: red;
    margin: 0;
}
.search-box .ant-card-body {
    padding: 5px 15px;
}
.showNumBox .ant-card-body .styleElse {
    line-height: 60px;
    height: 40px;
    font-size: 16px;
    font-weight: 400;
    margin-left: 10px;
}
.ant-modal-wrap .yincang .ant-modal-content .ant-modal-footer {
    display: none !important;
}
.yincang .ant-col-6 p {
    text-align: left;
    color: red;
    font-size: 16px;
    font-weight: 500;
}
.ant-table-thead div {
    font-weight: 700;
}
.tool-tip {
    position: absolute;
    top: 65px;
    right: 10px;
}
</style>
<style lang="less" scoped>
.ant-card-head .ant-tabs-bar {
    padding: 0;
}
.search-box .ant-card-body {
    padding: 5px 15px;
}
.search-box {
    padding: 15px 10px;
}
.search-box p {
    display: inline-block;
    border: 1px solid #f2f2f2;
    border-radius: 5px;
    margin-right: 10px;
    padding: 5px 10px;
    cursor: pointer;
}
.statistics .ant-col-6 .ant-card-body .styleElse {
    line-height: 60px;
    height: 40px;
    font-size: 16px;
    font-weight: 400;
    margin-left: 10px;
}
.ant-modal-wrap .yincang .ant-modal-content .ant-modal-footer {
    display: none !important;
}
.yincang .ant-col-6 p {
    text-align: left;
    color: red;
    font-size: 16px;
    font-weight: 500;
}
.ant-table-thead div {
    font-weight: 700;
}
.tool-tip {
    position: absolute;
    top: 65px;
    right: 10px;
}
.statistics {
    .ant-card-bordered {
        border: none;
    }
    .ant-card-head .ant-tabs {
        clear: both;
        margin-bottom: -13px;
        color: rgba(0, 0, 0, 0.65);
        font-weight: normal;
        font-size: 14px;
    }
    .duibi {
        position: absolute;
        right: 24px;
        top: 15px;
    }
    p {
        margin-bottom: 0;
    }
}
</style>

<style lang="less" scoped>
.middle-button {
    margin: 0 8px;
}
.newPlanStatic {
    .divider {
        height: 62px;
    }
    .showNumBox {
        background: white;
        overflow: hidden;
        margin: 15px 0;
        padding: 30px 0;
        text-align: center;
        .ant-card-body {
            padding-top: 0;
        }
        .title {
            font-size: 14px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #999999;
            line-height: 22px;
            display: inline-block;
        }
    }
    .tabbody {
        background: white;
        padding: 0 24px;
        margin-bottom: 15px;
        .ant-tabs-bar {
            margin: 0;
        }
    }
    .chartBox {
        background: white;
        padding: 20px 0;
    }
    .tableBody {
        background: white;
        padding: 20px;
    }
}
</style>
<template>
    <div class="newPlanStatic config-project">
        <div class="tabbody">
            <a-tabs v-model="tabKey" @change="tabChange">
                <a-tab-pane :key="1" tab="智能托管配置信息"> </a-tab-pane>
                <!-- <a-tab-pane :key="2" tab="账户"> </a-tab-pane> -->
                <a-button slot="tabBarExtraContent" type="primary" @click="newCreat(null)">
                    创建投放策略
                </a-button>
            </a-tabs>
        </div>
        <a-card>
            <div class="table-page-search-wrapper">
                <a-form layout="inline" :form="form" hide-required-mark :selfUpdate="true" @submit="handleQueryList">
                    <a-row :gutter="24" v-if="tabKey === 1">
                        <a-col :md="8" :sm="8" :xxl="8">
                            <a-form-item label="账户名称">
                                <selectTreeAccount
                                    v-decorator="['accountId', { initialValue: undefined }]"
                                    style="width:100%"
                                    :limit="1"
                                />
                            </a-form-item>
                        </a-col>
                        <a-col :md="8" :sm="8" :xxl="8">
                            <a-form-item label="策略名称">
                                <a-input placeholder="请输入策略名称" v-decorator="['name', { initialValue: undefined }]"/>
                            </a-form-item>
                        </a-col>
                        
                        <a-col :md="8" :sm="8" :xxl="8">
                            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
                                <a-button type="primary" icon="search" @click="handleQueryList">查询</a-button>
                                <a-button type="primary" @click="handleResetForm" icon="reload" class="middle-button"
                                    >重置</a-button
                                >
                            </span>
                        </a-col>
                    </a-row>
                </a-form>
            </div>
        </a-card>

        <a-row style="margin-bottom:15px;margin-top:12px">
            <a-col :span="24">
                <div class="tableBody" style="min-height:200px;padding-bottom: 50px">
                    <a-table
                        :columns="columns"
                        :dataSource="dataSource"
                        :pagination="false"
                        :loading="dataLoading"
                        bordered
                        @change="tableChange"
                        size="middle"
                        style="word-break: break-all;font-size:16px;font-weight:600"
                        id="outTable"
                        ref="accountTable"
                    >
                        <span slot="allAccountCount" slot-scope="text, record">
                            {{ record.successCount + '/' + text }}
                        </span>
                        <span slot="action" slot-scope="text, record">
                            <div v-if="record.projectName !== '-'">
                                <a @click="newCreat(record.id)">编辑</a>
                                <a-divider type="vertical" />
                                <a
                                    @click="
                                        ipaginationVideo.dateValue = []
                                        selectMaterial(record)
                                    "
                                    >选择素材</a
                                >
                                <a-divider type="vertical" />
                                <a @click="createLog(record)">创建记录</a>
                                <a-divider type="vertical" />
                                <a-popconfirm title="确定删除吗?" @confirm="() => deleteById(record.id)">
                                    <a>删除</a>
                                </a-popconfirm>
                            </div>
                            <div v-else>
                                -
                            </div>
                        </span>
                    </a-table>
                    <a-pagination
                        size="small"
                        :showTotal="ipagination.showTotal"
                        style="float: right;margin-top:10px"
                        v-if="dataSource.length > 0"
                        showQuickJumper
                        :pageSize.sync="ipagination.pageSize"
                        :total="ipagination.total"
                        v-model="ipagination.current"
                        @change="getDataSource"
                    />
                </div>
            </a-col>
        </a-row>
        <!-- 修改出价 -->
        <a-modal
            title="修改出价"
            v-if="modifyPriceVisible"
            :visible="modifyPriceVisible"
            :confirm-loading="modifyPriceLoading"
            dialog-class="push-modal"
            @ok="handleOkPrice"
            @cancel="handleCancelPrice"
        >
            <a-form
                :form="priceForm"
                :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
                :wrapperCol="{ lg: { span: 17 }, sm: { span: 17 } }"
                v-if="modifyPriceDetail"
            >
                <a-form-item label="策略名称"> {{ modifyPriceDetail.strategyName }} </a-form-item>
                <a-form-item label="优化目标">
                    <a-button type="primary">{{ modifyPriceDetail.bidType | bidType }}</a-button></a-form-item
                >
                <a-form-item label="转化目标"> {{ modifyPriceDetail.ocpxActionType | ocpxActionType }}</a-form-item>
                <a-form-item label="计费方式">
                    <a-button type="primary">{{
                        modifyPriceDetail.bidType === 2 ? '点击计费（CPC）' : '按展示付费（oCPM）'
                    }}</a-button>
                </a-form-item>
                <a-form-item label="转化目标出价">
                    <a-input
                        style="width:200px;ime-mode:disabled"
                        v-decorator="['cpaBid', { rules: [{ required: true, validator: cpaBidValid }] }]"
                    >
                    </a-input>
                    <br />
                    <span style="color:red"
                        >单出价请输入单数字，阶梯出价请用/隔开 例如10/12，区间出价请用-链接 例如20-25</span
                    >
                </a-form-item>
                <a-form-item
                    label="深度转化出价"
                    v-if="modifyPriceDetail.deepConversionBid && modifyPriceDetail.deepConversionBid != ''"
                    ><a-input
                        style="width:200px;ime-mode:disabled"
                        v-decorator="['deepConversionBid', { rules: [{ required: true, validator: cpaBidValid }] }]"
                    >
                    </a-input>
                    <br />
                    <span style="color:red"
                        >单出价请输入单数字，阶梯出价请用/隔开 例如10/12，区间出价请用-链接 例如20-25</span
                    >
                </a-form-item>
            </a-form>
        </a-modal>

        <a-modal
            title="创建记录"
            :width="800"
            v-if="accountVisible"
            :visible="accountVisible"
            :footer="null"
            @cancel="accountVisible = false"
            dialog-class="push-modal"
        >
            <a-table
                :columns="columnsLog"
                :dataSource="dataSourceLog"
                :pagination="ipaginationLog"
                :loading="dataLogLoading"
                bordered
                size="middle"
                style="word-break: break-all;font-size:16px;font-weight:600"
                id="outTable"
                ref="accountTable"
            >
                <span slot="cpaBid" slot-scope="text, record">
                    {{ text ? text / 1000 : '-' }}
                </span>
                <span slot="deepConversionBid" slot-scope="text, record">
                    {{ text ? text / 1000 : '-' }}
                </span>
            </a-table>
        </a-modal>
        <!-- 选择素材 -->
        <a-modal
            title="选择素材"
            :width="1000"
            v-if="materialVisible"
            :visible="materialVisible"
            :confirm-loading="materialLoading"
            dialog-class="push-modal"
            @ok="handleOkMaterial"
            @cancel="
                materialVisible = false
                checkPersonElse = []
                checkVideo = []
                checkPersonOne = ''
                sumContent = 0
            "
        >
            <div style="width:100%;display:flex;    justify-content: space-between;">
                <!-- <span>已选择：{{ sumContent }}</span> -->
                <div style="display:flex">
                    <a-input v-model="ipaginationVideo.name" type="text" placeholder="请输入需要搜索的素材名称" />
                    <!--  -->
                    <a-range-picker
                        :disabled-date="disabledDate"
                        format="YYYY-MM-DD"
                        v-model="ipaginationVideo.dateValue"
                        style="margin:0 5px"
                    />
                    <a-button type="primary" @click="searchMaterial" :loading="searchLoading"> 搜索</a-button>
                    <a-button type="primary" @click="setAllData" style="margin:0 5px"> 全选</a-button>
                </div>
                <a-button slot="tabBarExtraContent" type="primary" @click="tongbu()" :loading="tongbuLoading">
                    刷新素材</a-button
                >
            </div>
            <a-spin :spinning="spinning">
                <a-checkbox-group v-model="checkVideo" style="width: 100%;" @change="setVideoDataAll">
                    <div class="card-person-drawer info-detail">
                        <a-card class="card-person card-item" v-for="(item, index) in dataVideoList" :key="index">
                            <div
                                slot="title"
                                style="    overflow: hidden;
                            text-overflow: ellipsis;
                            white-space: nowrap;"
                            >
                                {{ item.photoName }}
                            </div>
                            <div slot="extra">
                                <a-checkbox :value="item.photoId" @change="setVideoData(item.photoId)"></a-checkbox>
                            </div>
                            <div style="width:100%;border: 1px solid #f2f2f2;position:relative">
                                <img :src="item.coverUrl" style="width:100%" alt="" />
                                <a-tag
                                    color="blue"
                                    v-if="item.useStatus == 0"
                                    style="position:absolute;top:5px;right:0px"
                                >
                                    已测试
                                </a-tag>
                            </div>
                        </a-card>
                    </div>
                </a-checkbox-group>
                <div style="text-align:right">
                    <a-pagination
                        size="small"
                        :showTotal="ipaginationVideo.showTotal"
                        style="float:right"
                        v-if="dataVideoList.length > 0"
                        showQuickJumper
                        :pageSize.sync="ipaginationVideo.pageSize"
                        :total="ipaginationVideo.total"
                        v-model="ipaginationVideo.current"
                        @change="getDataVideo"
                    />
                </div>
            </a-spin>
        </a-modal>
    </div>
</template>

<script>
import { TreeSelect } from 'ant-design-vue'
const SHOW_PARENT = TreeSelect.SHOW_PARENT
import ARow from 'ant-design-vue/es/grid/Row'
import ACol from 'ant-design-vue/es/grid/Col'
import moment from 'moment'
import pick from 'lodash.pick'
import { getKsAccountReport, getKsDetail, getReportList } from '@api/video.js'
import { getAction, postAction, downFile, downFilePost, deleteAction } from '@/api/manage'
import checkBoxGroup from '@/components/formComponents/checkBoxGroup'
import selectCheckAll from '@/views/modules/kuaishouapp/account/stepForm/stepModule/test'
import qs from 'qs'
import { mapGetters } from 'vuex'
import selectTreeAccount from '@/components/formComponents/selectAccount.vue'
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)
}
let TTcolumns = [
    {
        title: '策略名称',
        dataIndex: 'name',
        scopedSlots: { customRender: 'name' },
        align: 'center',
        key: 'name'
    },
    {
        title: '项目名称',
        dataIndex: 'projectName',
        scopedSlots: { customRender: 'projectName' },
        align: 'center',
        key: 'projectName'
    },
    {
        title: '账户ID',
        dataIndex: 'accountId',
        scopedSlots: { customRender: 'accountId' },
        align: 'center',
        key: 'accountId'
    },
    {
        title: '账户名称',
        dataIndex: 'accountName',
        scopedSlots: { customRender: 'accountName' },
        align: 'center',
        key: 'accountName'
    },
    {
        title: '用户名称',
        dataIndex: 'userName',
        scopedSlots: { customRender: 'userName' },
        align: 'center',
        key: 'userName'
    },
    {
        title: '视频数量',
        dataIndex: 'videoCount',
        scopedSlots: { customRender: 'videoCount' },
        align: 'center',
        key: 'videoCount'
    },
    {
        title: '策略日期',
        dataIndex: 'createTime',
        scopedSlots: { customRender: 'createTime' },
        align: 'center',
        key: 'createTime'
    },
    {
        title: '操作',
        dataIndex: 'action',
        scopedSlots: { customRender: 'action' },
        align: 'center',
        key: 'action',
        width: '300px'
    }
]

let KScolumns = []

export default {
    components: {
        ACol,
        ARow,
        checkBoxGroup,
        selectCheckAll,
        selectTreeAccount
    },

    data() {
        return {
            tongbuLoading: false,
            searchLoading: false,
            appIds: [],
            appOptions: [],
            materialVisible: false,
            materialLoading: false,
            scheduleTimeData: [{ scheduleTime: '' }],
            indexAll: 0,
            spinning: false,
            form: this.$form.createForm(this),
            priceForm: this.$form.createForm(this),
            variableForm: this.$form.createForm(this),
            variableLoading: false,
            exportloading: false,
            dateRange: [moment().subtract(1, 'weeks'), moment()],
            noImg: require('@/assets/noImg.png'),
            validationRules: {
                bid: [
                    {
                        required: true,
                        message: '出价信息必须填写'
                        // validator: this.validateBid,
                    }
                ]
            },
            ipagination: {
                current: 1,
                pageSize: 10,
                //   pageSizeOptions: ['10', '20', '30'],
                showTotal: (total, range) => {
                    return range[0] + '-' + range[1] + ' 共' + total + '条'
                },
                showQuickJumper: true,
                showSizeChanger: true,
                pageSizeOptions: ['10', '30', '50'],
                total: 0,
                onChange: (current, pageSize) => {
                    // 切换分页时的回调，
                    // 当在页面定义change事件时，切记要把此处的事件清除，因为这两个事件重叠了，可能到时候会导致一些莫名的bug
                    this.ipagination.current = current
                    this.ipagination.pageSize = pageSize
                }
            },
            ipaginationVideo: {
                current: 1,
                pageSize: 20,
                id: '',
                accountId: '',
                dateValue: [],
                name: '',
                //   pageSizeOptions: ['10', '20', '30'],
                showTotal: (total, range) => {
                    return range[0] + '-' + range[1] + ' 共' + total + '条'
                },
                showQuickJumper: true,
                //   showSizeChanger: true,
                total: 0,
                onChange: current => {
                    // 切换分页时的回调，
                    // 当在页面定义change事件时，切记要把此处的事件清除，因为这两个事件重叠了，可能到时候会导致一些莫名的bug
                    this.ipaginationVideo.current = current
                }
            },
            createId: '',
            dataLogLoading: false,
            columnsLog: [
                {
                    title: '项目ID',
                    dataIndex: 'projectId',
                    scopedSlots: { customRender: 'projectId' },
                    align: 'center',
                    key: 'projectId'
                },
                {
                    title: '计划ID',
                    dataIndex: 'campaignId',
                    scopedSlots: { customRender: 'campaignId' },
                    align: 'center',
                    key: 'campaignId'
                },
                {
                    title: '出价',
                    dataIndex: 'cpaBid',
                    scopedSlots: { customRender: 'cpaBid' },
                    align: 'center',
                    key: 'cpaBid'
                },
                {
                    title: '深度转化出价',
                    dataIndex: 'deepConversionBid',
                    scopedSlots: { customRender: 'deepConversionBid' },
                    align: 'center',
                    key: 'deepConversionBid'
                },
                {
                    title: '状态',
                    dataIndex: 'remarks',
                    scopedSlots: { customRender: 'remarks' },
                    align: 'center',
                    key: 'remarks'
                }
            ],
            dataSourceLog: [],
            ipaginationLog: {
                current: 1,
                pageSize: 10,
                //   pageSizeOptions: ['10', '20', '30'],
                showTotal: (total, range) => {
                    return range[0] + '-' + range[1] + ' 共' + total + '条'
                },
                showQuickJumper: true,
                // showSizeChanger: true,
                // pageSizeOptions: ['10', '30', '50'],
                total: 0,
                onChange: (current, pageSize) => {
                    // 切换分页时的回调，
                    // 当在页面定义change事件时，切记要把此处的事件清除，因为这两个事件重叠了，可能到时候会导致一些莫名的bug
                    this.ipaginationLog.current = current
                    this.ipaginationLog.pageSize = pageSize
                    this.getCreateList({ id: this.createId })
                }
            },
            value: 'valid',
            KSaccountList: [],
            TTaccountList: [],

            KSdesignList: [],
            TTdesignList: [],

            operateDisabled: false,
            duration: 1000,
            //treeselect的参数
            treeValue: [],
            treeData: [],
            SHOW_PARENT,

            type: 3,
            dateValue: [moment().subtract(7, 'days'), moment()],

            operate: '',
            designList: [],

            tabKey: 1,

            loading: false,
            TTcolumns,
            KScolumns,
            columns: [...TTcolumns],
            dataSource: [],

            dataVideoList: [],
            checkVideo: [],
            checkPersonOne: '',
            checkPersonElse: [],
            sumContent: 0,
            tableTab: 1,

            newPlan: 0,
            effectPlan: 0,

            openOptions: false,

            target: 'createTime',
            order: 'descend',
            projectId: undefined,
            projectIdAll: undefined,
            dataLoading: false,
            url: '/kuaishouProjectStrategy/queryProjectList',
            modifyPriceVisible: false,
            modifyPriceLoading: false,
            modifyPriceDetail: null,
            accountVisible: false,
            againLoading: false,
            accountProjectDetail: null,
            regionData: [{ label: '不限', value: 'unlimited' }],
            ageData: [{ label: '不限', value: 'unlimited' }]
        }
    },
    methods: {
        moment,
        ...mapGetters(['userInfo']),
        tongbu() {
            this.tongbuLoading = true

            this.getAction('/kuaishou/batch/syncVideo', {
                accountId: this.ipaginationVideo.accountId
            }).then(res => {
                if (res.success) {
                    this.$message.success(res.message)
                    this.tongbuLoading = false
                    this.getAction('/hosting/kuaishouHostingTemplate/getVideoList', {
                        id: this.ipaginationVideo.id,
                        accountId: this.ipaginationVideo.accountId,
                        pageSize: this.ipaginationVideo.pageSize,
                        pageNo: this.ipaginationVideo.current
                    }).then(resNei => {
                        if (resNei.success) {
                            this.materialVisible = true
                            this.dataVideoList = resNei.result.list
                            this.ipaginationVideo.total = resNei.result.total
                        }
                    })
                } else {
                    this.$message.error(res.message)
                    this.tongbuLoading = false
                }
            })
        },
        searchMaterial() {
            this.searchLoading = true
            var data = {
                id: this.ipaginationVideo.id,
                accountId: this.ipaginationVideo.accountId
            }

            this.selectMaterial(data)
        },
        deleteById(id) {
            deleteAction('/hosting/kuaishouHostingTemplate/delete', { id: id }).then(res => {
                if (res.success) {
                    const paramsData = this.form.getFieldsValue()
                    this.handleGetTableList(paramsData)
                }
            })
        },
        setAllData() {
            this.checkVideo.push(
                ...this.dataVideoList.map(item => {
                    return item.photoId
                })
            )
            this.checkPersonElse.push(
                ...this.dataVideoList.map(item => {
                    return item.photoId
                })
            )
            this.checkPersonElse = [...new Set(this.checkPersonElse)]
            this.checkVideo = [...new Set(this.checkVideo)]
            this.sumContent = this.checkPersonElse.length
            console.log(this.checkVideo)
        },
        setData(e, type) {
            if (type == 'region') {
                if (e.includes('1') || e.includes('2')) {
                } else {
                    let region = this.getElseData('intelliExtend')
                    let regionIndex = region.findIndex(item => item === '4')
                    if (regionIndex > -1) {
                        region.splice(regionIndex, 1)
                        this.variableForm.setFieldsValue({ intelliExtend: region })
                    }
                }
            } else if (type == 'agesRange') {
                if (e.includes('18') || e.includes('24') || e.includes('31') || e.includes('41') || e.includes('50')) {
                } else {
                    let agesRange = this.getElseData('intelliExtend')
                    let agesRangeIndex = agesRange.findIndex(item => item === '2')
                    if (agesRangeIndex > -1) {
                        agesRange.splice(agesRangeIndex, 1)
                        this.variableForm.setFieldsValue({ intelliExtend: agesRange })
                    }
                }
            } else if (type == 'gender') {
                if (e.includes('1') || e.includes('0')) {
                } else {
                    let gender = this.getElseData('intelliExtend')
                    let genderIndex = gender.findIndex(item => item === '3')
                    if (genderIndex > -1) {
                        gender.splice(genderIndex, 1)
                        this.variableForm.setFieldsValue({ intelliExtend: gender })
                    }
                }
            } else if (type == 'appIds') {
                if (e.includes('1')) {
                } else {
                    this.appIds = []
                }
            }
        },
        newCreat(id) {
            if (id) {
                this.$router.push({
                    path: '/autoLaunch/trusteeship/creatMaterialTest?id=' + id
                })
            } else {
                // window.open('/creat-material-test', '_blank')
                this.$router.push({
                    path: '/autoLaunch/trusteeship/creatMaterialTest'
                })
            }
        },
        remoteMethod(query) {
            if (query !== '') {
                getAction('/kuaishou/batch/getAppSearch', {
                    accountId: this.accountProjectDetail.accountId,
                    appName: query
                }).then(res => {
                    if (res.result) {
                        this.appOptions = res.result.map(item => {
                            return {
                                value: item.appId,
                                label: item.appName
                            }
                        })
                    } else {
                    }
                })
            } else {
                this.appOptions = []
            }
        },
        addSchedule() {
            this.scheduleTimeData.push({ scheduleTime: '' })
        },
        deleteSchedule(index) {
            this.scheduleTimeData.splice(index, 1)
        },
        editPrice(item) {
            this.modifyPriceVisible = true
            this.modifyPriceDetail = { ...item }

            this.$nextTick(() => {
                let cpaBid = ''
                let changeBid =
                    this.modifyPriceDetail.bidType === 2 ? this.modifyPriceDetail.bid : this.modifyPriceDetail.cpaBid
                if ((changeBid + '').includes('/')) {
                    let bidArr = changeBid.split('/')
                    for (let index = 0; index < bidArr.length; index++) {
                        bidArr[index] = bidArr[index] / 1000
                    }
                    cpaBid = bidArr.join('/')
                } else if ((changeBid + '').includes('-')) {
                    let bidArr = changeBid.split('-')
                    for (let index = 0; index < bidArr.length; index++) {
                        bidArr[index] = bidArr[index] / 1000
                    }
                    cpaBid = bidArr.join('-')
                } else {
                    cpaBid = changeBid / 1000
                }

                let deepConversionBid = undefined
                if (this.modifyPriceDetail.deepConversionBid && this.modifyPriceDetail.deepConversionBid != '') {
                    if ((this.modifyPriceDetail.deepConversionBid + '').includes('/')) {
                        let bidArr = this.modifyPriceDetail.deepConversionBid.split('/')
                        for (let index = 0; index < bidArr.length; index++) {
                            bidArr[index] = bidArr[index] / 1000
                        }
                        deepConversionBid = bidArr.join('/')
                    } else if ((this.modifyPriceDetail.deepConversionBid + '').includes('-')) {
                        let bidArr = this.modifyPriceDetail.deepConversionBid.split('-')
                        for (let index = 0; index < bidArr.length; index++) {
                            bidArr[index] = bidArr[index] / 1000
                        }
                        deepConversionBid = bidArr.join('-')
                    } else {
                        deepConversionBid = this.modifyPriceDetail.deepConversionBid / 1000
                    }
                }

                this.priceForm.setFieldsValue({
                    cpaBid: cpaBid,
                    deepConversionBid: deepConversionBid
                })
            })
        },
        handleOkPrice() {
            this.priceForm.validateFields((err, values) => {
                //console.log(values)
                if (!err) {
                    this.modifyPriceLoading = true
                    if (values.cpaBid) {
                        if ((values.cpaBid + '').includes('/')) {
                            let bidArr = values.cpaBid.split('/')
                            for (let index = 0; index < bidArr.length; index++) {
                                bidArr[index] = bidArr[index] * 1000
                            }
                            values.cpaBid = bidArr.join('/')
                        } else if ((values.cpaBid + '').includes('-')) {
                            let bidArr = values.cpaBid.split('-')
                            for (let index = 0; index < bidArr.length; index++) {
                                bidArr[index] = bidArr[index] * 1000
                            }
                            values.cpaBid = bidArr.join('-')
                        } else {
                            values.cpaBid = values.cpaBid * 1000
                        }
                    } else {
                        values.cpaBid = 0
                    }
                    if (values.deepConversionBid) {
                        if ((values.deepConversionBid + '').includes('/')) {
                            let bidArr = values.deepConversionBid.split('/')
                            for (let index = 0; index < bidArr.length; index++) {
                                bidArr[index] = bidArr[index] * 1000
                            }
                            values.deepConversionBid = bidArr.join('/')
                        } else if ((values.deepConversionBid + '').includes('-')) {
                            let bidArr = values.deepConversionBid.split('-')
                            for (let index = 0; index < bidArr.length; index++) {
                                bidArr[index] = bidArr[index] * 1000
                            }
                            values.deepConversionBid = bidArr.join('-')
                        } else {
                            values.deepConversionBid = values.deepConversionBid * 1000
                        }
                    } else {
                        values.deepConversionBid = 0
                    }
                    // this.modifyPriceDetail
                    let params = {}
                    if (this.modifyPriceDetail.bidType === 2) {
                        params.bid = values.cpaBid
                        if (values.deepConversionBid) {
                            params.deepConversionBid = values.deepConversionBid
                        }
                    } else {
                        params = { ...values }
                    }
                    postAction('/dimension/kuaiShouDimensionStrategy/edit', {
                        ...params,
                        id: this.modifyPriceDetail.id
                    }).then(res => {
                        this.modifyPriceLoading = false
                        if (res.success) {
                            this.handleCancelPrice()
                            const paramsData = this.form.getFieldsValue()
                            this.handleGetTableList(paramsData)
                        } else {
                            this.$message.error(res.message)
                        }
                    })
                } else {
                    this.$message.error('请正确填写必填项目')
                }
            })
        },
        handleCancelPrice() {
            this.priceForm.resetFields()
            this.modifyPriceVisible = false
        },
        cpaBidValid(rule, value, callback) {
            let z = /-/g
            let a = /\//g
            let d = /\./g
            if (value === '' || value === undefined) {
                callback('出价必须填写')
            } else if (value.startsWith('.') || value.endsWith('.')) {
                callback('请填写正确出价')
            } else if (value.startsWith('-') || value.endsWith('-')) {
                callback('请填写正确出价')
            } else if (value.match(a) && value.match(z)) {
                callback('不允许出现除"-"和"/"之外的所有字符，并且二者不可同时出现')
            } else if (value.match(/[^0-9+-\/]/g)) {
                callback('请填写正确出价')
            } else {
                callback()
            }
        },
        btKeyUp(e) {
            //没有显示‘破折号’和 '.' 需要的可以手动加上
            // this.priceForm.setFieldsValue({
            //     cpaBid: e.target.value.replace(/[^0-9+-\/]/g, '')
            // })
            // (
            //         /[\u4e00-\u9fa5/\s+/]|[`~!@#$%^&*() \+ =<>?"{}|, \/ ;' \\ [ \] ·~！@#￥%……&*（）—— \+ ={}|《》？：“”【】、；‘’，。、]/g,
            //         ''
            //     )
        },
        getData(className) {
            return this.priceForm.getFieldValue(className)
        },
        getElseData(className) {
            return this.variableForm.getFieldValue(className)
        },
        againAccount() {
            this.againLoading = true
            this.getAction('/ai/projectCreate/projectAutomaticCreates', {
                id: this.accountProjectDetail.id,
                operationType: 1
            }).then(res => {
                this.againLoading = false
                if (res.success) {
                    this.$message.success('重新匹配成功')
                } else {
                    this.$message.error(res.message)
                }
            })
        },
        createLog(item) {
            this.accountVisible = true
            this.createId = item.id
            this.ipaginationLog.current = 1
            this.getCreateList(item)
        },
        getCreateList(item) {
            this.dataLogLoading = true
            var params = {}
            params.templateId = item.id
            params.pageNo = this.ipaginationLog.current
            params.pageSize = this.ipaginationLog.pageSize
            this.getAction('/task/kuaishouHostingTask/list', params).then(res => {
                this.dataLogLoading = false
                if (res.success) {
                    this.dataSourceLog = res.result.records || []
                    this.ipaginationLog.total = res.result.total || 0
                }
            })
        },
        selectMaterial(item) {
            this.materialVisible = true
            this.spinning = true
            this.ipaginationVideo.id = item.id
            this.ipaginationVideo.accountId = item.accountId
            this.ipaginationVideo.current = 1
            this.getAction('/hosting/kuaishouHostingTemplate/getVideoList', {
                id: this.ipaginationVideo.id,
                accountId: this.ipaginationVideo.accountId,
                pageSize: this.ipaginationVideo.pageSize,
                pageNo: this.ipaginationVideo.current,
                startDate:
                    this.ipaginationVideo.dateValue && this.ipaginationVideo.dateValue.length === 2
                        ? moment(this.ipaginationVideo.dateValue[0]).format('YYYY-MM-DD')
                        : null,
                endDate:
                    this.ipaginationVideo.dateValue && this.ipaginationVideo.dateValue.length === 2
                        ? moment(this.ipaginationVideo.dateValue[1]).format('YYYY-MM-DD')
                        : null,
                name: this.ipaginationVideo.name
            }).then(resNei => {
                this.searchLoading = false
                this.spinning = false
                if (resNei.success) {
                    this.dataVideoList = resNei.result.records
                    this.ipaginationVideo.total = resNei.result.total
                }
            })
        },
        lookPreview(item) {
            this.$router.push({
                path: '/autoLaunch/lookPreview?id=' + item.id
            })
            // getAction('/dimension/kuaiShouDimensionUnit/previewByStrategyId', { strategyId: item.id }).then(res => {})
        },
        getDataVideo(current, pageSize) {
            // 切换分页时的回调，
            // 当在页面定义change事件时，切记要把此处的事件清除，因为这两个事件重叠了，可能到时候会导致一些莫名的bug
            this.spinning = true
            this.ipaginationVideo.current = current
            this.ipaginationVideo.pageSize = pageSize
            this.checkVideo = this.checkPersonElse
            this.dataVideoList = []
            this.getAction('/hosting/kuaishouHostingTemplate/getVideoList', {
                id: this.ipaginationVideo.id,
                accountId: this.ipaginationVideo.accountId,
                pageSize: this.ipaginationVideo.pageSize,
                pageNo: this.ipaginationVideo.current,
                startDate:
                    this.ipaginationVideo.dateValue && this.ipaginationVideo.dateValue.length === 2
                        ? moment(this.ipaginationVideo.dateValue[0]).format('YYYY-MM-DD')
                        : null,
                endDate:
                    this.ipaginationVideo.dateValue && this.ipaginationVideo.dateValue.length === 2
                        ? moment(this.ipaginationVideo.dateValue[1]).format('YYYY-MM-DD')
                        : null,
                name: this.ipaginationVideo.name
            }).then(resNei => {
                this.spinning = false
                if (resNei.success) {
                    this.dataVideoList = resNei.result.records
                    this.ipaginationVideo.total = resNei.result.total
                }
            })
        },
        getDataSource(current, pageSize) {
            // 切换分页时的回调，
            // 当在页面定义change事件时，切记要把此处的事件清除，因为这两个事件重叠了，可能到时候会导致一些莫名的bug
            this.ipagination.current = current
            this.ipagination.pageSize = pageSize
            const paramsData = this.form.getFieldsValue()
            this.handleGetTableList(paramsData)
        },
        handleOkMaterial() {
            let dataAll = this.checkPersonElse
            this.checkVideo = dataAll
            this.materialLoading = true
            this.postDataAction('/task/kuaishouHostingTask/submitTask', {
                templateId: this.ipaginationVideo.id,
                videoArray: this.checkVideo
            }).then(res => {
                this.materialLoading = false
                if (res.success) {
                    this.materialVisible = false
                    this.checkPersonElse = []
                    this.checkVideo = []
                    this.checkPersonOne = ''
                    this.sumContent = 0
                }
            })
        },
        setVideoData(data) {
            this.checkPersonOne = data
        },
        setVideoDataAll(data) {
            //  checkPerson: [],
            // checkPersonAll: [],
            if (data.findIndex(item => item === this.checkPersonOne) > -1) {
                this.checkPersonElse.push(...data)
                this.checkPersonElse = [...new Set(this.checkPersonElse)]
            } else {
                data.findIndex(item => item === this.checkPersonOne) > -1
                this.checkPersonElse.splice(
                    this.checkPersonElse.findIndex(item => item === this.checkPersonOne),
                    1
                )
            }

            this.sumContent = this.checkPersonElse.length
            // var dataCount = 20
            // if (this.sumContent > dataCount) {
            //     this.$message.error('最多选择' + dataCount + '个定向')
            //     this.checkPerson.pop()
            //     this.checkPersonElse.splice(
            //         this.checkPersonElse.findIndex(item => item === this.checkPersonOne),
            //         1
            //     )
            //     this.sumContent--

            //     // this.checkPersonAll[this.ipagination.current - 1] = this.checkPerson
            // }
        },

        onChangeStatus(text, rescord, type) {
            let status = text === 0 ? 1 : 0
            let url = ''
            let params = {}
            params.id = rescord.id
            params.strategyStatus = status
            url = '/dimension/kuaiShouDimensionStrategy/edit'
            this.postDataAction(url, params).then(res => {
                if (res.success) {
                    const paramsData = this.form.getFieldsValue()
                    this.handleGetTableList(paramsData)
                } else {
                    this.$message.error(res.message)
                }
            })
        },
        handleQueryList(event) {
            this.ipagination.current = 1
            event.preventDefault()
            const paramsData = this.form.getFieldsValue()
            this.handleGetTableList(paramsData)
        },
        handleResetForm() {
            this.ipagination.current = 1
            this.form.resetFields()
            if (this.tabKey == 1) {
                this.projectId = undefined
                this.projectIdAll = undefined
            }
            const paramsData = this.form.getFieldsValue()
            this.handleGetTableList(paramsData)
        },
        handleGetTableList(data) {
            let paramsData = {
                ...data,
                startDate:
                    data.timeRange && data.timeRange.length === 2
                        ? moment(data.timeRange[0]).format('YYYY-MM-DD')
                        : null,
                endDate:
                    data.timeRange && data.timeRange.length === 2
                        ? moment(data.timeRange[1]).format('YYYY-MM-DD')
                        : null,
                pageNo: this.ipagination.current,
                pageSize: this.ipagination.pageSize,
                userId: this.userInfo().id
            }
            this.dataSource = []
            this.dataLoading = true
            this.getAction('/hosting/kuaishouHostingTemplate/list', paramsData)
                .then(result => {
                    this.dataLoading = false
                    if (result.success) {
                        this.dataSource = result.result.records || []
                        // if (result.result.total) {
                        //     this.dataSource.unshift(result.result.total)
                        // }

                        this.ipagination.total = result.result.total || 0
                        // result.result.total
                    } else {
                        this.$message.error(result.message)
                    }
                })
                .catch(error => {
                    this.dataLoading = false
                    console.log(error, 'eeee')
                })
        },
        getAccountNoProject() {
            this.projectId = undefined
            const paramsData = this.form.getFieldsValue()
            this.handleGetTableList(paramsData)
        },
        toAccountDetail(item) {
            this.tabKey = 2
            this.projectId = { id: item.projectId, name: item.projectName }
            this.url =
                this.tabKey == 1
                    ? '/kuaishouProjectStrategy/queryProjectList'
                    : '/kuaishouProjectStrategy/queryAccountList'
            this.$nextTick(() => {
                this.columns = this.tabKey == 1 ? [...TTcolumns] : [...KScolumns]
                this.target = this.tabKey == 1 ? 'createTime' : 'statDate'
                const paramsData = this.form.getFieldsValue()
                this.handleGetTableList(paramsData)
            })
        },
        disabledDate(current) {
            // Can not select days before today and today
            return current && current > moment().endOf('day')
        },
        dateChange(date, dateString) {
            // console.log(date,dateString)
        },

        filterOption(input, option) {
            // console.log(input, option)
            return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        },

        // 快手头条的切换
        tabChange(key) {
            this.ipagination.current = 1
            this.columns = this.tabKey == 1 ? [...TTcolumns] : [...KScolumns]
            this.url =
                this.tabKey == 1
                    ? '/kuaishouProjectStrategy/queryProjectList'
                    : '/kuaishouProjectStrategy/queryAccountList'
            this.target = this.tabKey == 1 ? 'createTime' : 'statDate'
            this.projectId = undefined
            const paramsData = this.form.getFieldsValue()
            this.handleGetTableList(paramsData)
        },
        operateChange(value) {
            console.log(value)
            if (value) {
                this.accountDisabled = true
                this.accountId = ''
            } else {
                this.accountDisabled = false
            }
        },

        tableChange(pagination, filters, sorter, { currentDataSource }) {
            this.ipagination.current = pagination.current
            this.ipagination.pageSize = pagination.pageSize
            if (sorter.order) {
                this.order = sorter.order ? sorter.order : 'descend'
                this.target = sorter.columnKey
                const paramsData = this.form.getFieldsValue()
                this.handleGetTableList({
                    ...paramsData,
                    target: sorter.columnKey,
                    order: sorter.order ? sorter.order : 'descend'
                })
            }
        },

        // table区域的tab切换
        tableTabChange(key) {
            if (key == 1) {
                this.columns = this.tabKey == 1 ? [...TTcolumns] : [...KScolumns]
                this.target = 'new'
            } else {
                this.columns = this.tabKey == 1 ? [...TTcolumns] : [...KScolumns]
                this.target = 'valid'
            }
        }
    },
    watch: {
        dateValue(newName, oldName) {
            this.search()
        }
    },
    computed: {
        newDate() {
            var myDate = new Date()
            myDate.getYear() //获取当前年份(2位)
            var n = myDate.getFullYear() //获取完整的年份(4位,1970-????)
            var m = myDate.getMonth() //获取当前月份(0-11,0代表1月)
            var d = myDate.getDate() //获取当前日(1-31)
            var day = myDate.getHours()
            return day
        }
    },
    mounted() {
        const paramsData = this.form.getFieldsValue()
        this.handleGetTableList(paramsData)
    },
    activated: function() {},

    filters: {
        toPercentage(val) {
            if (typeof val != 'string') {
                return (val * 100).toFixed(2) + '%'
            } else {
                return val
            }
        },
        //保留两位小数并且变成货币格式
        decimalsHandle(val) {
            if (val && typeof val != 'string') {
                if (val >= 0) {
                    val = parseFloat(val).toFixed(2)
                    let numberStr = val.toString()
                    let str = numberStr.split('.')

                    let str0 = str[0].split('').reverse()
                    for (let i = 0; i < str0.length; i++) {
                        if ((i + 1) % 4 === 0) {
                            str0.splice(i, 0, ',')
                        }
                    }
                    str0.reverse()
                    let handleResult = ''
                    for (let j = 0; j < str0.length; j++) {
                        handleResult += str0[j]
                    }

                    return handleResult + '.' + str[1]
                } else {
                    val = parseFloat(val).toFixed(2)
                    let numberStr = val.toString()
                    let str = numberStr.split('.')

                    let str0 = str[0]
                        .substr(1)
                        .split('')
                        .reverse()
                    for (let i = 0; i < str0.length; i++) {
                        if ((i + 1) % 4 === 0) {
                            str0.splice(i, 0, ',')
                        }
                    }
                    str0.reverse()
                    let handleResult = ''
                    for (let j = 0; j < str0.length; j++) {
                        handleResult += str0[j]
                    }

                    return '-' + handleResult + '.' + str[1]
                }
            } else if (typeof val == 'string') {
                return val
            } else {
                return 0
            }
        },
        //变成货币格式
        formatCurrency(val) {
            if (val) {
                let numberStr = val.toString()
                let str = numberStr.split('').reverse()
                for (let i = 0; i < str.length; i++) {
                    if ((i + 1) % 4 === 0) {
                        str.splice(i, 0, ',')
                    }
                }
                str.reverse()
                let handleResult = ''
                for (let j = 0; j < str.length; j++) {
                    handleResult += str[j]
                }
                return handleResult
            } else {
                return '-'
            }
        }
    }
}
</script>
