<template>
    <div class="crowedPackage">
        <div class="optHeader">
            <div class="top">
                <span class="optItem">  
                <a-tree-select
                    v-model="treeValue"
                    show-search
                    style="width: 600px;height:30px"
                    :dropdownMatchSelectWidth='true'
                    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"              
                    tree-checkable
                    searchPlaceholder='请输入账户关键字搜索'
                    :show-checked-strategy="SHOW_PARENT"
                    placeholder="请选择账户或搜索账户关键字"
                    treeNodeFilterProp="title"
                    :allowClear="true"
                    @change="treeChange"
                    @search="treeSearch"
                    @select="treeSelect"                        
                    :maxTagCount='1'    
                    :tree-data="treeData"
                    :filterOption='filterOption'
                >
                </a-tree-select>
                </span>
                <span class="optItem">
                    <a-date-picker v-model="dateValue" @change="dateChange" />
                </span>

            </div>
            <div class="bottom">
                <div class="optItem">
                    <a-select size="default" placeholder='覆盖数量' v-model="coverageQuantity" style="width: 200px" @change="coverChange">
                        <a-select-option v-for="i in 25" :key="(i + 9).toString(36) + i">
                            {{ (i + 9).toString(36) + i }}
                        </a-select-option>
                    </a-select>
                </div>
                <div class="optItem">
                    <a-select size="default" placeholder='类别' v-model="category" style="width: 200px" @change="categoryChange">
                        <a-select-option value='' > 
                            全部
                        </a-select-option>
                        <a-select-option v-for="(item,index) in categoryArr" :key="index" :value='item.value' > 
                            {{ item.title }}
                        </a-select-option>
                    </a-select>
                </div>
                <div class="optItem">
                    <a-input-search placeholder="按名称搜索" v-model="nameSearch" style="width: 200px" @search="onSearch" />
                </div>
                <div class="optionBtn">
                     <a-button class="search" type='primary' @click="search">查询</a-button>
                     <a-button class="search" type='link' @click="clearAll">清空全部</a-button>
                </div>
            </div>
        </div>
        <div class="tableBOX">
            <div class="tableOpt">
                <a-button class="search" type='primary' @click="updatePackage">上传人群包</a-button>
                <a-button class="search" type='primary' @click="synchro">同步</a-button>
                <a-select size="default" placeholder='批量操作' v-model="batchValue" style="width: 200px" @change="batchChange">
                    
                    <a-select-option  value='push'>
                        推送
                    </a-select-option>
                    <a-select-option  value='delete'>
                        删除
                    </a-select-option>
                </a-select>
                <a-button class="addCol" type='primary' @click="search">自定义列</a-button>
            </div>
            <div class="tableArea">
                <a-table 
                :columns="columns" 
                :data-source="dataSource" 
                :row-selection="rowSelection" 
                bordered
                >
                    <template slot="campaignName" slot-scope="text,record">                                       
                        <editableCell :text="text" slotName='campaignName' @change="onCellChange(record.key, 'campaignName', $event)" />                       
                    </template>
                    <span slot="groupBudget" slot-scope="text,record">
                       <editableCell :text="text" slotName='groupBudget' @change="onCellChange(record.key, 'groupBudget', $event)" /> 
                    </span>
                    <span slot="status" slot-scope="text,record">
                        <span v-if="record.status">
                            <span style='color:#33CC33'>可用</span>
                            <span style="display:block">推送完成</span> 
                        </span>
                        <span v-else>
                            <span style='color:#CC3333'>不可用</span>
                            <span style="display:block">推送失败</span> 
                        </span>                
                    </span>
                    <span slot="operation" slot-scope="text,record">
                        <a href="javascript:;" style="margin-right:10px">推送</a>
                        <a-popconfirm
                            v-if="dataSource.length"
                            title="确定要删除吗？"
                            @confirm="() => onDelete(record.key)"
                        >
                            <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>
        <!-- 上传人群包的界面 -->
        <a-modal v-model="updatePackageVisiable"  @ok="updatePackageOk" width="750px"  okText='上传'>
            <div id="updatePackageOk">

            <p class="title">上传人群包</p>
            <div class="updatePackagebody" >
                <p class="item">
                    <span class="desc">匹配类型 <span class="redCircular"></span></span>
                    <a-select size="default" placeholder='请选择匹配类型'  v-model="matchValue" style="width: 400px" @change="matchChange">
                        <a-select-option v-for="i in 25" :key="(i + 9).toString(36) + i">
                            {{ (i + 9).toString(36) + i }}
                        </a-select-option>
                    </a-select>
                    <span class="tips">大部分是15位数字，如123456789012345（电信是14位）</span>
                </p>
                <p class="item">
                    <span class="desc">人群包名称 <span class="redCircular"></span></span>
                    <a-input placeholder="请输入人群包名称" v-model="crowedName" style="width: 400px" />
                </p>
                <p class="item">
                    <span class="desc">类型匹配 <span class="Circular"></span></span>
                    <a-radio-group name="radioGroup" v-model="typeMatch">
                        <a-radio :value="1">
                            设备号匹配
                        </a-radio>
                        <a-radio :value="2">
                            uid匹配
                        </a-radio>
                    </a-radio-group>
                    <span class="tips">
                        <span class="tipsinfo">设备号匹配：定向/排除时直接按照设备号圈选，数据相对量少而精确</span>
                        <span class="tipsinfo">UID匹配：定向/排除时圈选在该设备上登录的全部UID数据，数据相对量多而广泛</span>
                    </span>
                </p>
                <p class="item">
                    <span class="desc">人群分组 <span class="redCircular"></span></span>
                    <span class="crowedGroup">
                        <a-input-group compact >
                            <a-input style="width: 290px" placeholder='请输入内容' v-model="populationGroup"/>
                            <a-button type='default' @click="showGroupPage">选择已有<a-icon type="down" /></a-button>
                        </a-input-group>
                        <div class="crowedGroupPage" v-show="showcrowedPackage">
                            <ul @click.stop="selectgroupName">
                                <li class="crowedGroupPageItem">系统推荐</li>
                                <li class="crowedGroupPageItem">哈哈哈</li>
                                <li class="crowedGroupPageItem">嘿嘿</li>
                                <li class="crowedGroupPageItem">魏志佳编辑</li>
                                <li class="crowedGroupPageItem">1</li>
                                <li class="crowedGroupPageItem">1</li>                               
                            </ul>
                        </div>
                    </span>                                       
                </p>
                <p class="item">
                    <span class="desc">上传文件 <span class="redCircular"></span></span>
                    <a-upload action="https://www.mocky.io/v2/5cc8019d300000980a055e76" directory>
                        <a-button> <a-icon type="upload" /> 点击上传ZIP包 </a-button>
                    </a-upload>
                    <span class="tips">
                        <span class="tipsTitle">文件格式说明</span>
                        <span class="tipsinfo">1.安卓和IOS设备号，imei小写后MD5加密，IDFA大写后MD5加密，32位MD5均可</span>
                        <span class="tipsinfo">2.上传文件内，每行一个号码，号码数量不多于3千万</span>
                        <span class="tipsinfo">3.文件类型为单个或多个txt文件经过zip格式压缩得到，压缩后大小不超过1G</span>
                        <span class="tipsinfo">4.上传过程中需要一定的格式校验时间，请耐心等待</span>
                    </span>
                </p>
            </div>
            
            </div>
        </a-modal>
    </div>
