<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 @click="handleUpdateMod(record)">修改出价</a>
                    <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>
        <a-modal
            title="修改出价"
            v-if="modeVisible"
            :visible="modeVisible"
            dialog-class="mode-modal-class"
            @ok="handleModeSure"
            @cancel="handleModeCancel"
        >
            <div>
                <a-form-model
                    ref="ruleForm"
                    :model="configForm"
                    :rules="rules"
                    :label-col="labelCol"
                    :wrapper-col="wrapperCol"
                >
                    <a-form-model-item v-if="updateModTxt.adBidCreateType === 'FIX'" label="目标转化出价" prop="adCpaBid">
                        <a-input-number
                            class="common-input"
                            v-model="configForm.adCpaBid"
                            :min="0.1"
                            :step="0.01"
                            placeholder="请输入"
                        />
                    </a-form-model-item>
                    <div v-if="updateModTxt.adBidCreateType === 'RAND'">
                        <a-form-model-item label="目标转化出价范围"
                        class="dp-link-start" prop="adMinBid">
                            <a-input-number
                                class="common-input"
                                v-model="configForm.adMinBid"
                                :min="0.1"
                                :max="10000"
                                placeholder="请输入最小值"
                            />
                        </a-form-model-item>
                        <span class="icon-span">~</span>
                        <a-form-model-item class="dp-link-end" prop="adMaxBid">
                            <a-input-number
                                class="common-input"
                                v-model="configForm.adMaxBid"
                                :min="0.1"
                                :max="10000"
                                placeholder="请输入最大值"
                            />
                        </a-form-model-item>
                    </div>
                    <div v-if="updateModTxt.adBidCreateType === 'STEP'">
                        <a-form-model-item label="目标转化出价范围" class="dp-link-start" prop="adMinBid">
                            <a-input-number
                                class="common-input"
                                v-model="configForm.adMinBid"
                                :min="0.1"
                                :max="10000"
                                placeholder="请输入最小值"
                            />
                        </a-form-model-item>
                        <span class="icon-span">~</span>
                        <a-form-model-item class="dp-link-end" prop="adMaxBid">
                            <a-input-number
                                class="common-input"
                                v-model="configForm.adMaxBid"
                                :min="0.1"
                                :max="10000"
                                placeholder="请输入最大值"
                            />
                        </a-form-model-item>
                        <a-form-model-item label="浮动间隔" prop="adStepBid">
                            <a-input-number
                                class="common-input"
                                v-model="configForm.adStepBid"
                                placeholder="请输入浮动间隔"
                            />
                        </a-form-model-item>
                    </div>
                </a-form-model>
            </div>
        </a-modal>
    </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() {
        let adMinBidValidator = (rule, value, callback) => {
            const finallyResult = Number(this.configForm.adMaxBid);
            if (finallyResult !== '' && value && Number(value) < finallyResult) {
                callback();
            }
            else {
                callback('最低出价不能高于最高出价');
            }
        };
        let adMaxBidValidator = (rule, value, callback) => {
            const finallyResult = Number(this.configForm.adMinBid);
            if (finallyResult !== undefined && value && Number(value) > finallyResult) {
                callback();
            }
            else {
                callback('最高出价不能低于最低出价');
            }
        };
        let floatingIntervalValidator = (rule, value, callback) => {
            const finallyResult = Number(this.configForm.adMinBid) + Number(value);
            if (finallyResult !== undefined < Number(this.configForm.adMaxBid)) {
                callback();
            }
            else {
                callback('最低出价+浮动间隔<最高出价');
            }
        };
        return {
            labelCol: {span: 4},
            wrapperCol: {span: 14},
            configForm: {
                adMinBid: undefined,
                adMaxBid: undefined,
                adStepBid: undefined,
                adCpaBid: undefined
            },
            rules: {
                adCpaBid: [
                    {required: true, message: '请输入', trigger: 'blur'}
                ],
                adStepBid: [
                    {required: true, message: '请输入', trigger: 'blur'},
                    {validator: floatingIntervalValidator, trigger: 'blur'}
                ],
                adMinBid: [
                    {required: true, message: '请输入最低出价', trigger: 'blur'},
                    {validator: adMinBidValidator, trigger: 'blur'}
                ],
                adMaxBid: [
                    {required: true, message: '请输入最高出价', trigger: 'blur'},
                    {validator: adMaxBidValidator, trigger: 'blur'}
                ]
            },
            modeVisible: false,
            updateModTxt: {},
            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']),
        handleModeSure() {
            let paramsData = new FormData();
            if (this.updateModTxt.adBidCreateType === 'FIX') {
                paramsData.append('type', 1);
                paramsData.append('id', this.updateModTxt.id);
                paramsData.append('adCpaBid', this.configForm.adCpaBid);
            }
            else if (this.updateModTxt.adBidCreateType === 'RAND') {
                paramsData.append('type', 1);
                paramsData.append('id', this.updateModTxt.id);
                paramsData.append('adMinBid', this.configForm.adMinBid);
                paramsData.append('adMaxBid', this.configForm.adMaxBid);
            }
            else if (this.updateModTxt.adBidCreateType === 'STEP') {
                paramsData.append('type', 1);
                paramsData.append('id', this.updateModTxt.id);
                paramsData.append('adMinBid', this.configForm.adMinBid);
                paramsData.append('adMaxBid', this.configForm.adMaxBid);
                paramsData.append('adStepBid', this.configForm.adStepBid);
            }
            this.$refs.ruleForm.validate(valid => {
                if (valid) {
                    this.handlePopoverChange(paramsData);
                }
                else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        handleModeCancel() {
            this.adMinBid = undefined;
            this.adMaxBid = undefined;
            this.adStepBid = undefined;
            this.adCpaBid = undefined;
            this.modeVisible = false;
        },
        handleUpdateMod(record) {
            this.updateModTxt = record;
            this.modeVisible = true;
        },
        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;
                // if (this.updateModTxt === 'FIX') {
                //     paramsData.append('type', 1);
                //     paramsData.append('id', defaultList.id);
                //     paramsData.append('adCpaBid', this.modContent);
                // }
                // else if (this.updateModTxt === 'RAND') {
                //     paramsData.append('type', 1);
                //     paramsData.append('id', defaultList.id);
                //     paramsData.append('adMinBid', this.adMinBid);
                //     paramsData.append('adMaxBid', this.adMaxBid);
                // }
                // else if (this.updateModTxt === 'STEP') {
                //     paramsData.append('type', 1);
                //     paramsData.append('id', defaultList.id);
                //     paramsData.append('adMinBid', this.adMinBid);
                //     paramsData.append('adMaxBid', this.adMaxBid);
                //     paramsData.append('adStepBid', this.adStepBid);
                // }
            }
            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.adMinBid = undefined;
                    this.adMaxBid = undefined;
                    this.adStepBid = undefined;
                    this.adCpaBid = undefined;
                    this.modeVisible = false;
                    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>