<template>
    <div class="newGroup">
        
        <div class="currentOPt">
            <div class="currentAccount">
                选择账号： 
                <a-tree-select
                    show-search
                    allow-clear
                    dropdownMatchSelectWidth
                    v-model="accountID"
                    style="width: 60%"
                    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                    :tree-data="treeData"
                    placeholder="请选择具体账户"                   
                    :filterOption='filterOption'
                    treeNodeFilterProp='title'
                    @change='accountIDChange'                  
                >
                    
                </a-tree-select>
            </div>
            <div class="tabBody">
                <a-tabs default-active-key="create" @change="tabChange">
                    <a-tab-pane key="create" tab="新建广告组">
                        <a-form :form="form">
                            <a-form-item label="推广目的" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
                                <a-radio-group   v-decorator="['landingType',{initialValue:'APP' }]" @change="landingTypeChange">
                                    <a-radio-button value="APP">应用推广</a-radio-button>
                                    <a-radio-button value="LINK">销售线索收集</a-radio-button>                                   
                                </a-radio-group>
                            </a-form-item>
                            <a-form-item label="广告组预算" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
                                <a-radio-group  v-decorator="['budgetMode',{initialValue:'BUDGET_MODE_INFINITE' }]">
                                    <a-radio-button value="BUDGET_MODE_INFINITE">不限</a-radio-button>
                                    <a-radio-button value="BUDGET_MODE_DAY">指定日预算</a-radio-button>                                   
                                </a-radio-group>
                            </a-form-item>
                            <a-form-item v-if="getFormData('budgetMode')=='BUDGET_MODE_DAY'" label="日预算" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
                                <a-input-number  :max="9999999.99" :step="1"  v-decorator="['budget',{initialValue:1000 }]" @change="budgetChange" @blur='budgetBlur' />
                                <span class="tip" v-if="getFormData('budget')<1000">预算不少于1000.00元，不超过9999999.99元，请正确输入</span>
                            </a-form-item>
                            <a-form-item label="广告组名称" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
                               <a-input   v-decorator="['campaignName', { rules: [{ required: true ,message: '广告组名称必须填写'}] }]" />
                            </a-form-item>
                            <a-form-item label="广告组状态" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
                               <a-radio-group  v-decorator="['operation',{initialValue:'enable' }]">
                                    <a-radio-button value="enable">开</a-radio-button>
                                    <a-radio-button value="disable">关</a-radio-button>                                   
                                </a-radio-group>
                            </a-form-item>
                           
                        </a-form>
                    </a-tab-pane>
                    <a-tab-pane key="exist" tab="选择已有广告组" forceRender>
                        <div class="selectedExist">
                            <a-input v-model="selectedCampaignValue" class="input" placeholder="请输入广告组id或名称" @change="selectedCampaign">
                                <a-icon slot="addonAfter" type="search" />
                            </a-input>
                            <div class="campaign-have-list">
                                <div class="campaign-have-header">列表</div>
                                <div class="hasAccountID" v-if="accountID">
                                    <a-spin :spinning="spinning">
                                        <ul v-if="campaignHaveList.length>0">
                                            <li class="ad-d-flex ad-d-flex-between" v-for="(item,index) in campaignHaveList" :key="index" @click="goPlan(item)">
                                                <span class="info">{{item.name}}</span>
                                                <span class="landing-type">信息流_{{item.landingType_dictText}}</span>
                                            </li>
                                        </ul>
                                        <div v-else class="noAccountID">
                                            暂无数据
                                        </div>
                                    </a-spin>
                                </div>
                                <div class="noAccountID" v-else>
                                    选择账户后，才能选择已有广告组
                                </div>
                                
                            </div>
                            <div class="fenye" v-if="totalPage">
                                <a-pagination :current='currentPage' size='small' :total='totalPage' :pageSize='10' @change="pageNoChange" />
                            </div>
                        </div>
                        
                        
                    </a-tab-pane>
                
                </a-tabs>
            </div>
            <div class="creatBody">
                <a-button type='default' class="goback" @click="goback">返回</a-button>
                <a-button type='danger' @click="goShowTable" style="margin-right:20px">保存并返回</a-button>
                <a-button  type='primary' @click="nextHandle" :loading='nextLoading'>创建并下一步</a-button>
            </div>
        </div>
    </div>
