<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;
}
</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>
.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>
<style lang="less" scoped>
@import 'configProject';
</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="6">
                            <!-- <a-form-item label="项目名称">
                                <a-input
                                    v-decorator="['projectName']"
                                    type="text"
                                    placeholder="请输入需要搜索的项目名称"
                                />
                            </a-form-item> -->
                            <selectTable :projectId.sync="projectIdAll" ref="selectTable"></selectTable>
                        </a-col>

                        <a-col :md="8" :sm="8" :xxl="6">
                            <a-form-item label="运营负责人">
                                <a-select
                                    placeholder="请选择运营负责人"
                                    showSearch
                                    optionFilterProp="children"
                                    style="width: 100%"
                                    :filterOption="filterOption"
                                    v-decorator="['userId']"
                                >
                                    <a-select-option
                                        v-for="appModel in designList"
                                        :key="appModel.userId + new Date().getTime()"
                                        :value="appModel.userId"
                                        >{{ appModel.realName }}&#12288;&#12288;{{ appModel.roleName }}</a-select-option
                                    >
                                </a-select>
                            </a-form-item>
                        </a-col>
                        <!--  -->
                        <a-col :md="8" :sm="8" :xxl="6">
                            <a-form-item label="数据周期">
                                <a-range-picker
                                    :disabled-date="disabledDate"
                                    format="YYYY-MM-DD"
                                    v-decorator="['timeRange', { initialValue: [moment(), moment()] }]"
                                />
                            </a-form-item>
                        </a-col>
                        <a-col :md="8" :sm="8" :xxl="6">
                            <a-form-item label="状态">
                                <a-select
                                    v-decorator="['dataStatus', { initialValue: 'null' }]"
                                    placeholder="请选择"
                                    allow-clear
                                >
                                    <a-select-option key="null">
                                        不限
                                    </a-select-option>
                                    <a-select-option :key="1">
                                        启动
                                    </a-select-option>
                                    <a-select-option :key="0">
                                        关闭
                                    </a-select-option>
                                </a-select>
                            </a-form-item>
                        </a-col>
                        <a-col :md="8" :sm="8" :xxl="6">
                            <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-row :gutter="24" v-else>
                        <a-col :span="24" style="margin-bottom:15px" v-if="projectId">
                            <a-tag color="blue" closable @close="getAccountNoProject" v-if="projectId">
                                {{ projectId.name }}
                            </a-tag>
                        </a-col>
                        <a-col :md="8" :sm="8" :xxl="6">
                            <a-form-item label="账户名称">
                                <a-input
                                    v-decorator="['authName']"
                                    type="text"
                                    placeholder="请输入需要搜索的账户名称"
                                />
                            </a-form-item>
                        </a-col>

                        <a-col :md="8" :sm="8" :xxl="6">
                            <a-form-item label="数据周期">
                                <a-range-picker
                                    :disabled-date="disabledDate"
                                    format="YYYY-MM-DD"
                                    v-decorator="['timeRange', { initialValue: [moment(), moment()] }]"
                                />
                            </a-form-item>
                        </a-col>
                        <a-col :md="8" :sm="8" :xxl="6">
                            <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"
                        :scroll="{ x: 2500 }"
                        size="middle"
                        style="word-break: break-all;font-size:16px;font-weight:600"
                        id="outTable"
                        ref="accountTable"
                    >
                        <span slot="dataStatus" slot-scope="text, record">
                            <a-switch
                                :checked="text == 1"
                                @change="onChangeStatus(text, record, 'dataStatus')"
                                :loading="spinning"
                                v-if="record.projectName !== '-'"
                            />
                        </span>
                        <span slot="projectStrategy" slot-scope="text, record">
                            <a-switch
                                :checked="text == 1"
                                @change="onChangeStatus(text, record, 'projectStrategy')"
                                :loading="spinning"
                                v-if="record.projectName !== '-'"
                            />
                        </span>

                        <span slot="statDate" slot-scope="text, record">
                            {{ record.projectName !== '-' ? text : '-' }}
                        </span>
                        <span slot="projectName" slot-scope="text, record">
                            <a @click="toAccountDetail(record)" v-if="tabKey === 1 && text !== '-'">{{ text }}</a>
                            <span v-else> {{ text }} </span>
                        </span>
                        <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="editPrice(record)">出价</a>
                                <a-divider type="vertical" />
                                <a @click="newCreat(record.id)">编辑</a>
                                <a-divider type="vertical" />
                                <a @click="matchingAccount(record)">匹配</a>
                            </div>
                            <div v-else>
                                -
                            </div>
                        </span>
                        <span slot="charge" slot-scope="text">{{ text | decimalsHandle }}</span>

                        <span slot="companyName" slot-scope="text">{{ text || '未知' }}</span>
                        <span slot="planName" slot-scope="text">{{ text || '-' }}</span>
                        <span slot="clipName" slot-scope="text">{{ text || '-' }}</span>
                        <span slot="shotName" slot-scope="text">{{ text || '-' }}</span>

                        <span slot="activeNum" slot-scope="text">{{ text | formatCurrency }}</span>
                        <span slot="clickNum" slot-scope="text">{{ text | formatCurrency }}</span>
                        <span slot="convertNum" slot-scope="text">{{ text | formatCurrency }}</span>
                        <span slot="showNum" slot-scope="text">{{ text | formatCurrency }}</span>
                        <span slot="aclick" slot-scope="text">{{ text | formatCurrency }}</span>
                        <span slot="bclick" slot-scope="text">{{ text | formatCurrency }}</span>
                        <span slot="photoClick" slot-scope="text">{{ text | formatCurrency }}</span>
                        <span slot="photoShow" slot-scope="text">{{ text | formatCurrency }}</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.projectName }} </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"
            @cancel="accountVisible = false"
            dialog-class="push-modal"
            :footer="null"
        >
            <div v-if="accountProjectDetail" style="font-size:16px;font-weight:700;margin-bottom:15px">
                <span>项目：</span>
                <span>{{ accountProjectDetail.projectName }}</span>
            </div>
            <a-button
                type="primary"
                @click="againAccount"
                :loading="againLoading"
                style="float: right;
                    position: absolute;
                    top: 75px;
                    right: 25px;
                    z-index: 100;"
                >重新匹配</a-button
            >
            <a-table
                :columns="accountProjectColumns"
                :dataSource="accountProjectList"
                :pagination="false"
                bordered
                size="middle"
                style="word-break: break-all;font-size:16px;font-weight:600"
            >
                <span slot="authStatus" slot-scope="text">
                    {{ text === 0 ? '失败' : '成功' }}
                </span>
            </a-table>
        </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 selectTable from '@/views/modules/Statistics/components/selectPagination.vue'