</template>

<script>
import moment from 'moment';
import { getAction, postAction, downFile, downFilePost } from '@/api/manage';
import editableCell from './editableCell'
import { TreeSelect } from 'ant-design-vue';
const SHOW_PARENT = TreeSelect.SHOW_PARENT;


const columns = [
  {
    title: '名称',
    dataIndex: 'userName',
    align: 'center',
    key:'userName',
    scopedSlots: { customRender: 'userName' }
  },
  {
    title: '类别',
    dataIndex: 'department',
    align: 'center', 
    key: 'department',
    scopedSlots: { customRender: 'department' }
  },
  {
    title: '创建时间',
    dataIndex: 'roleName',
    align: 'center',
    
    key: 'roleName',
    scopedSlots: { customRender: 'roleName' }
  },
  
  {
    title: '全部覆盖人数',
    dataIndex: 'cost',
    align: 'center',
    scopedSlots: { customRender: 'cost' },
    sorter:()=>{}
  },
  {
    title: '账户名称',
    dataIndex: 'accountName',
    align: 'center',
    scopedSlots: { customRender: 'accountName' },
    
  },
  {
    title: '状态',
    dataIndex: 'status',
    align: 'center',
    scopedSlots: { customRender: 'status' },
    
  },
            
  {
    title: '操作',
    dataIndex: 'operation',
    align: 'center',
    scopedSlots: { customRender: 'operation' },
    
  }
]