</template>

<script>

import moment from 'moment';
import {mapGetters} from 'vuex';

import { getAction, postAction, downFile, downFilePost } from '@/api/manage';
import qs from 'qs'
const formItemLayout = {
  labelCol: { span: 2 },
  wrapperCol: { span: 8 },
};

export default {
    data() {
        return {
            nextLoading:false,
            tabKey:'create',
            accountID:undefined,
            treeData:[],
            formItemLayout,
            form: this.$form.createForm(this),
            selectedCampaignValue:undefined,
            spinning:false,
            campaignHaveList:[],
            currentPage:1,
            totalPage:0
        }
    },
    methods: {
        ...mapGetters(['userInfo']),
        tabChange(key){
            console.log(key);
            this.tabKey=key;
            
        },
        accountIDChange(val){
            console.log(val,this.accountID);
            let currentData=this.treeData.filter((item)=>{
                return item.value==val
            })
            // console.log(currentData);
            if(currentData.length>0){
                this.accountID=undefined;
                this.openID=val
            }
            this.getExsitGroupList();
            console.log(this.treeData)
            this.treeData.forEach((item)=>{
                item.children.forEach(ele=>{
                    if(ele.value==val){
                        let accountInfo=JSON.stringify(ele)
                        localStorage.setItem('accountInfo',accountInfo)
                    }
                })
            })
        },
        getExsitGroupList(){
            this.spinning=true;
            getAction('/ctop/byteDanceCampaign/list',{
                accountId:this.accountID,
                pageNo:this.currentPage,
                name:this.selectedCampaignValue
            }).then(res=>{
                console.log(res)
                if(res.success){
                    this.spinning=false;
                    this.totalPage=res.result.total;
                    this.campaignHaveList=res.result.records;
                }
            })
        },
        filterOption(input, option){
            console.log(input, option)
            return (
                option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
            );
        },
         //请求项目和账户内容
        accountHttp(){
            this.treeData=[];
            this.accountID=undefined;
            getAction('/ctop/projectMember/getProjectAccountByUserId?mediaType=1&userId=' + this.userInfo().id, {}).then(res => {
            if(res.success){
                    // console.log(res);
                    if(res.result){
                        res.result.forEach((element,index) => {
                        if(element){                  
                            this.treeData.push({});                    
                            this.treeData[index].title=element.project.projectName +'_('+ element.project.advertiserName +')';
                            this.treeData[index].value='project'+element.project.projectId;
                            this.treeData[index].key=element.project.projectId;
                            this.treeData[index].mediaId=element.project.mediaId;
                            this.treeData[index].children=[];
                                                
                            if(element.account.length){
                            element.account.forEach((ele,i)=>{
                                this.treeData[index].children.push({});
                                this.treeData[index].children[i].title=ele.userName+'_'+ele.authName;
                                this.treeData[index].children[i].value=ele.accountId;
                                this.treeData[index].children[i].key=ele.accountId;
                            })
                                
                            }                           
                        }      
                        });
                        // console.log(this.treeData)
                        // this.accountID=this.accountInfo.value
                    }
            }
            })
        },


        //获取表单的某一个属性值
        getFormData(className) {
            return this.form.getFieldValue(className)
        },
        //推广目的改变
        landingTypeChange(e){
            console.log(e.target)
            if(e.target.value=='APP'){
                this.form.setFieldsValue({
                    campaignName:`应用推广_${moment().format('MM_DD_HH:SS')}`
                })
            }else if(e.target.value=='LINK'){
                this.form.setFieldsValue({
                    campaignName:`销售线索收集_${moment().format('MM_DD_HH:SS')}`
                })
            }
        },
        //预算改变
        budgetChange(val){
            console.log(val)  
            var strRegex = /^[0-9](.)+$/
            var re = new RegExp(strRegex)
            // console.log(re.test(res))
            if (re.test(val)) {
                return true
            } else {
                // return false
                this.$message.error('请勿输入非数字！')
                // let num = val.splice(val.length-2,1)
                // this.form.setFieldsValue({
                //     budget:1000
                // })
            }          
        },
        budgetBlur(e){
            console.log(e.target.value)

            if(e.target.value==0){
                this.form.setFieldsValue({
                    budget:1000.0
                })
            }
        },
        nextHandle(){
           if(this.accountID){
                this.form.validateFields((err, values) => {
                    if (!err) {
                        this.nextLoading=true;
                        console.log('Received values of form: ', values);
                       if(values.budgetMode== "BUDGET_MODE_DAY" && (values.budget<1000||values.budget>9999999.99 )){
                            this.$message.error('日预算不少于1000.00元，不超过9999999.99元，请正确输入')
                        }else{
                             postAction('/ctop/byteDanceCampaign/add',qs.stringify({
                                accountId:this.accountID,
                                ...values
                            })).then(res=>{
                                console.log(res)
                                if(res.success){
                                    this.nextLoading=false;
                                    this.$message.success('广告组创建成功，1s后将跳转到新建计划页面');
                                    values.id=res.campaign_id;
                                    values.accountId=this.accountID
                                    let groupInfo=JSON.stringify(values)
                                    localStorage.setItem('groupInfo',groupInfo)
                                    setTimeout(() => {
                                        this.$router.push('/modules/BatchCreate/newPlan')
                                    },1000);                                
                                }else{
                                    this.nextLoading=false;
                                    this.$message.error(res.message) 
                                }
                            })
                        }
                    }else{
                         this.$message.error('请正确填写必填选项') 
                    }
                });
           }else{
               this.$message.error('请选择具体的账户')
           }
            
        },
        goback(){
            this.$router.push('/modules/BatchCreate/TouTiaoBatch')
            this.$bus.$emit('remove', '/modules/BatchCreate/newGroup')
            localStorage.setItem('groupInfo','');
            localStorage.setItem('planInfo','');
            localStorage.setItem('accountInfo','');
        },

        selectedCampaign(e){
            // console.log(e.target.value,this.selectedCampaignValue);
            if(this.accountID){
                this.getExsitGroupList();
            }else{
                this.$message.warning('请选择账户后重试！')
                this.selectedCampaignValue=undefined;
            }
        },
        goPlan(item){
            console.log(item)
            let groupInfo=JSON.stringify(item)
            localStorage.setItem('groupInfo',groupInfo)
            this.$router.replace(`/modules/BatchCreate/newPlan`)
        },
        //分页页码改变
        pageNoChange(val){
            console.log(val);
            this.currentPage=val;
            this.selectedCampaign()
        },
        goShowTable(){
            if(this.accountID){
                this.form.validateFields((err, values) => {
                    if (!err) {
                        this.nextLoading=true;
                        console.log('Received values of form: ', values);
                       if(values.budgetMode== "BUDGET_MODE_DAY" && (values.budget<1000||values.budget>9999999.99 )){
                            this.$message.error('日预算不少于1000.00元，不超过9999999.99元，请正确输入')
                        }else{
                             postAction('/ctop/byteDanceCampaign/add',qs.stringify({
                                accountId:this.accountID,
                                ...values
                            })).then(res=>{
                                console.log(res)
                                if(res.success){

                                    localStorage.setItem('groupInfo','');
                                    localStorage.setItem('planInfo','');
                                    localStorage.setItem('accountInfo','');

                                    this.nextLoading=false;
                                    this.$message.success('广告组创建成功，即将返回批量页面');
                                    values.id=res.campaign_id;
                                    values.accountId=this.accountID
                                    let groupInfo=JSON.stringify(values)
                                    localStorage.setItem('groupInfo',groupInfo)
                                    setTimeout(() => {
                                        this.$router.push('/modules/BatchCreate/TouTiaoBatch')
                                    },1000);                                
                                }else{
                                    this.nextLoading=false;
                                    this.$message.error(res.message) 
                                }
                            })
                        }
                    }else{
                        // console.log(err)
                        this.$message.error('请正确填写必填选项') 
                    }
                });
           }else{
               this.$message.error('请选择具体的账户')
           }
        },
    },
    mounted() {
        this.accountHttp();
        let name=this.getFormData('landingType')
        if(name=='APP'){
            this.form.setFieldsValue({
                campaignName:`应用推广_${moment().format('MM_DD_HH:SS')}`
            })
        }else{
            this.form.setFieldsValue({
                campaignName:`销售线索收集_${moment().format('MM_DD_HH:SS')}`
            })
        };

        let accountInfo=localStorage.getItem('accountInfo');
        if(accountInfo!=null){
            this.accountInfo=JSON.parse(accountInfo);

        }
    },
    // beforeCreate() {
    //     this.form = this.$form.createForm(this, { name: 'validate_other' });
    // },
}
</script>
<style lang="scss">
.newGroup{
  .ant-btn-danger {
    background-color: #ff4d4f !important; 
  }
}
</style>
<style lang="scss" scoped>
.newGroup{
    ul, li {
        list-style: none;
        padding: 0;
        margin: 0;
    }
    // background: rgb(249,249,249);

    // padding: 20px; 
    .currentOPt{             
        .currentAccount{
            height: 70px;
            padding: 20px 30px;
            background: #fff;
            margin-bottom: 20px;
        }
        .tabBody{
            background: #fff;
            margin-bottom: 20px;
            padding: 20px 30px;
            .tip{
                font-size: 12px;
                color: tomato;
                display: block;
                margin-top: 5px;
                height: 20px;
                line-height: 20px;
                
            }
            .selectedExist{
                width: 600px;
                .input{
                    margin-bottom:16px ;
                }
                .campaign-have-list{
                    font-family: PingFangSC-Regular;
                    font-size: 14px;
                    color: #333;
                    border: 1px solid #DADFE3;
                    border-radius: 4px;
                    margin-bottom: 16px;
                    height: 388px;
                    .campaign-have-header {
                        height: 38px;
                        width: 100%;
                        padding-left: 13px;
                        line-height: 38px;
                        background: #f8f9fa;
                        border-radius: 4px 4px 0px 0px;
                        border-bottom: 1px solid #DADFE3;
                    }
                    .campaign-have-list ul {
                        width: 100%;
                        height: 350px;
                        padding-top: 6px;
                        
                    }
                    li{
                        padding: 6px 10px;
                        cursor: pointer;
                    }
                    li:hover{
                        background: #EDF1F5;
                    }
                    .ad-d-flex-between {
                        justify-content: space-between !important;
                    }

                    .ad-d-flex, .ad-btn {
                        display: flex;
                        align-items: center;
                    }
                    .byted-loading-v {
                        position: absolute;
                        top: 0;
                        right: 0;
                        bottom: 0;
                        left: 0;
                        z-index: 996;
                        background-color: hsla(0,0%,96%,.9);
                    }
                    .info{
                        width: 60%;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        white-space: nowrap;
                    }
                    .landing-type {
                        color: #999;
                        font-size: 12px;
                        white-space: nowrap;
                    }
                }
                .noAccountID{
                    font-size: 14px;
                    text-align: center;
                    color: #999;
                    line-height: 388px;
                }
                .fenye{
                    height: 60px;
                    padding-top: 12px;
                    text-align: right;
                }
            }
        }
        .creatBody{
            background: #fff;
            margin-bottom: 20px;
            padding: 20px 30px;
            text-align: right;
            .goback{
                margin-right: 20px;
            }
        }
    }
}
</style>