<template>
    <div class="directionalPackage">
        <!-- <div class="topOptions">
           
                <span class="OptinItem topOpt">               
                    <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>
                </span>
                <span class="timepcik">

                </span>
                <span class="optionBtn">
                    <a-button type='primary' @click="search" class="searchBtn">查询</a-button>
                    
                </span>
        </div> -->
        <div class="tableBOX">
           
            <div class="newOpt">
                    <a-button class="search" type='primary' @click="openDirectionalPackage">新建定向包</a-button>
            </div>
            <div class="tableArea">
                <a-table 
                    :columns="columns" 
                    :data-source="dataSource" 
                    :pagination="ipagination"
                    bordered
                    @change="sort"
                    size='middle'
                >
                    
                    <span slot="landingType" slot-scope="text">
                        <span v-if="text=='EXTERNAL'">落地页</span>
                        <span v-if="text=='APP_ANDROID'">应用下载-安卓</span>
                        <span v-if="text=='APP_IOS'">应用下载-IOS</span>
                        <span v-if="text=='AWEME'">抖音推广</span>                       
                    </span>
                    <span slot="deliveryRange" slot-scope="text">
                        <span v-if="text=='DEFAULT'">默认</span>
                        <span v-if="text=='UNION'">穿山甲</span>                     
                    </span>
                    
                    <span slot="operation" slot-scope="text,record">
                        <a href="javascript:;" style="margin-right:10px" @click="editDirectedPackage(record.id)">编辑</a>
                        <a-popconfirm
                            v-if="dataSource.length"
                            title="确定要删除吗？"
                            @confirm="() => onDelete(record)"
                        >
                            <a href="javascript:;">删除</a>
                        </a-popconfirm>        
                    </span>
                    <span slot="parentGroup" slot-scope="text">
                        <a href="javascript:;" >{{text}}</a>
                    </span>
                    <span slot="parentPlan" slot-scope="text">
                        <a href="javascript:;" >{{text}}</a>
                    </span>
                    <span slot="cost" slot-scope="cost">       
                        {{cost | formatCurrency }}
                    </span>
                </a-table>
            </div>
        </div>
    </div>
</template>

<script>
import moment from 'moment';
import {mapGetters} from 'vuex';

import { getAction, postAction, downFile, downFilePost } from '@/api/manage';
import { JeecgListMixin } from '@/mixins/ipagination'
import qs from 'qs'
const columns = [
  {
    title: '定向包名称',
    dataIndex: 'name',
    align: 'center',
    key:'name',
    scopedSlots: { customRender: 'name' }
  },
  {
    title: '定向描述',
    dataIndex: 'description',
    align: 'center', 
    key: 'description',
    scopedSlots: { customRender: 'description' }
  },
  {
    title: '定向包类型',
    dataIndex: 'landingType',
    align: 'center',   
    key: 'landingType',
    scopedSlots: { customRender: 'landingType' }
  },
  
  {
    title: '投放范围',
    dataIndex: 'deliveryRange',
    align: 'center',
    scopedSlots: { customRender: 'deliveryRange' },
   
  },
    // {
    //     title: '关联计划',
    //     dataIndex: 'accountName',
    //     align: 'center',
    //     scopedSlots: { customRender: 'accountName' },
        
    // },   
  {
    title: '操作',
    dataIndex: 'operation',
    align: 'center',
    scopedSlots: { customRender: 'operation' },
    
  }
]


