<style lang="scss" scoped>
::v-deep.vue-treeselect__control {
    line-height: 36px !important;
}
::v-deep .ant-collapse-item,
::v-deep.ant-collapse-content {
    overflow: inherit !important;
}
.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>
@import 'channelManage';
::v-deep .ant-tag .anticon-close {
    font-size: 16px;
    color: red;
}
</style>
<template>
    <div class="channelManage config-project">
        <a-card>
            <div class="table-page-search-wrapper">
                <a-tag closable @close="closeLog" style="margin-bottom:15px;font-size: 16px;">
                    {{ accountName }}
                </a-tag>
                <a-form layout="inline" :form="form" hide-required-mark :selfUpdate="true" @submit="handleQueryList">
                    <a-row :gutter="24">
                        <a-col :md="8" :sm="8" :xxl="6">
                            <a-form-item label="渠道号名称">
                                <a-input placeholder="请输入渠道号名称" v-decorator="['channelName']"></a-input>
                            </a-form-item>
                        </a-col>
                        <a-col :md="8" :sm="8" :xxl="6">
                            <a-form-item label="渠道号">
                                <a-input placeholder="请输入渠道号" v-decorator="['channelCode']"></a-input>
                            </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>

                <!-- <a-row :gutter="24">
                    <a-col :md="8" :sm="8" :xxl="6">
                        <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
                            <a-button type="primary" @click="visibleAddItem = true">添加单品</a-button>
                            <a-button
                                type="primary"
                                @click="itemChannel"
                                class="middle-button"
                                :disabled="selectedRowKeys.length == 0"
                                >关联单品</a-button
                            >
                        </span>
                    </a-col>
                </a-row> -->
            </div>
        </a-card>

        <a-row style="margin-bottom:15px;margin-top:12px">
            <a-col :span="24">
                <!-- {
                            selectedRowKeys: selectedRowKeys,
                            onChange: onSelectChange
                        } -->
                <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"
                        rowKey="id"
                        :scroll="{ x: 3000 }"
                        :rowSelection="rowSelection"
                    >
                        <span slot="items" slot-scope="text, record">
                            {{
                                text.length > 0
                                    ? text
                                          .map(i => {
                                              if (i) {
                                                  return i.itemName
                                              }
                                          })
                                          .join()
                                    : '-'
                            }}
                        </span>
                        <span slot="channelState" slot-scope="text, record">
                            <a-switch :checked="text === 1" @change="handleSwitchChang($event, record)" />
                        </span>
                        <span slot="action" slot-scope="text, records">
                            <a @click="addNewChannel(records)" :disabled="!accountId">查看详情</a>
                        </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="渠道号使用明细"
            :width="800"
            ref="modal"
            :visible="visibleChannel"
            :footer="null"
            @cancel="visibleChannel = false"
        >
            <div style="width:100%;display:flex;margin-bottom:15px;font-weight:700;font-size:16px">
                <span style="min-width:250px;white-space:nowrap;">项目：{{ projectName }}</span>
                <span>使用层级：{{ usageLevel == 'account' ? '账户' : usageLevel == 'plan' ? '计划' : '组' }}</span>
            </div>
            <a-table
                :columns="detailColumns"
                :dataSource="dataDetailSource"
                :pagination="ipaginationDetail"
                :loading="dataDetailLoading"
                bordered
                size="middle"
                style="word-break: break-all;font-size:16px;font-weight:600"
                id="outTable"
                ref="accountTable"
                rowKey="accountId"
            >
            </a-table>
        </a-modal>

        <a-modal
            title="关联单品"
            :width="800"
            ref="modal"
            :visible="visibleItem"
            @cancel="visibleItem = false"
            @ok="handleOkItem"
        >
            <a-form-model ref="itemForm" :model="itemForm" :rules="rules" v-bind="formItemLayout">
                <a-collapse accordion v-model="activeKey" ref="collapse">
                    <template v-for="(item, index) in itemForm.items">
                        <a-collapse-panel
                            :forceRender="true"
                            :header="item.channelName + '(' + item.channelCode + ')'"
                            style="background: #f9f9fa;border-radius: 4px;margin-bottom:15px;overflow: hidden;border: 1px solid #d9d9d9;"
                        >
                            <span slot="extra">
                                <a-popconfirm :title="`确定删除吗？`" @confirm="deleteRule($event, item, index)">
                                    <a-icon type="delete" @click="deleteIcon($event)" />
                                </a-popconfirm>
                            </span>
                            <a-form-model-item label="产品" ref="projectId">
                                <!-- <a-input v-model="item.projectId" placeholder="请输入规则名称" /> -->
                                {{ item.productName }}
                            </a-form-model-item>
                            <a-form-model-item label="项目" ref="keyword">
                                {{ item.projectName }}
                            </a-form-model-item>
                            <a-form-model-item label="渠道号" ref="channelCode">
                                {{ item.channelCode }}
                            </a-form-model-item>
                            <a-form-model-item label="渠道号名称" ref="channelName">
                                {{ item.channelName }}
                            </a-form-model-item>
                            <a-form-model-item
                                label="关联单品名称"
                                ref="projectId"
                                :prop="'items.' + index + '.id'"
                                :rules="[{ required: true, message: '请选择单品', trigger: 'blur' }]"
                            >
                                <a-select allowClear v-model="item.id">
                                    <a-select-option :value="item.id" v-for="(item, index) in item.itemList">{{
                                        item.itemName
                                    }}</a-select-option>
                                </a-select>
                            </a-form-model-item>
                        </a-collapse-panel>
                    </template>
                </a-collapse>
            </a-form-model>
        </a-modal>

        <a-modal
            title="添加单品"
            :width="800"
            ref="modal"
            :visible="visibleAddItem"
            @cancel="visibleAddItem = false"
            @ok="handleOk"
            :confirmLoading="confirmLoading"
        >
            <a-button type="primary" @click="addOneItem" style="margin-bottom:10px">添加单品信息</a-button>
            <a-form-model ref="ruleForm" :model="addItemForm" :rules="rules" v-bind="formItemLayout">
                <a-collapse accordion v-model="activeKey" ref="collapse" v-if="visibleAddItem">
                    <template v-for="(item, index) in addItemForm.items">
                        <a-collapse-panel
                            :forceRender="true"
                            :header="item.itemName"
                            style="background: #f9f9fa;border-radius: 4px;margin-bottom:15px;overflow: hidden;border: 1px solid #d9d9d9;"
                        >
                            <span slot="extra">
                                <a-popconfirm :title="`确定删除吗？`" @confirm="deleteRule($event, item, index)">
                                    <a-icon type="delete" @click="deleteIcon($event)" />
                                </a-popconfirm>
                            </span>
                            <a-form-model-item
                                label="项目"
                                ref="projectId"
                                :prop="'items.' + index + '.projectId'"
                                :rules="[{ required: true, message: '请选择项目', trigger: 'change' }]"
                            >
                                <!-- <a-input v-model="item.projectId" placeholder="请输入规则名称" /> -->
                                <Treeselect v-model="item.projectId" style="width:100%" />
                            </a-form-model-item>
                            <a-form-model-item
                                label="素材关键字"
                                ref="keyword"
                                :prop="'items.' + index + '.keyword'"
                                :rules="[
                                    { required: true, message: '请填写素材关键字', trigger: 'blur' },
                                    { min: 1, max: 15, message: '长度不得小于1,最大长度为15', trigger: 'blur' }
                                ]"
                            >
                                <a-input v-model="item.keyword" placeholder="请输入素材关键字" />
                            </a-form-model-item>
                            <a-form-model-item
                                label="单品名称"
                                ref="itemName"
                                :prop="'items.' + index + '.itemName'"
                                :rules="[
                                    { required: true, message: '请填写单品名称', trigger: 'blur' },
                                    { min: 1, max: 10, message: '长度不得小于1,最大长度为10', trigger: 'blur' }
                                ]"
                            >
                                <a-input v-model="item.itemName" placeholder="请输入单品名称" />
                            </a-form-model-item>
                        </a-collapse-panel>
                    </template>
                </a-collapse>
            </a-form-model>
        </a-modal>
    </div>
