<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 solt="accountBudget" slot-scope="text, record">
                    {{ record.accountBudgetMode === '1' ? '不限' : text }}
                </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 @click="handleUpdateBudget(record)">修改预算</a>
                </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="budgetVisible"
            :visible="budgetVisible"
            dialog-class="mode-modal-class"
            @ok="handleBudgetSure"
            @cancel="handleBudgetCancel"
        >
            <div>
                <a-form-model
                    ref="budgetForm"
                    :model="budgetForm"
                    :rules="budgetRules"
                    :label-col="labelCol"
                    :wrapper-col="wrapperCol"
                >
                    <a-form-model-item label="预算方式">
                        <a-radio-group
                            v-model="budgetForm.budgetType"
                            button-style="solid"
                            @change="handleAccountMode"
                        >
                            <a-radio-button value="1">不限预算</a-radio-button>
                            <a-radio-button value="2">指定预算</a-radio-button>
                        </a-radio-group>
                    </a-form-model-item>
                    <a-form-model-item v-if="budgetForm.budgetType === '2'" label="账户日预算" prop="budget">
                        <a-input-number
                            v-model="budgetForm.budget"
                            :min="1000"
                            :max="9999999.99"
                            :step="0.01"
                            @blur="handleAccountBudget"
                        /> 元
                    </a-form-model-item>
                    <!-- <div v-if="adBudgetShowTitle" style="width: 500px;color: #f00;margin-left: 140px;">单次修改预算幅度, 不能低于100.0元</div> -->
                </a-form-model>
            </div>
        </a-modal>
        <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"
                                :step="0.01"
                                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"
                                :step="0.01"
                                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"
                                :step="0.01"
                                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"
                                :step="0.01"
                                placeholder="请输入最大值"
                            />
                        </a-form-model-item>
                        <a-form-model-item label="浮动间隔" prop="adStepBid">
                            <a-input-number
                                class="common-input"
                                :min="0"
                                :step="0.01"
                                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 adCpaBidValidator = (rule, value, callback) => {
            if (Number(this.updateModTxt.adBudget) < Number(value)) {
                callback('出价不能大于预算');
            }
            else {
                callback();
            }
        };
        let adMaxBidValidator = (rule, value, callback) => {
            const finallyResult = Number(this.configForm.adMinBid);
            if (finallyResult && value && Number(value) <= finallyResult) {
                callback('最高出价不能低于最低出价');
            }
            else if (Number(this.updateModTxt.adBudget) < Number(value)) {
                callback('出价不能大于预算');
            }
            else if (Number(this.configForm.adMaxBid) > Number(this.configForm.adMinBid) + Number(this.configForm.adStepBid)) {
                this.$refs['ruleForm'].clearValidate(['adStepBid']);
                callback();
            }
            else {
                this.$refs['ruleForm'].clearValidate(['adMinBid']);
                callback();
            }
        };
        let floatingIntervalValidator = (rule, value, callback) => {
            const finallyResult = Number(this.configForm.adMinBid) + Number(value);
            if (finallyResult < Number(this.configForm.adMaxBid)) {
                callback();
            }
            else {
                callback('最低出价+浮动间隔<最高出价');
            }
        };
        let budgetValidator = (rule, value, callback) => {
            // const finallyResult = Number(this.configForm.adMinBid) + Number(value);
            // if (finallyResult < Number(this.configForm.adMaxBid)) {
            //     callback();
            // }
            // else {
            //     callback('最低出价+浮动间隔<最高出价');
            // }
            const changeBudget = this.updateModTxt.accountBudget;
            if (Number(value) > Number(changeBudget) && Number(value) < (Number(changeBudget) + 100)) {
                callback('单次修改预算幅度, 不能低于100.0元');
            }
            else if (Number(value) < Number(changeBudget) && Number(value) > (Number(changeBudget) - 100)) {
                callback('单次修改预算幅度, 不能低于100.0元');
            }
            else {
                callback();
            }
        };
        return {
            adBudgetShowTitle: false,
            budgetVisible: false,
            budgetForm: {
                budgetType: '1',
                budget: 0
            },
            budgetRules: {
                budget: [
                    {required: true, message: '请输入', trigger: 'blur'},
                    {validator: budgetValidator, trigger: 'blur'}
                ]
            },
            labelCol: {span: 4},
            wrapperCol: {span: 14},
            configForm: {
                adMinBid: undefined,
                adMaxBid: undefined,
                adStepBid: undefined,
                adCpaBid: undefined
            },
            rules: {
                adCpaBid: [
                    {required: true, message: '请输入', trigger: 'blur'},
                    {validator: adCpaBidValidator, 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: 'accountBudget',
                    align: 'center'
                },
                {
                    title: '出价（元）',
                    dataIndex: 'adCpaBidStr',
                    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']),
        handleAccountMode(e) {
            this.budgetForm.budget = 1000;
            this.adBudgetShowTitle = false;
        },
        handleAccountBudget(e) {
            const adBudgetInput = e.target.value;
            // const changeBudget = this.updateModTxt.accountBudget;
            this.budgetForm.budget = Number(Number(adBudgetInput).toFixed(2));
            // if (Number(adBudgetInput) >= Number(changeBudget) && Number(adBudgetInput) < (Number(changeBudget) + 100)) {
            //     this.adBudgetShowTitle = true;
            // }
            // else if (Number(adBudgetInput) <= Number(changeBudget) && Number(adBudgetInput) > (Number(changeBudget) - 100)) {
            //     this.adBudgetShowTitle = true;
            // }
            // else {
            //     this.adBudgetShowTitle = false;
            // }
        },
        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.configForm.adMinBid = record.adMinBid;
            this.configForm.adMaxBid = record.adMaxBid;
            this.configForm.adStepBid = record.adStepBid;
            this.modeVisible = true;
        },
        handleUpdateBudget(record) {
            this.updateModTxt = record;
            this.budgetForm.budgetType = record.accountBudgetMode;
            this.budgetForm.budget = record.accountBudget;
            this.budgetVisible = true;
        },
        handleBudgetSure() {
            let paramsData = new FormData();
            paramsData.append('accountId', this.updateModTxt.accountId);
            paramsData.append('adId', this.updateModTxt.adId);
            paramsData.append('type', 2);
            paramsData.append('budget', this.budgetForm.budget);
            paramsData.append('budgetType', this.budgetForm.budgetType);
            paramsData.append('id', this.updateModTxt.id);
            paramsData.append('cost', this.updateModTxt.cost);
            if (this.adBudgetShowTitle) {
                return;
            }
            this.$refs.budgetForm.validate(valid => {
                if (valid) {
                    this.handlePopoverChange(paramsData);
                }
                else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        handleBudgetCancel() {
            this.budgetVisible = false;
            this.budgetForm.budgetType = '1';
        },
        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.budgetVisible = false;
                    this.budgetForm.budgetType = '1';
                    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,
                loginUserId: 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;
                        if (item.accountBudgetMode === '1') {
                            item.accountBudget = '不限';
                        }
                    });
                    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>