export default {
    mixins: [JeecgListMixin],
    data() {
        return {
             //主页的表格
            dataSource:[],
            columns,
            accountID:undefined,
            treeData:[],
            userId:''
        }
    }, 
    methods: {
        ...mapGetters(['userInfo']),
        openDirectionalPackage(){
            this.$router.push({path:'/BatchCreate/newDirectedPackage'})
        },
        filterOption(input, option){
            console.log(input, option)
            return (
                option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
            );
        },
        accountIDChange(val){
            console.log(val);
            let currentData=this.treeData.filter((item)=>{
                return item.value==val
            })
            console.log(currentData);
            if(currentData.length>0){
                this.accountID=undefined;
                this.openID=val
            }
        },
        //请求项目和账户内容
        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+'_'+element.project.projectName;
                            this.treeData[index].children[i].value=ele.accountId;
                            this.treeData[index].children[i].key=ele.accountId;
                        })
                            
                        }                           
                    }      
                    });
                    // console.log(this.treeData)
                    
                }
            }
            })
        },
        sort(pagination, filters, sorter, { currentDataSource }){
            console.log(pagination, filters, sorter)           
            // this.ipagination.current=pagination.current;
            getAction('/ctop/audiencePackage/queryByUserId',{
                userId:this.userId,
                pageNo:this.ipagination.current
            }).then((res)=>{
                console.log(res);
                this.dataSource=res.result.records;
                this.ipagination.total=res.result.total
            })
        },
        search(){
            this.dataSource=[];
            if(this.accountID){
                
            }else{
                this.$message.error('请先选择账户!')
            }
        },
        onDelete(record){
            console.log(record);
            let params=qs.stringify({
                id:record.id
            })
            postAction('/ctop/audiencePackage/delete',params).then((res)=>{
                console.log(res);
                if(res.success){
                    this.getTableList()
                }else{
                    this.$message.error('删除失败，请稍后重试！')
                }
            })
        },
        editDirectedPackage(id){
            this.$router.push(`/BatchCreate/newDirectedPackage?id=${id}`)
        },
        getTableList(){
            getAction('/ctop/audiencePackage/queryByUserId',{
                userId:this.userId
            }).then((res)=>{
                console.log(res);
                this.dataSource=res.result.records;
                this.ipagination.total=res.result.total
            })
        },
    },
    watch:{

    },
    mounted() {
         this.accountHttp();

         let userinfo=localStorage.getItem('pro__Login_Userinfo')
         if(userinfo){
             this.userId=JSON.parse(userinfo).value.id
         }
        this.getTableList()
    },
    filters: {
        toPercentage(val) {
            if(val){
                if(typeof val != 'string'){
                    return (val * 100).toFixed(2) + '%'
                }else{
                    return val
                }
            }else if(typeof val =='string'){
                    return val
                }
            else{
                return 0
            }    
        },
            //保留两位小数并且变成货币格式
        decimalsHandle(val){
            
            if(val && typeof val !='string'){
                if(val>=0){
                    val=parseFloat(val).toFixed(2);
                    let numberStr = val.toString()
                    let str = numberStr.split('.')
                    
                    let str0=str[0].split('').reverse();
                    for (let i = 0; i < str0.length; i++) {
                        if ((i + 1) % 4 === 0) {
                            str0.splice(i, 0, ',')
                        }
                    }
                    str0.reverse()
                    let handleResult = ''
                    for (let j = 0; j < str0.length; j++) {
                        handleResult += str0[j]
                    }
                    
                    return handleResult+'.'+str[1]
                }else{
                    val=parseFloat(val).toFixed(2);
                    let numberStr = val.toString()
                    let str = numberStr.split('.')
                    
                    let str0=str[0].substr(1).split('').reverse();
                    for (let i = 0; i < str0.length; i++) {
                        if ((i + 1) % 4 === 0) {
                            str0.splice(i, 0, ',')
                        }
                    }
                    str0.reverse()
                    let handleResult = ''
                    for (let j = 0; j < str0.length; j++) {
                        handleResult += str0[j]
                    }
                    
                    return '-'+handleResult+'.'+str[1]
                }
                
            }else if(typeof val =='string'){
                return val
            }
            else{
                return 0
            }           
        },
        //变成货币格式
        formatCurrency(val){
            if((val||val==0)&& typeof val !='string'){
                let numberStr = val.toString()
                let str = numberStr.split('').reverse()
                for (let i = 0; i < str.length; i++) {
                    if ((i + 1) % 4 === 0) {
                    str.splice(i, 0, ',')
                    }
                }
                str.reverse()
                let handleResult = ''
                for (let j = 0; j < str.length; j++) {
                    handleResult += str[j]
                }
                return handleResult
            }else if(typeof val =='string'){
                    return val
            }
            else{
                return '-'
            }
            
        }
    },
}
</script>

<style lang="scss" scoped>
.directionalPackage{
    .topOptions{
        padding: 15px 15px;
        background-color: #fff;
        margin-bottom: 15px;
        .topOpt{
            width: 100%;
            margin-bottom: 10px;
        }
    
        .search{
            margin-right: 15px;
        }
        .addCol{
            float:right;

        }
        .optionBtn{
            // display: inline-block;
            float: right;
            .searchBtn{
                margin-right: 10px;
            }
        }
    }
    .tableBOX{
        background: #fff;
        padding: 15px 15px;
        
        
        .newOpt{
            margin-bottom: 10px;
        }
        
    }

}
</style>