</template>

<script>
import ARow from 'ant-design-vue/es/grid/Row'
import ACol from 'ant-design-vue/es/grid/Col'
import moment from 'moment'
import { getKsAccountReport, getKsDetail, getReportList } from '@api/video.js'
import { getAction, postAction, downFile, downFilePost } from '@/api/manage'
import selectTable from '@/views/modules/material/comment/selectTable.vue'
import selectTableProject from '@/views/modules/Statistics/components/selectPagination.vue'
import qs from 'qs'
import Treeselect from './components/treeSelectProject.vue'
let TTcolumns = [
    {
        title: '开关',
        dataIndex: 'channelState',
        scopedSlots: { customRender: 'channelState' },
        align: 'center',
        key: 'channelState'
    },
    {
        title: '生成方式（来源）',
        dataIndex: 'createType',
        align: 'center',
        key: 'createType',
        customRender: function(text) {
            if (text == 1) {
                return '系统生成'
            } else if (text == 2) {
                return '表格导入'
            } else if (text == 3) {
                return '自定义填写'
            } else {
                return text
            }
        }
    },

    {
        title: '创建时间',
        dataIndex: 'stateDate',
        scopedSlots: { customRender: 'stateDate' },
        align: 'center',
        key: 'stateDate'
    },
    {
        title: '渠道号',
        dataIndex: 'channelCode',
        scopedSlots: { customRender: 'channelCode' },
        align: 'center',
        key: 'channelCode'
    },

    {
        title: '渠道号名称',
        dataIndex: 'channelName',
        scopedSlots: { customRender: 'channelName' },
        align: 'center',
        key: 'channelName'
    },
    {
        title: '下载链接',
        dataIndex: 'url',
        customRender: function(text) {
            if (text) {
                return text
            } else {
                return '-'
            }
        },
        align: 'center',
        key: 'url',
        width: 300
    },
    {
        title: '调起链接',
        dataIndex: 'schemaUri',
        customRender: function(text) {
            if (text) {
                return text
            } else {
                return '-'
            }
        },
        align: 'center',
        key: 'schemaUri',
        width: 300
    },
    {
        title: '第三方点击监测链接',
        dataIndex: 'clickTrackUrl',
        customRender: function(text) {
            if (text) {
                return text
            } else {
                return '-'
            }
        },
        align: 'center',
        key: 'clickTrackUrl',
        width: 300
    },
    {
        title: '第三方actionBar监测链接',
        dataIndex: 'actionbarClickUrl',
        customRender: function(text) {
            if (text) {
                return text
            } else {
                return '-'
            }
        },
        align: 'center',
        key: 'actionbarClickUrl',
        width: 300
    },

    {
        title: '是否关联单品',
        dataIndex: 'isHaveItem',
        customRender: function(text) {
            if (text == 1) {
                return '是'
            } else if (text == 0) {
                return '否'
            } else {
                return text
            }
        },
        align: 'center',
        key: 'isHaveItem'
    },
    {
        title: '关联单品名称',
        dataIndex: 'items',
        scopedSlots: { customRender: 'items' },
        align: 'center',
        key: 'items'
    },
    {
        title: '使用层级',
        dataIndex: 'usageLevel',
        customRender: function(text) {
            if (text == 'account') {
                return '账户'
            } else if (text == 'plan') {
                return '计划'
            } else if (text == 'group') {
                return '组'
            } else {
                return text
            }
        },
        align: 'center',
        key: 'usageLevel'
    },
    // {
    //     title: '使用次数',
    //     dataIndex: 'usageTimes',
    //     scopedSlots: { customRender: 'usageTimes' },
    //     align: 'center',
    //     key: 'usageTimes'
    // },
    {
        title: '是否循环',
        dataIndex: 'isCycle',
        customRender: function(text) {
            if (text == 1) {
                return '是'
            } else if (text == 0) {
                return '否'
            } else {
                return text
            }
        },
        align: 'center',
        key: 'isCycle'
    },
    // {
    //     title: '循环次数',
    //     dataIndex: 'cycleTimes',
    //     scopedSlots: { customRender: 'cycleTimes' },
    //     align: 'center',
    //     key: 'cycleTimes'
    // },
    // {
    //     title: '当前已循环次数',
    //     dataIndex: 'haveCycleTimes',
    //     scopedSlots: { customRender: 'haveCycleTimes' },
    //     align: 'center',
    //     key: 'haveCycleTimes'
    // },
    {
        title: '使用明细',
        dataIndex: 'action',
        scopedSlots: { customRender: 'action' },
        align: 'center',
        key: 'action'
    }
]

