<template>
    <div class="account-config-content">
        <div class="control-con-header">
            <a-form
                class="grid-form"
                layout="inline"
                :form="form"
                hide-required-mark
                @submit="handleQueryList"
            >
                <a-row class="grid-form-options">
                    <a-form-item
                        class="grid-form-item"
                        label="账户"
                        :colon="false"
                    >
                        <acount-search class="acount-search-class" :appId.sync="acountId" :multiple="false" request="1,3"></acount-search>
                    </a-form-item>
                    <a-form-item class="form-handle-btn">
                        <a-button type="default" class="reset-class" @click="handleResetList">重置</a-button>
                        <a-button type="primary" html-type="submit">查询</a-button>
                    </a-form-item>
                </a-row>
            </a-form>
            <a-button type="primary" class="upload-person" @click="handleAddAccountConfig">新建账户配置</a-button>
        </div>
        <div class="control-con-table">
            <a-table
                ref="table"
                size="middle"
                bordered
                :columns="columns"
                :dataSource="dataSource"
                :pagination="false"
            >
                <span slot="customTitle">
                    花费(元)
                    <a-tooltip placement="top">
                        <template slot="title">
                            <span>当日花费</span>
                        </template>
                        <a-icon type="smile-o"/>
                    </a-tooltip>
                </span>
                <span slot="acountRelax" slot-scope="text, record">
                    <a-switch :checked="text === 0" @change="handleSwitchChang($event, record)"/>
                </span>
                <span slot="action" slot-scope="text, record">
                    <a @click="handleEdit(record)">编辑</a>
                    <a-divider type="vertical"/>
                    <a @click="handleListDelete(record)">删除</a>
                    <a-divider type="vertical"/>
                    <a-popover v-model="record.visible" trigger="click">
                        <template slot="content">
                            <div><a-input v-model="modContent" placeholder="请输入" style="width: 140px;"/></div>
                            <div style="margin-top: 10px;">
                                <a-button
                                    size="small"
                                    type="primary"
                                    style="margin-left: 15px;margin-right: 15px;"
                                    @click="handlePopoverSure(record, 'mod')"
                                >
                                    确定
                                </a-button>
                                <a-button size="small" @click="handleModPopover(record)">取消</a-button>
                            </div>
                        </template>
                        <a>修改出价</a>
                    </a-popover>
                    <a-divider type="vertical"/>
                    <a-popover v-model="record.show" trigger="click">
                        <template slot="content">
                            <div><a-input v-model="budgetContent" placeholder="请输入" style="width: 140px;"/></div>
                            <div style="margin-top: 10px;">
                                <a-button
                                    size="small"
                                    type="primary"
                                    style="margin-left: 15px;margin-right: 15px;"
                                    @click="handlePopoverSure(record, 'budget')"
                                >
                                    确定
                                </a-button>
                                <a-button size="small" @click="handleBudgetPopover(record)">取消</a-button>
                            </div>
                        </template>
                        <a>修改预算</a>
                    </a-popover>
                </span>
            </a-table>
            <a-pagination
                class="pagin-table-class"
                :total="totalAll"
                :show-total="total => `共 ${totalAll} 条`"
                size="small"
                show-size-changer
                show-quick-jumper
                @change="onShowSizeChange"
                @showSizeChange="onShowSizeChange"
            />
        </div>
    </div>
</template>
<script>
import AcountSearch from '@/views/modules/Statistics/components/Treeselect.vue';

import {getAction, putAction, deleteAction} from '@/api/manage';
import {mapGetters} from 'vuex';
import {urlAcount} from './account-config-server.js';