import { getKsAccountReport, getKsDetail, getReportList } from '@api/video.js'
import { getAction, postAction, downFile, downFilePost } from '@/api/manage'

import qs from 'qs'

let TTcolumns = [
    {
        title: '开关',
        dataIndex: 'dataStatus',
        scopedSlots: { customRender: 'dataStatus' },
        align: 'center',
        key: 'dataStatus'
    },
    {
        title: '项目名称',
        dataIndex: 'projectName',
        scopedSlots: { customRender: 'projectName' },
        align: 'center',
        key: 'projectName'
    },
    {
        title: '可用账户数/账户数量',
        dataIndex: 'allAccountCount',
        scopedSlots: { customRender: 'allAccountCount' },
        align: 'center',
        key: 'allAccountCount'
    },

    {
        title: '运营负责人',
        dataIndex: 'responsibleName',
        scopedSlots: { customRender: 'responsibleName' },
        align: 'center',
        key: 'responsibleName'
    },
    {
        title: '策略日期',
        dataIndex: 'statDate',
        scopedSlots: { customRender: 'statDate' },
        align: 'center',
        key: 'statDate'
    },
    {
        title: '操作',
        dataIndex: 'action',
        scopedSlots: { customRender: 'action' },
        align: 'center',
        key: 'action'
    },
    {
        title: '消耗',
        dataIndex: 'charge',
        scopedSlots: { customRender: 'charge' },
        align: 'center',
        key: 'charge',
        sorter: () => {}
    },
    {
        title: '封面曝光数',
        dataIndex: 'photoShow',
        scopedSlots: { customRender: 'photoShow' },
        align: 'center',
        key: 'photoShow',
        sorter: () => {}
    },
    {
        title: '封面点击数',
        dataIndex: 'photoClick',
        scopedSlots: { customRender: 'photoClick' },
        align: 'center',
        key: 'photoClick',
        sorter: () => {}
    },
    {
        title: '素材曝光数',
        dataIndex: 'aclick',
        scopedSlots: { customRender: 'aclick' },
        align: 'center',
        key: 'aclick',
        sorter: () => {}
    },
    {
        title: '行为数',
        dataIndex: 'bclick',
        scopedSlots: { customRender: 'bclick' },
        align: 'center',
        key: 'bclick',
        sorter: () => {}
    },
    {
        title: '封面点击率',
        dataIndex: 'photoClickRatio',
        scopedSlots: { customRender: 'photoClickRatio' },
        align: 'center',
        key: 'photoClickRatio',
        sorter: () => {}
    },
    {
        title: '行为率',
        dataIndex: 'actionRatio',
        scopedSlots: { customRender: 'actionRatio' },
        align: 'center',
        key: 'actionRatio',
        sorter: () => {}
    },
    {
        title: '平均千次封面曝光花费（元）',
        dataIndex: 'impression1kCost',
        scopedSlots: { customRender: 'impression1kCost' },
        align: 'center',
        key: 'impression1kCost',
        sorter: () => {}
    },
    {
        title: '平均封面点击单价（元）',
        dataIndex: 'photoClickCost',
        scopedSlots: { customRender: 'photoClickCost' },
        align: 'center',
        key: 'photoClickCost',
        sorter: () => {}
    },
    {
        title: '平均行为单价（元）',
        dataIndex: 'actionCost',
        scopedSlots: { customRender: 'actionCost' },
        align: 'center',
        key: 'actionCost',
        sorter: () => {}
    }
]

