<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 label="素材类型">
                        <a-select v-model="creativeStatus" style="width: 100px">
                            <a-select-option :value="2">不限</a-select-option>
                            <a-select-option value="CREATIVE_IMAGE_MODE_VIDEO_VERTICAL">竖版视频</a-select-option>
                            <a-select-option value="CREATIVE_IMAGE_MODE_LARGE">大图横图</a-select-option>
                            <a-select-option value="CREATIVE_IMAGE_MODE_LARGE_VERTICAL">大图竖图</a-select-option>
                            <a-select-option value="CREATIVE_IMAGE_MODE_UNION_SPLASH">开屏</a-select-option>
                            <a-select-option value="UNIVERSAL">通投智选</a-select-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label="状态">
                        <a-select v-model="searchStatus" style="width: 100px">
                            <a-select-option :value="2">不限</a-select-option>
                            <a-select-option :value="0">开启</a-select-option>
                            <a-select-option :value="1">关闭</a-select-option>
                        </a-select>
                    </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" style=" position: absolute;right: 150px;top: 0;" @click="linkConfigurtion">链接配置</a-button>
            <a-button type="primary" class="upload-person" @click="handleAddAccountConfig">新建账户配置</a-button>
        </div>
        <div class="control-con-table">
            <a-table
                ref="table"
                size="middle"
                bordered
                :loading="controlLoading"
                :columns="columns"
                :dataSource="dataSource"
                :pagination="false"
            >
                <span slot="customTitle">
                    花费(元)
                    <a-tooltip placement="top">
                        <template slot="title">
                            <span>当日花费</span>
                        </template>
                        <a-icon type="question-circle"/>
                    </a-tooltip>
                </span>
                <span slot="acountRelax" slot-scope="text, record">
                    <a-switch :checked="text === 0" @change="handleSwitchChang($event, record)"/>
                </span>
                <span slot="creativeImageMode" slot-scope="text,record">
                    <span>{{ handleChangeCreativeImage(text,record) }}</span>
                </span>
                <span solt="accountBudget" slot-scope="text, record">
                    {{ record.accountBudgetMode === '1' ? '不限' : text }}
                </span>
                <span slot="action" slot-scope="text, record">
                    <a @click="handleCopy(record)">复制</a>
                    <a-divider type="vertical"/>
                    <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 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 {
            creativeImageOption: [
                {
                    id: 'CREATIVE_IMAGE_MODE_VIDEO_VERTICAL',
                    value: '竖版视频'
                },
                {
                    id: 'CREATIVE_IMAGE_MODE_VIDEO',
                    value: '横版视频'
                },
                {
                    id: 'CREATIVE_IMAGE_MODE_LARGE',
                    value: '大图横图'
                },
                {
                    id: 'CREATIVE_IMAGE_MODE_SMALL',
                    value: '小图'
                },
                {
                    id: 'CREATIVE_IMAGE_MODE_LARGE_VERTICAL',
                    value: '大图竖图'
                },
                {
                    id: 'CREATIVE_IMAGE_MODE_UNION_SPLASH',
                    value: '开屏'
                }
            ],
            searchStatus: 0,
            creativeStatus: 2,
            controlLoading: true,
            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: '素材类型',
                    align: 'center',
                    dataIndex: 'creativeImageMode',
                    scopedSlots: {customRender: 'creativeImageMode'}
                },
                {
                    title: '账户ID',
                    align: 'center',
                    dataIndex: 'accountId'
                },
                {
                    title: '创建时间',
                    dataIndex: 'createTime',
                    align: 'center'
                },
                {
                    title: '账户余额',
                    dataIndex: 'validBalance',
                    align: 'center'
                },
                {
                    title: '账户日预算（元）',
                    dataIndex: 'accountBudget',
                    width: 180,
                    align: 'center'
                },
                {
                    title: '出价（元）',
                    dataIndex: 'adCpaBidStr',
                    align: 'center'
                },
                {
                    align: 'center',
                    dataIndex: 'cost',
                    width: 150,
                    slots: {title: 'customTitle'}
                },
                {
                    title: '操作',
                    dataIndex: 'action',
                    align: 'center',
                    width: '23%',
                    scopedSlots: {customRender: 'action'}
                }
            ]
        };
    },
    created() {
        this.form = this.$form.createForm(this);
    },
    mounted() {
        this.handleInitTable();
    },
    methods: {
        
        ...mapGetters(['nickname', 'avatar', 'userInfo']),
        handleChangeCreativeImage(val,record) {
           

           if (record.inventoryCatalog == 'UNIVERSAL') {
           
            return  record.inventoryCatalog != null && record.inventoryCatalog == 'UNIVERSAL' ?'通投智选' : '-'
           }else{
               return val ? this.creativeImageOption.filter(item => item.id === val)[0].value : '-';
           }
                
            
            
        },
        handleAccountMode(e) {
            this.budgetForm.budget = 1000;
            this.adBudgetShowTitle = false;
        },
        handleAccountBudget(e) {
            const adBudgetInput = e.target.value;
            this.budgetForm.budget = Number(Number(adBudgetInput).toFixed(2));
        },
        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.controlLoading = true;
                    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.adCpaBid = record.adCpaBid;
            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.controlLoading = true;
                    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.searchStatus = 0;
            this.creativeStatus = 2;
            this.controlLoading = true;
            this.handleInitTable();
        },
        handleInitTable() {
            const paramsData = {
                accountId: this.acountId,
                status: this.searchStatus === 2 ? '' : this.searchStatus,
                creativeImageMode: this.creativeStatus === 2 || this.creativeStatus == 'UNIVERSAL'? '' : this.creativeStatus,
                inventoryCatalog:this.creativeStatus == 'UNIVERSAL' ? 'UNIVERSAL' :'',
                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 => {
                        if (item.accountBudgetMode === '1') {
                            item.accountBudget = '不限';
                        }
                    });
                    this.controlLoading = false;
                    this.dataSource = result.result.records;
                    this.totalAll = result.result.total;
                }
                else {
                    this.$message.error(result.message);
                }
            }).catch(error => {
                console.log(error, 'eeee');
            });
        },
        handleCopy(data) {
            let that = this;
            this.$confirm({
                title: '复制提示',
                content: '请确认是否复制该账户配置',
                onOk() {
                    let params = {
                        accountModal: 'copy',
                        id: data.id
                    };
                    localStorage.setItem('queryList', JSON.stringify(params));
                    that.$router.push('/account-config/components/configuration-modal');
                    // /account-config/components/configuration-copy
                }
            });
        },
        handleListDelete(data) {
            let that = this;
            this.$confirm({
                title: '删除提示',
                content: '是否删除该条数据',
                onOk() {
                    that.controlLoading = true;
                    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');
                    });
                }
            });
        },
        handleQueryList(event) {
            this.tablePag.page = 1;
            event.preventDefault();
            this.controlLoading = true;
            this.handleInitTable();
        },
        onShowSizeChange(current, pageSize) {
            this.tablePag = {
                page: current,
                size: pageSize
            };
            this.controlLoading = true;
            this.handleInitTable();
        },
        handleSwitchChang(checked, data) {
            this.controlLoading = true;
            const paramsData = {
                id: data.id,
                state: checked ? 0 : 1,
                creativeImageMode: this.creativeStatus === 2 ? '' : this.creativeStatus,
                accountId: data.accountId,
                creativeImageMode: data.creativeImageMode,
                adDeliveryRange:'UNIVERSAL'
            };
            const forDate = new FormData();
            forDate.append('id', paramsData.id);
            forDate.append('state', paramsData.state);
            forDate.append('accountId', paramsData.accountId);
            forDate.append('creativeImageMode', paramsData.creativeImageMode);
            if (data.inventoryCatalog == 'UNIVERSAL') {
                forDate.append('adDeliveryRange',paramsData.adDeliveryRange)
            }
            
            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');
        },
        linkConfigurtion(){
            this.$router.push('/account-config/components/link-configuration');
        },
    }
};
</script>
<style lang="less" scoped>
    @import "account-config";
</style>