export default {
    name: 'account-config',
    components: {
        AcountSearch
    },
    data() {
        return {
            modContent: '',
            budgetContent: '',
            acountId: undefined, // 搜索的账户ID
            totalAll: 0,
            tablePag: {
                page: 1,
                size: 10
            },
            dataSource: [],
            columns: [
                {
                    title: '开关',
                    align: 'center',
                    dataIndex: 'status',
                    scopedSlots: {customRender: 'acountRelax'}
                },
                {
                    title: '广告账户名称',
                    align: 'center',
                    dataIndex: 'accountId_dictText'
                },
                {
                    title: '账户ID',
                    align: 'center',
                    dataIndex: 'accountId'
                },
                {
                    title: '创建时间',
                    dataIndex: 'createTime',
                    align: 'center'
                },
                {
                    title: '账户余额',
                    dataIndex: 'validBalance',
                    align: 'center'
                },
                {
                    title: '账户日预算量（元）',
                    dataIndex: 'adBudget',
                    align: 'center'
                },
                {
                    title: '出价（元）',
                    dataIndex: 'adCpaBid',
                    align: 'center'
                },
                {
                    align: 'center',
                    dataIndex: 'cost',
                    slots: {title: 'customTitle'}
                },
                {
                    title: '操作',
                    dataIndex: 'action',
                    align: 'center',
                    scopedSlots: {customRender: 'action'}
                }
            ]
        };
    },
    created() {
        this.form = this.$form.createForm(this);
    },
    mounted() {
        this.handleInitTable();
    },
    methods: {
        ...mapGetters(['nickname', 'avatar', 'userInfo']),
        handlePopoverSure(record, type) {
            const defaultList = {
                accountId: record.accountId,
                bid: this.modContent,
                budget: this.budgetContent,
                adId: record.adId ? record.adId : '',
                id: record.id
            };
            let paramsData = new FormData();
            if (type === 'mod') {
                record.visible = false;
                this.modContent = '';
                paramsData.append('accountId', defaultList.accountId);
                paramsData.append('adId', defaultList.adId);
                paramsData.append('type', 1);
                paramsData.append('bId', defaultList.bid);
                paramsData.append('id', defaultList.id);
            }
            else if (type === 'budget') {
                if (Number(defaultList.budget) >= record.adBudget && Number(defaultList.budget) < (record.adBudget + 100)) {
                    this.$message.error('单次修改预算幅度, 不能低于100.0元');
                    return;
                }
                if (Number(defaultList.budget) <= record.adBudget && Number(defaultList.budget) > (record.adBudget - 100)) {
                    this.$message.error('单次修改预算幅度, 不能低于100.0元');
                    return;
                }
                record.show = false;
                this.budgetContent = '';
                paramsData.append('accountId', defaultList.accountId);
                paramsData.append('adId', defaultList.adId);
                paramsData.append('type', 2);
                paramsData.append('budget', defaultList.budget);
                paramsData.append('id', defaultList.id);
            }
            this.handlePopoverChange(paramsData);
        },
        handlePopoverChange(data) {
            putAction(urlAcount + '/bytedance-api/advertiser/aiBytedanceAdvertiserStrategy/updStaOrCpaOrBudgetById', data).then(result => {
                if (result.code === 0) {
                    this.$message.success(result.message);
                    this.handleInitTable();
                }
                else {
                    this.$message.error(result.message);
                }
            }).catch(error => {
                console.log(error, 'eeee');
            });
        },
        handleResetList() {
            this.acountId = '';
            this.handleInitTable();
        },
        handleInitTable() {
            const paramsData = {
                accountId: this.acountId,
                logingUserId: this.userInfo().id,
                pageNo: this.tablePag.page,
                pageSize: this.tablePag.size
            };
            getAction(urlAcount + '/bytedance-api/advertiser/aiBytedanceAdvertiserStrategy/list', paramsData).then(result => {
                if (result.code === 0) {
                    result.result.records.forEach(item => {
                        item.show = false;
                        item.visible = false;
                    });
                    this.dataSource = result.result.records;
                    this.totalAll = result.result.total;
                }
                else {
                    this.$message.error(result.message);
                }
            }).catch(error => {
                console.log(error, 'eeee');
            });
        },
        handleListDelete(data) {
            let that = this;
            this.$confirm({
                title: '删除提示',
                content: '确定要删除这一条吗？',
                onOk() {
                    deleteAction(urlAcount + '/bytedance-api/advertiser/aiBytedanceAdvertiserStrategy/delete', {id: data.id}).then(result => {
                        if (result.code === 0) {
                            that.handleInitTable();
                            that.$message.success('删除成功');
                        }
                        else {
                            that.$message.error(result.message);
                        }
                    }).catch(error => {
                        console.log(error, 'eeee');
                    });
                }
            });
        },
        handleBudgetPopover(record) {
            record.show = false;
        },
        handleModPopover(record) {
            record.visible = false;
        },
        handleQueryList(event) {
            event.preventDefault();
            this.handleInitTable();
        },
        onShowSizeChange(current, pageSize) {
            this.tablePag = {
                page: current,
                size: pageSize
            };
            this.handleInitTable();
        },
        handleSwitchChang(checked, data) {
            const paramsData = {
                id: data.id,
                state: checked ? 0 : 1,
                accountId: data.accountId
            };
            const forDate = new FormData();
            forDate.append('id', paramsData.id);
            forDate.append('state', paramsData.state);
            forDate.append('accountId', paramsData.accountId);
            putAction(urlAcount + '/bytedance-api/advertiser/aiBytedanceAdvertiserStrategy/updStaById', forDate).then(result => {
                if (result.code === 0) {
                    this.$message.success(result.message);
                    this.handleInitTable();
                }
                else {
                    this.$message.error(result.message);
                }
            }).catch(error => {
                console.log(error, 'eeee');
            });
        },
        handleEdit(data) {
            // TODO 切换路由时候，及时删除上一次相同路由
            let params = {
                accountModal: 'edit',
                id: data.id
            };
            localStorage.setItem('queryList', JSON.stringify(params));
            this.$router.push('/account-config/components/configuration-modal');
        },
        handleAddAccountConfig() {
            let params = {
                accountModal: 'add'
            };
            localStorage.setItem('queryList', JSON.stringify(params));
            this.$router.push('/account-config/components/configuration-modal');
        }
    }
};
</script>
<style lang="less" scoped>
    @import "account-config";
</style>