let KScolumns = [
    {
        title: '开关',
        dataIndex: 'projectStrategy',
        scopedSlots: { customRender: 'projectStrategy' },
        align: 'center',
        key: 'projectStrategy'
    },
    {
        title: '账户名称',
        dataIndex: 'authName',
        scopedSlots: { customRender: 'authName' },
        align: 'center',
        key: 'authName'
    },
    {
        title: '账户ID',
        dataIndex: 'accountId',
        scopedSlots: { customRender: 'accountId' },
        align: 'center',
        key: 'accountId'
    },

    {
        title: '所属项目',
        dataIndex: 'projectName',
        scopedSlots: { customRender: 'projectName' },
        align: 'center',
        key: 'projectName'
    },

    {
        title: '开始投放日期',
        dataIndex: 'statDate',
        scopedSlots: { customRender: 'statDate' },
        align: 'center',
        key: 'statDate',
        sorter: () => {}
    },
    {
        title: '消耗',
        dataIndex: 'charge',
        scopedSlots: { customRender: 'charge' },
        align: 'center',
        key: 'charge',
        sorter: () => {}
    },
    {
        title: '封面曝光数',
        dataIndex: 'photoShow',
        scopedSlots: { customRender: 'photoShow' },
        align: 'center',
        key: 'photoShow',
        sorter: () => {}
    },
    {
        title: '封面点击数',
        dataIndex: 'photoClick',
        scopedSlots: { customRender: 'photoClick' },
        align: 'center',
        key: 'photoClick',
        sorter: () => {}
    },
    {
        title: '素材曝光数',
        dataIndex: 'aclick',
        scopedSlots: { customRender: 'aclick' },
        align: 'center',
        key: 'aclick',
        sorter: () => {}
    },
    {
        title: '行为数',
        dataIndex: 'bclick',
        scopedSlots: { customRender: 'bclick' },
        align: 'center',
        key: 'bclick',
        sorter: () => {}
    },
    {
        title: '封面点击率',
        dataIndex: 'photoClickRatio',
        scopedSlots: { customRender: 'photoClickRatio' },
        align: 'center',
        key: 'photoClickRatio',
        sorter: () => {}
    },
    {
        title: '行为率',
        dataIndex: 'actionRatio',
        scopedSlots: { customRender: 'actionRatio' },
        align: 'center',
        key: 'actionRatio',
        sorter: () => {}
    },
    {
        title: '平均千次封面曝光花费（元）',
        dataIndex: 'impression1kCost',
        scopedSlots: { customRender: 'impression1kCost' },
        align: 'center',
        key: 'impression1kCost',
        sorter: () => {}
    },
    {
        title: '平均封面点击单价（元）',
        dataIndex: 'photoClickCost',
        scopedSlots: { customRender: 'photoClickCost' },
        align: 'center',
        key: 'photoClickCost',
        sorter: () => {}
    },
    {
        title: '平均行为单价（元）',
        dataIndex: 'actionCost',
        scopedSlots: { customRender: 'actionCost' },
        align: 'center',
        key: 'actionCost',
        sorter: () => {}
    }
]