const categoryArr=[
    {
        title:'规则',
        value:'guize',
        key:'guize'
    },
    {
        title:'运算',
        value:'yunsuan',
        key:'yuansuan'
    },
    {
        title:'上传',
        value:'update',
        key:'update'
    },
    {
        title:'扩展',
        value:'extend',
        key:'extend'
    },
    {
        title:'API',
        value:'API',
        key:'API'
    },
    {
        title:'付费',
        value:'pay',
        key:'pay'
    },
    {
        title:'主题人群',
        value:'crowd',
        key:'crowd'
    },
]
export default {
    components: {
        editableCell,
    },
    data() {
        return {
            //treeselect的参数
            
            treeData: [],
            SHOW_PARENT,
            accountId:[],
            
             //主页的表格
            dataSource:[
                {
                    userName:'人群纠错包1',
                    department:'运算',
                    roleName:'2020-6-10',
                    cost:16897546322,
                    accountName:'伊对-01',
                    status:true,
                    key:0
                },
                {
                    userName:'人群纠错包2',
                    department:'运算',
                    roleName:'2020-6-10',
                    cost:16897322,
                    accountName:'伊对-02',
                    status:false,
                    key:1
                },
                {
                    userName:'人群纠错包3',
                    department:'运算',
                    roleName:'2020-6-10',
                    cost:16322,
                    accountName:'伊对-03',
                    status:true,
                    key:2
                },
            ],
            categoryArr,
            columns,
            selectedRowKeys:[],
            rowSelection:{
                onChange: (selectedRowKeys, selectedRows) => {
                    console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
                    console.log(selectedRowKeys);
                    this.selectedRowKeys=selectedRowKeys;
                },
                onSelect: (record, selected, selectedRows) => {
                    console.log(record, selected, selectedRows);
                    
                },
                onSelectAll: (selected, selectedRows, changeRows) => {
                    console.log(selected, selectedRows, changeRows);
                    
                },
            },
            editID:0,
            //查询条件
            treeValue: [],
            coverageQuantity:undefined,
            category:undefined,
            dateValue:null,//日期选择器
            nameSearch:undefined,
            batchValue:undefined, //批量操作的选中值

            updatePackageVisiable:false,//上传人群包的弹出框
            matchValue:undefined, //上传人群包的匹配框
            crowedName:undefined,//上传人群包名称
            typeMatch:2,//类型匹配
            showcrowedPackage:false,
            populationGroup:undefined,//上传人群包---人群分组
        }
    },
    methods: {
        //项目改变后的事件
        treeChange(val) {
            // console.log(this.treeData)
            console.log(val)
            this.accountId = [];
            //选择一个后禁用其他
            if(val.length==1){
                if(val[0]*1){
                    let selectindex=0
                    this.treeData.forEach((ele,index)=>{                   
                        if(ele.children){
                            ele.children.map((item,ind)=>{
                                    if(item.value==val[0]){
                                        selectindex=index;
                                        
                                    }
                            })
                        }                   
                    });
                    console.log(selectindex)
                    if(selectindex ||selectindex==0){
                        this.treeData.forEach((ele,index)=>{
                            if(index!=selectindex){
                                ele.disableCheckbox = true;
                                if(ele.children){
                                    ele.children.map((item,ind)=>{
                                        item.disableCheckbox = true;
                                    })
                                }
                            }
                        })
                    }
                    
                }else{
                    //  console.log(1)
                    this.treeData.forEach((ele,index)=>{
                            if(ele.value!=val[0]){
                                ele.disableCheckbox = true;
                                
                                if(ele.children){
                                    ele.children.forEach((item,ind)=>{
                                        item.disableCheckbox = true;
                                    })
                                }
                            }
                            
                    })
                }
               
            }

            if(val.length==0){
                this.treeData.forEach((ele,index)=>{              
                        ele.disableCheckbox = false;
                        this.mediaId=ele.mediaId;
                        if(ele.children){
                            ele.children.forEach((item,ind)=>{
                                item.disableCheckbox = false;
                            })
                        }
                    
                });
               
            }
            if(val){
                val.forEach((ele,index)=>{
                if(ele*1){
                    this.accountId.push(ele.value)
                }else{              
                    let projectArr=this.treeData.filter((item)=>{
                        return item.value==ele
                    });
                    console.log(projectArr)
                    projectArr[0].children.forEach((element)=>{
                        this.accountId.push(element.value)
                    })
                }
                })       
            }
            
            console.log(this.accountId)
        },
        treeSearch(){
            // console.log(arguments);
        },
        treeSelect(){
            // console.log(arguments);
            // this.treeValue=arguments[0].value
        },
        coverChange(){

        },
        categoryChange(){

        },
        //日期改变
        dateChange(date, dateString) {
            // console.log(date, dateString);
            this.dateValue=date;
        },
        //按名字搜索
        onSearch(value) {
            // console.log(value);
        },
        //批量操作
        batchChange(val){
            // console.log(val)
            this.batchValue=val
        },
        //查询按钮
        search(){

        },
        //清空全部
        clearAll(){
            this.treeValue=[];
            this.coverageQuantity=undefined;
            this.category=undefined;
            this.dateValue=null;//日期选择器
            this.nameSearch=undefined;
            this.batchValue=undefined; //批量操作的选中值
        },
        //表格里的删除按钮
        onDelete(key) {
            console.log(key)
            const dataSource = [...this.dataSource];
            this.dataSource = dataSource.filter(item => item.key !== key);

        },
        //上传人群包
        updatePackage(){
            this.updatePackageVisiable=true;
        },
        //同步人群包
        synchro(){

        },
        updatePackageOk(){
            this.updatePackageVisiable = false;
        },
        //匹配类型
        matchChange(val){
            // console.log(val)
        },
        //上传人群包--选择已有的人群分组
        showGroupPage(){
            this.showcrowedPackage=!this.showcrowedPackage
        },
        //人群分组选中事件
        selectgroupName(e){
            // console.log(e)
            this.populationGroup=e.target.innerText;
            this.showcrowedPackage=!this.showcrowedPackage
        },
 
        filterOption(input, option){
            // console.log(input, option)
            return (
                option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
                );
        },
    },
    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 '-'
            }
            
        }
    },
    mounted() {
        
    },
}
</script>
<style lang="scss">
    #updatePackageOk{
        .title{
            font-size: 18px;
            font-weight: 700;
        }
        .desc{
            width: 100px;
            display: inline-block;
            text-align: right;
            margin-right: 10px;
            .redCircular,.Circular{
                display: inline-block;
                margin-left: 5px;
                width: 5px;
                height: 5px;
                border-radius: 50%;
                background-color: red;
                position: relative;
                top: -2px;
            }
            .Circular{
                background-color: transparent;
            }
        }
        .updatePackagebody{
            .crowedGroup{
                display: inline-block;
                width: 500px;
                position: relative;
                .crowedGroupPage{
                    position: absolute;
                    width: 400px;
                    height: 250px;
                    top: 32px;
                    left: 0;
                    background-color: #fff;
                    border: 1px solid #ddd;
                    border-top: null;
                    border-radius: 0  0 10px 10px ;
                    overflow:auto;
                    z-index: 3;
                    ul{
                        padding: 0;
                        margin: 0em;
                    }
                    .crowedGroupPageItem{
                        height: 30px;
                        line-height: 30px;
                        padding: 0 15px;
                        list-style: none;
                        
                    }
                    .crowedGroupPageItem:hover{
                        background-color: rgba(0,0,0,.2);
                    }
                }
            }
            .tips{
                display: block;
                font-size: 12px;
                color: #999;
                margin-left: 110px;
                margin-top: 10px;
                .tipsinfo{
                    display: block;
                    margin-bottom: 6px;
                }
                .tipsTitle{
                    display: block;
                    color: #777;
                }
            }
        }

    }
</style>
<style lang="scss" scoped>
.crowedPackage{
    
    .optHeader{
        margin: 15px 0;
        padding: 15px 15px;
        background: #fff;
        .optItem{
            display: inline-block;
            margin-right: 15px;
            .ok{
                margin-right: 15px;
            }
        }
        .top{
            margin-bottom: 15px;
        }
        .optionBtn{
        // display: inline-block;
            float: right;
            .searchBtn{
                margin-right: 10px;
            }
        }
    }
    .optHeader:hover{
        box-shadow: 0 0 15px rgba(0,0,0,.2);
        border-radius: 10px;
    }
    .tableBOX{
        background: #fff;
        padding: 15px 15px;
        .tableOpt{
            margin-bottom: 10px;
            .search{
                margin-right: 15px;
            }
            .addCol{
                float:right;

            }
        }
        
    }

}
</style>