let detailColumns = [
    // {
    //     title: '渠道号',
    //     dataIndex: 'channelCode',
    //     scopedSlots: { customRender: 'channelCode' },
    //     align: 'center',
    //     key: 'channelCode'
    // },
    {
        title: '渠道号名称',
        dataIndex: 'channelName',
        scopedSlots: { customRender: 'channelName' },
        align: 'center',
        key: 'channelName'
    },
    {
        title: '使用范围',
        dataIndex: 'usageRange',
        customRender: function(text) {
            if (text == 1) {
                return '账户'
            } else if (text == 2) {
                return '项目'
            } else {
                return text
            }
        },
        align: 'center',
        key: 'usageRange'
    },
    // {
    //     title: '项目名称',
    //     dataIndex: 'projectName',
    //     scopedSlots: { customRender: 'projectName' },
    //     align: 'center',
    //     key: 'projectName'
    // },
    {
        title: '账户名称',
        dataIndex: 'authName',
        scopedSlots: { customRender: 'authName' },
        align: 'center',
        key: 'authName'
    },
    {
        title: '账户ID',
        dataIndex: 'accountId',
        scopedSlots: { customRender: 'accountId' },
        align: 'center',
        key: 'accountId'
    },
    {
        title: '创建广告计划ID',
        dataIndex: 'campaignId',
        scopedSlots: { customRender: 'campaignId' },
        align: 'center',
        key: 'campaignId'
    },
    {
        title: '创建广告组ID',
        dataIndex: 'unitId',
        scopedSlots: { customRender: 'unitId' },
        align: 'center',
        key: 'unitId'
    },
    {
        title: '创建时间',
        dataIndex: 'createTime',
        scopedSlots: { customRender: 'createTime' },
        align: 'center',
        key: 'createTime'
    }
]

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

    data() {
        return {
            productId: '',
            projectId: '',
            accountId: '',
            accountName: '',
            projectName: '',
            selectedRowKeys: [],
            visibleChannel: false,
            visibleAddItem: false,
            visibleItem: false,
            channelCode: '',
            usageLevel: '',
            channelType: 'a',
            createType: 1,
            indexAll: 0,
            spinning: false,
            form: this.$form.createForm(this),
            activeKey: '0',
            addItemForm: {
                items: [{ projectId: '', keyWord: '', itemName: '默认名称-单品1' }]
            },
            itemForm: {
                items: [{ project_Id: '', channelName: '', channelCode: '', projectName: '', productName: '' }]
            },
            confirmLoading: false,
            rules: {},
            formItemLayout: {
                labelCol: { span: 4 },
                wrapperCol: { span: 20 }
            },
            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
                }
            },
            ipaginationDetail: {
                current: 1,
                pageSize: 10,
                //   pageSizeOptions: ['10', '20', '30'],
                showTotal: (total, range) => {
                    return range[0] + '-' + range[1] + ' 共' + total + '条'
                },
                showQuickJumper: true,
                total: 0,
                onChange: (current, pageSize) => {
                    // 切换分页时的回调，
                    // 当在页面定义change事件时，切记要把此处的事件清除，因为这两个事件重叠了，可能到时候会导致一些莫名的bug
                    this.ipaginationDetail.current = current
                    this.ipaginationDetail.pageSize = pageSize
                    this.dataDetailLoading = true
                    var params = {}
                    params.accountId = localStorage.getItem('channelInfoAccountId')
                        ? JSON.parse(localStorage.getItem('channelInfoAccountId')).accountId
                        : null
                    params.projectId = localStorage.getItem('channelInfoProjectId')
                        ? localStorage.getItem('channelInfoProjectId')
                        : null
                    params.channelCode = this.channelCode
                    params.pageNo = this.ipaginationDetail.current
                    params.pageSize = this.ipaginationDetail.pageSize
                    getAction('/channel/channelNumberUsageDetailsList', params).then(res => {
                        this.dataDetailLoading = false
                        if (res.success) {
                            this.dataDetailSource = res.result.list || []
                            this.ipaginationDetail.total = res.result.total || 0
                        }
                    })
                }
            },
            value: 'valid',
            KSaccountList: [],
            TTaccountList: [],

            KSdesignList: [],
            TTdesignList: [],

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

            type: 3,

            operate: '',
            designList: [],

            tabKey: 1,

            loading: false,
            columns: [...TTcolumns],
            detailColumns: [...detailColumns],
            dataSource: [],
            dataDetailSource: [],
            dataDetailLoading: false,
            tableTab: 1,

            newPlan: 0,
            effectPlan: 0,

            openOptions: false,

            target: 'createTime',
            order: 'descend',
            dataLoading: false,
            url: '/channel/channelNumberDetails',
            modifyPriceVisible: false,
            modifyPriceLoading: false,
            modifyPriceDetail: null,
            accountVisible: false,
            againLoading: false,
            accountProjectDetail: null,
            accountProjectList: []
        }
    },
    components: {
        Treeselect
    },
    methods: {
        moment,
        closeLog() {
            this.$router.replace('/autoLaunch/channelAdmin')
            this.$bus.$emit('remove', '/autoLaunch/channelDetailList')
        },
        deleteIcon(event) {
            event.stopPropagation()
        },
        deleteRule(event, item, index) {
            event.stopPropagation()
            this.addItemForm.items.splice(index, 1)
        },
        addOneItem() {
            this.addItemForm.items.push({
                projectId: '',
                keyWord: '',
                itemName: '默认名称-单品' + (this.addItemForm.items.length + 1)
            })
        },
        onSelectChange(selectedRowKeys, selectionRows) {
            this.selectedRowKeys = selectedRowKeys
            // this.selectionRows = selectionRows
        },
        handleSwitchChang(checked, data) {
            const paramsData = {
                id: data.id,
                channelState: checked ? 1 : 0
            }
            getAction('/channel/updateChannelState', paramsData)
                .then(result => {
                    if (result.code === 200) {
                        const paramsData = this.form.getFieldsValue()
                        this.handleGetTableList(paramsData)
                    } else {
                        this.$message.error(result.message)
                    }
                })
                .catch(error => {
                    console.log(error, 'eeee')
                })
        },
        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()
            }
        },
        itemChannel() {
            postAction('/channel/channelNumberBindingItemInfo', { ids: this.selectedRowKeys }).then(res => {
                if (res.success) {
                    this.itemForm.items = res.result.map((item, index) => {
                        return {
                            ...item,
                            channelId: item.id,
                            id: '',
                            itemList: this.getItemList(item.project_Id, item.itemList, index)
                        }
                    })
                    this.visibleItem = true
                }
            })
        },
        getItemList(projectId, list, index) {
            getAction('/channelItem/queryAllChannelItemByProjectId', { projectId }).then(res => {
                if (res.success) {
                    this.itemForm.items[index].itemList = res.result
                }
            })
        },
        handleOkItem() {
            this.$refs.itemForm.validate(valid => {
                if (valid) {
                    this.confirmLoading = true
                    let params = this.itemForm.items.map(item => {
                        return {
                            id: item.id,
                            channelId: item.channelId
                        }
                    })
                    postAction('/channelItem/channelBindingItem', params).then(res => {
                        this.confirmLoading = false
                        if (res.success) {
                            this.visibleItem = false
                            this.itemForm.items = []
                            this.handleResetForm()
                            this.selectedRowKeys = []
                            this.activeKey = '0'
                        } else {
                            this.$message.error(res.message)
                        }
                    })
                }
            })
        },
        handleOk() {
            this.$refs.ruleForm.validate(valid => {
                if (valid) {
                    this.confirmLoading = true
                    postAction('/channelItem/addChannelItem', this.addItemForm.items).then(res => {
                        this.confirmLoading = false
                        if (res.success) {
                            this.visibleAddItem = false
                            this.addItemForm.items = [{ projectId: '', keyWord: '', itemName: '默认名称-单品1' }]
                            this.handleResetForm()
                        } else {
                            this.$message.error(res.message)
                        }
                    })
                }
            })
        },
        handleCancel() {
            this.visibleChannel = false
        },
        addNewChannel(item) {
            this.visibleChannel = true
            this.dataDetailLoading = true
            this.channelCode = item.channelCode
            this.usageLevel = item.usageLevel
            //      dataIndex: 'usageLevel',
            // customRender: function(text) {
            //     if (text == 'account') {
            //         return '账户'
            //     } else if (text == 'plan') {
            //         return '计划'
            //     } else if (text == 'group') {
            //         return '组'
            //     } else {
            //         return text
            //     }
            // },
            var params = {}
            params.accountId = JSON.parse(localStorage.getItem('channelInfoAccountId')).accountId
            params.channelCode = item.channelCode
            params.pageNo = this.ipaginationDetail.current
            params.pageSize = this.ipaginationDetail.pageSize
            getAction('/channel/channelNumberUsageDetailsList', params).then(res => {
                this.dataDetailLoading = false
                if (res.success) {
                    this.dataDetailSource = res.result.list || []
                    this.ipaginationDetail.total = res.result.total || 0
                }
            })
        },
        getDataSource(current, pageSize) {
            // 切换分页时的回调，
            // 当在页面定义change事件时，切记要把此处的事件清除，因为这两个事件重叠了，可能到时候会导致一些莫名的bug
            this.ipagination.current = current
            this.ipagination.pageSize = pageSize
            const paramsData = this.form.getFieldsValue()
            this.handleGetTableList(paramsData)
        },
        handleQueryList(event) {
            this.ipagination.current = 1
            event.preventDefault()
            const paramsData = this.form.getFieldsValue()
            this.handleGetTableList(paramsData)
        },
        handleResetForm() {
            this.ipagination.current = 1
            this.form.resetFields()
            const paramsData = this.form.getFieldsValue()
            this.handleGetTableList(paramsData)
        },
        handleGetTableList(data) {
            let paramsData = {
                channelCode: data.channelCode,
                channelName: data.channelName,
                accountId: localStorage.getItem('channelInfoAccountId')
                    ? JSON.parse(localStorage.getItem('channelInfoAccountId')).accountId
                    : null,
                projectId: localStorage.getItem('channelInfoProjectId')
                    ? localStorage.getItem('channelInfoProjectId')
                    : null,
                pageNo: this.ipagination.current,
                pageSize: this.ipagination.pageSize
            }
            this.dataSource = []
            this.dataLoading = true
            this.getAction(this.url, paramsData)
                .then(result => {
                    this.dataLoading = false
                    if (result.code === 200) {
                        this.dataSource = result.result.list || []
                        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)
        },
        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
        },
        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'
                })
            }
        },

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

            getAction(url, {}).then(res => {
                if (res.success) {
                    this.designList = res.result
                }
            })
        }
    },
    watch: {
        productId: function(n, o) {
            if (n != '') {
                this.$refs.selectTableProject.keyValue = ''
                this.$refs.selectTableProject.getData(n)
            }
        },
        visibleAddItem: function(n, o) {
            if (!n) {
                this.addItemForm = {
                    items: [{ projectId: '', keyWord: '', itemName: '默认名称-单品1' }]
                }
                this.addItemForm.items[0].projectId = ''
            }
        }
    },
    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
        },
        rowSelection() {
            return {
                onChange: (selectedRowKeys, selectedRows) => {
                    this.selectedRowKeys = selectedRowKeys
                },
                selectedRowKeys: this.selectedRowKeys,
                getCheckboxProps: record => ({
                    props: {
                        disabled: record.isHaveItem === 0
                    }
                })
            }
        }
    },
    mounted() {
        const paramsData = this.form.getFieldsValue()
        this.handleGetTableList(paramsData)
        if (localStorage.getItem('channelInfoAccountId')) {
            this.accountId = JSON.parse(localStorage.getItem('channelInfoAccountId')).accountId
            this.accountName = JSON.parse(localStorage.getItem('channelInfoAccountId')).accountName
            this.projectName = JSON.parse(localStorage.getItem('channelInfoAccountId')).projectName
        } else {
            this.accountId = null
        }
        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>