export default {
    components: {
        ACol,
        ARow,
        selectTable
    },

    data() {
        return {
            indexAll: 0,
            spinning: false,
            form: this.$form.createForm(this),
            priceForm: this.$form.createForm(this),
            exportloading: false,
            planId: '',
            shotId: '',
            clipId: '',
            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
                }
            },
            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: [],

            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,
            accountProjectList: [],
            accountProjectColumns: [
                {
                    title: '账户名称',
                    dataIndex: 'authName',
                    scopedSlots: { customRender: 'authName' },
                    align: 'center',
                    key: 'authName'
                },
                {
                    title: '账户状态',
                    dataIndex: 'authStatus',
                    scopedSlots: { customRender: 'authStatus' },
                    align: 'center',
                    key: 'authStatus'
                },
                {
                    title: '失败原因',
                    dataIndex: 'resultText',
                    customRender(t) {
                        if (t === 'success') {
                            return '-'
                        } else {
                            return t
                        }
                    },
                    align: 'center',
                    key: 'resultText'
                }
            ]
        }
    },
    methods: {
        moment,
        newCreat(id) {
            if (id) {
                window.open('/creat-config?id=' + id, '_blank')
            } else {
                window.open('/creat-config', '_blank')
            }
        },
        editPrice(item) {
            getAction('/kuaishouProjectStrategy/queryBidInfo', { id: item.id }).then(res => {
                if (res.success) {
                    this.modifyPriceVisible = true
                    this.modifyPriceDetail = { ...res.result, projectName: item.projectName, id: item.id }
                    console.log(this.modifyPriceDetail)
                    this.$nextTick(() => {
                        let cpaBid = ''
                        let changeBid = res.result.bidType === 2 ? res.result.bid : res.result.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 (res.result.deepConversionBid && res.result.deepConversionBid != '') {
                            if ((res.result.deepConversionBid + '').includes('/')) {
                                let bidArr = res.result.deepConversionBid.split('/')
                                for (let index = 0; index < bidArr.length; index++) {
                                    bidArr[index] = bidArr[index] / 1000
                                }
                                deepConversionBid = bidArr.join('/')
                            } else if ((res.result.deepConversionBid + '').includes('-')) {
                                let bidArr = res.result.deepConversionBid.split('-')
                                for (let index = 0; index < bidArr.length; index++) {
                                    bidArr[index] = bidArr[index] / 1000
                                }
                                deepConversionBid = bidArr.join('-')
                            } else {
                                deepConversionBid = res.result.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('/kuaishouProjectStrategy/updateProjectStrategy', {
                        ...params,
                        id: this.modifyPriceDetail.id
                    }).then(res => {
                        this.modifyPriceLoading = false
                        if (res.success) {
                            this.handleCancelPrice()
                        } 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)
        },
        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)
                }
            })
        },
        matchingAccount(item) {
            this.accountVisible = true
            this.accountProjectDetail = { id: item.id, projectName: item.projectName }
            getAction('/kuaishouProjectStrategy/queryMatchResult', { projectId: item.projectId, pageSize: 100 }).then(
                res => {
                    if (res.success) {
                        this.accountProjectList = res.result.list
                    }
                }
            )
        },
        getDataSource(current, pageSize) {
            // 切换分页时的回调，
            // 当在页面定义change事件时，切记要把此处的事件清除，因为这两个事件重叠了，可能到时候会导致一些莫名的bug
            this.ipagination.current = current
            this.ipagination.pageSize = pageSize
            const paramsData = this.form.getFieldsValue()
            this.handleGetTableList(paramsData)
        },
        onChangeStatus(text, rescord, type) {
            let status = text === 0 ? 1 : 0
            let url = ''
            let params = {}
            if (status === 0) {
                if (type === 'dataStatus') {
                    params.id = rescord.id
                    params.dataStatus = status
                    url = '/kuaishouProjectStrategy/updateProjectStrategy'
                } else if (type === 'projectStrategy') {
                    params.accountId = rescord.accountId
                    params.projectStrategy = status
                    url = '/kuaishouProjectStrategy/updateAccountStatus'
                }
                this.postDataAction(url, params).then(res => {
                    if (res.success) {
                        const paramsData = this.form.getFieldsValue()
                        this.handleGetTableList(paramsData)
                    } else {
                        this.$message.error(res.message)
                    }
                })
            } else {
                if (type === 'dataStatus') {
                    this.getAction('/kuaishouProjectStrategy/checkProjectisOpen', {
                        projectId: rescord.projectId
                    }).then(res => {
                        console.log(res)
                        if (res.success) {
                            if (res.result === 1) {
                                params.id = rescord.id
                                params.dataStatus = status
                                url = '/kuaishouProjectStrategy/updateProjectStrategy'
                                this.postDataAction(url, params).then(res => {
                                    if (res.success) {
                                        const paramsData = this.form.getFieldsValue()
                                        this.handleGetTableList(paramsData)
                                    } else {
                                        this.$message.error(res.message)
                                    }
                                })
                            } else {
                                this.$message.error('此项目有开启的配置，无法开启')
                                return
                            }
                        }
                    })
                } else if (type === 'projectStrategy') {
                    params.accountId = rescord.accountId
                    params.projectStrategy = status
                    url = '/kuaishouProjectStrategy/updateAccountStatus'
                    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.$refs.selectTable.keyValue = undefined
                this.$refs.selectTable.getData()
                this.projectIdAll = undefined
            }
            const paramsData = this.form.getFieldsValue()
            this.handleGetTableList(paramsData)
        },
        handleGetTableList(data) {
            let paramsData = {
                projectName: data.projectName,
                authName: data.authName,
                dataStatus: data.dataStatus == 'null' ? null : data.dataStatus,
                userId: data.userId,
                startTime:
                    data.timeRange && data.timeRange.length === 2
                        ? moment(data.timeRange[0]).format('YYYY-MM-DD')
                        : null,
                endTime:
                    data.timeRange && data.timeRange.length === 2
                        ? moment(data.timeRange[1]).format('YYYY-MM-DD')
                        : null,
                pageNo: this.ipagination.current,
                pageSize: this.ipagination.pageSize
            }
            if (data.target) {
                paramsData.sortCode = data.target
                if (data.order == 'descend') {
                    paramsData.sortType = 'DESC'
                } else {
                    paramsData.sortType = 'ASC'
                }
            } else {
                paramsData.sortCode = this.target
                paramsData.sortType = this.order == 'descend' ? 'DESC' : 'ASC'
            }
            if (this.tabKey === 1) {
                paramsData.projectId = this.projectIdAll
            } else {
                paramsData.projectId = this.projectId ? this.projectId.id : null
            }
            this.dataSource = []
            this.dataLoading = true
            postAction(this.url, paramsData)
                .then(result => {
                    this.dataLoading = false
                    if (result.code === 200) {
                        this.dataSource = result.result.pageInfo.list || []
                        if (result.result.total) {
                            this.dataSource.unshift(result.result.total)
                        }

                        this.ipagination.total = result.result.pageInfo.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'
            }
            // this.getNewPlan()
        },

        // 获取所有运营
        getAllOperator(key) {
            let url = '/sys/user/getAllUserListV1'
            this.designList = []

            getAction(url, {}).then(res => {
                if (res.success) {
                    this.designList = res.result
                }
            })
        },

        // 获取展示数据
        getNewPlan() {
            let url = ''
            if (this.tabKey == 1) {
                // 头条
                url = '/ctop/bytedanceVideoEtlInfo/list'
            } else {
                // 快手

                url = '/ctop/kuaishouVideoEtlInfo/list'
            }

            this.loading = true

            getAction(url, {
                type: this.value,
                clipId: this.clipId == '' ? null : this.clipId,
                shotId: this.shotId == '' ? null : this.shotId,
                planId: this.planId == '' ? null : this.planId,
                startDate: this.dateRange[0].format('YYYY-MM-DD'),
                endDate: this.dateRange[1].format('YYYY-MM-DD'),
                pageSize: this.ipagination.pageSize,
                pageNo: this.ipagination.current
            }).then(res => {
                console.log(res)
                this.loading = false

                if (res.success) {
                    if (res.result) {
                        this.dataSource = res.result.records
                        this.ipagination.total = res.result.total
                    }
                }
            })
        },

        // 查询按钮
        search() {
            // if(this.accountId || this.operate){
            //     this.echartSpinning=true;
            //     this.getNewPlan()
            // }else{
            //     this.$message.error('请选择具体账户或者运营')
            // }
            this.ipagination.current = 1
            this.getNewPlan()
        }
    },
    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)
        this.getAllOperator()
    },
    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>
