<template>
    <div class="housekeeper">
         <div class="topOptions">
            <span class="OptinItem topOpt">
                <!-- <Treeselect :appId.sync="accountID" :multiple="false" request="2,4" reqUrl='/ctop/projectMember/getProjectAccountByUserId' ref="treeSelect" style="margin-bottom:8px " /> -->

                <a-tree-select
                    v-model="accountIds"
                    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"
                                       
                    :maxTagCount='1'    
                    :tree-data="treeData"
                    :filterOption='filterOption'
                >
              
                </a-tree-select>
            </span>
            <span class="OptinItem">
                <a-select  style="width: 120px" v-model="statusValue" @change="statusChange" placeholder="请选择状态">
                    <a-select-option :value="0" >
                        不限
                    </a-select-option>
                    <a-select-option :value="1" >
                        启用
                    </a-select-option>
                    <a-select-option :value="2" >
                        暂停
                    </a-select-option>
                </a-select>
            </span>

            <span class="OptinItem">
                <!-- <a-date-picker @change="dateChange" /> -->
                 <a-range-picker v-model="dateValue" :disabled-date="disabledDate"  style="width: 250px;" format="YYYY-MM-DD" @change="dateChange" />
            </span>
            <span class="OptinItem">
                <a-input-search placeholder="请输入投放项目的名称" v-model="optionId" style="width: 200px"  />
            </span>
            <span class="optionBtn">
                <a-button type='primary' @click="search" class="searchBtn">查询</a-button>
                <!-- <a-button type='default' @click="reset">重置</a-button> -->
            </span>
        </div>
        <div class="tableArea">
            <div class="tableOption">
                <span class="OptinItem" style="margin-right:20px">
                    <a-button type='primary' @click="addNewProject">
                        <a-icon type="plus" />
                        新增投放项目
                    </a-button>
                </span>
                <span class="OptinItem">
                    <a-tooltip>
                        <template slot="title" >
                            这里可以批量启动、暂停、删除你的选择哦~
                        </template>
                        <!-- <a-button type="link" @click="changeSelectStatus">批量操作</a-button> -->
                        <span >批量操作：</span>
                    </a-tooltip>
                </span>
                <span class="OptinItem">
                    <a-select  style="width: 120px" @change="optChange" v-model="optValue" placeholder="请选择状态" :disabled='selectedRowKeys.length<=0'>
                        <a-select-option value="open" >
                            启动
                        </a-select-option>
                        <a-select-option value="pause">
                            暂停
                        </a-select-option>
                        <a-select-option value="delete">
                            删除
                        </a-select-option>
                    </a-select>
                </span>
                 <span class="OptinItem">
                    <a-popconfirm
                        title="确定要删除选择的内容吗？"
                        ok-text="删除"
                        cancel-text="取消"
                        @confirm="confirm"
                        @cancel="cancel"
                        v-if="optValue=='delete'"
                    >
                        <a-button type='primary' @click="isOkHandle" class="ok">确定</a-button>
                    </a-popconfirm>
                    <a-button type='primary' @click="isOkHandle" class="ok" v-else>确定</a-button>

                 </span>
                <!-- <span class="optionBtn">
                    <a-button type='primary' @click="reset">自定义列</a-button>
                </span> -->
            </div>
            <div class="table">
                <a-table
                    :columns="columns"
                    :data-source="data"
                    :rowSelection="{selectedRowKeys: selectedRowKeys,...rowSelection}"
                    bordered
                    :pagination="ipagination"
                    :loading="loading"
                    @change="sort"
                    
                >
                   

                    <span slot="checkedStatus" slot-scope="text,record">
                        <a-spin :spinning="record.spin" size="small" >
                            <div class="spin-content">
                                <a-switch size="default" :checked=text  @change="switchChange(text,record)"/>
                            </div>
                        </a-spin>    
                        <!-- <a-switch size="default" :checked=text  @change="switchChange(text,record)"/>                     -->
                    </span>

                    <span slot="budgetMode" slot-scope="text">
                        <span v-if="text=='DAILY'">日预算</span>
                        <span v-if="text=='TOTAL'">总预算</span>
                    </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="time" slot-scope="text,record">
                        {{record.startTime}}至{{record.endTime}}
                    </span>
                    <span slot="flowControlMode" slot-scope="text">
                        <span v-if="text=='FLOW_CONTROL_MODE_FAST'">优先跑量</span>
                        <span v-if="text=='FLOW_CONTROL_MODE_SMOOTH'">优先低成本</span>
                        <span v-if="text=='FLOW_CONTROL_MODE_BALANCE'">均衡投放</span>
                    </span>

                    <span slot="options" slot-scope="text,record">
                        <a href="javascript:;" @click="editProject(record)">编辑</a>
                        <a-divider type="vertical" />
                        <a href="javascript:;" @click="planAnalysis(record)">计划分析</a>
                        <a-divider type="vertical" />
                        <a href="javascript:;" @click="deleteProject(record)">删除</a>
                    </span>
                </a-table>
            </div>
        </div>
    </div>
</template>

<script>
import moment from 'moment';
import { getAction, postAction, downFile, downFilePost } from '@/api/manage';
const SHOW_PARENT = TreeSelect.SHOW_PARENT;
import { TreeSelect } from 'ant-design-vue';
import qs from 'qs'
const columns = [
  {
    title: '开关',
    dataIndex: 'checkedStatus',
    key: 'checkedStatus',
    align: 'center',
    scopedSlots: { customRender: 'checkedStatus' }
  },
  {
    title: '投放项目名称',
    dataIndex: 'name',
    key: 'name',
    align: 'center',
    scopedSlots: { customRender: 'name' }
  },
  {
    title: '投放项目状态',
    dataIndex: 'statusName',
    key: 'statusName',
    align: 'center',
  },
    //   {
    //     title: '建议',
    //     dataIndex: 'landingType_dictText',
    //     key: 'landingType_text',
    //     align: 'center',
    //   },
  {
    title: '投放项目预算类型',
    dataIndex: 'budgetMode',
    key: 'budgetMode',
    align: 'center',
    width:250,
    scopedSlots: { customRender: 'budgetMode' }
  },
  {
    title: '投放项目预算(元)',
    dataIndex: 'budget',
    key: 'budget',
    align: 'center',
    scopedSlots: { customRender: 'budget' }
  },
  {
    title: '投放时间',
    dataIndex: 'time',
    key: 'time',
    align: 'center',
    scopedSlots: { customRender: 'time' }
  },
  {
    title: '投放项目ID',
    dataIndex: 'id',
    key: 'id',
    align: 'center',
    scopedSlots: { customRender: 'id' }
  },
  {
    title: '所属账户ID',
    dataIndex: 'accountId',
    key: 'accountId',
    align: 'center',
    scopedSlots: { customRender: 'accountId' }
  },
  {
    title: '操作',
    dataIndex: 'options',
    key: 'options',
    align: 'center',
    width:200,
    scopedSlots: { customRender: 'options' }
  },
];

export default {
    data() {
        return {
            treeData: [],
            SHOW_PARENT,
            accountIds:[],
            ipagination: {
                current: 1,
                pageSize: 10,
                //   pageSizeOptions: ['10', '20', '30'],
                showTotal: (total, range) => {
                    return range[0] + "-" + range[1] + " 共" + total + "条"
                },
                showQuickJumper: true,
                showSizeChanger:true,
                pageSizeOptions: ['10', '30', '50'],
                total: 0,
                onChange: (current, pageSize) => {
                    // 切换分页时的回调，
                    // 当在页面定义change事件时，切记要把此处的事件清除，因为这两个事件重叠了，可能到时候会导致一些莫名的bug
                    this.ipagination.current = current;
                    this.ipagination.pageSize= pageSize;
                }
            },

            accountID:undefined,
            treeData:[],
            dateValue:[],//日期选择框选择
            dateString:[],//--我赋值的是dateString


            statusValue:undefined,
            optionId:'',//input输入的id或关键词
            optValue:undefined,

            data:[],
            columns,
            selectedRowKeys:[],
            selectedRows:[],
            loading:false,
            userInfo:{},
        }
    },
    computed: {
        rowSelection(){
            return {
                onChange: (selectedRowKeys, selectedRows) => {
                    // console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
                    this.selectedRowKeys=selectedRowKeys;
                    this.selectedRows=selectedRows;
                },
                onSelect: (record, selected, selectedRows) => {
                    // console.log(record, selected, selectedRows);
                    this.modifyTableData=selectedRows;

                    this.selectedRows=selectedRows;
                },
                onSelectAll: (selected, selectedRows, changeRows) => {
                    // console.log(selected, selectedRows, changeRows);
                    this.modifyTableData=selectedRows
                    this.selectedRows=selectedRows;
                },
            }

        },
    },
    methods:{
         // //项目改变后的事件
        treeChange(val) {
        // console.log(this.treeData)
            console.log(val)
            this.accountIds = [];
            //选择一个后禁用其他
            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;
                                    })
                                }
                            }
                            
                    })
                }
                // console.log(this.mediaId)
                
            }

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


                })       
            }
            
            console.log(this.accountIds);
            let LHKaccountInfo=[]
            this.accountIds.forEach(item=>{
                this.treeData.forEach(element=>{
                    element.children.forEach(ele=>{
                    if(item==ele.value){
                        LHKaccountInfo.push(ele)
                    }
                    })
                })
            })

        
        },
        
        
        filterOption(input, option){
        console.log(input, option)
        return (
            option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
            );
        },
    
        //请求项目和账户内容
        accountHttp(){
            this.treeData=[];
            this.accountIds=[];
            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)
                        
                    }
            }
            })
        },

        //状态改变
        statusChange(value){
            console.log(value);

        },

        disabledDate(current) {
            // console.log(current)
            return current && current > moment().subtract(1, 'day')
        },

        dateChange(date, dateString) {
            console.log(date, dateString);
            this.dateString=dateString;
        },

        search(){
            // console.log(this.accountID,this.dateString,this.statusValue,this.optionId);

            if(this.accountIds.length>0){
                this.loading=true
                
                this.tableListHttp()
                
            }else{
                this.$message.error('请选择账户后重试')
            }

        },

           //批量操作下的启动 删除 暂停
        optChange(value){
            // console.log(value)
            this.optValue=value;
        },

         //确定删除
        confirm(e) {
            // console.log(e);
            this.loading=true;
            if(this.optValue=='delete'){
                
                let params=[];
                params=this.selectedRows.map(item=>{
                    return {
                        accountId:record.accountId,
                        groupId:record.id,
                        
                    }
                })
            }
        },

         //批量操作的确定按钮
        isOkHandle(){
            console.log(this.optValue,this.selectedRows)
            if(this.optValue&&this.selectedRowKeys.length>0){
                let params=[];
                params=this.selectedRows.map(item=>{
                    return {
                        accountId:record.accountId,
                        groupId:record.id,
                        optStatus:'DELETE',
                    }
                })
            
                if(this.optValue=='pause'){   
                    this.loading=true;
                    params.forEach(item=>{
                        item.optStatus='ENABLE';
                    })
                    // this.batchEditStatus(params)
                }else if(this.optValue=='open'){
                   params.forEach(item=>{
                        item.optStatus='DISABLED';
                    })
                    // this.batchEditStatus(params)
                }
              
                this.batchEditStatus(params)
                
            }
            
        },

        sort(pagination, filters, sorter, { currentDataSource }){
            
            this.ipagination.current=pagination.current;

            this.ipagination.pageSize=pagination.pageSize;
            this.search()
        },

        batchEditStatus(params){
            postAction('/adlab/ctopAdlabProjectDetail/edit',params).then(res=>{
                console.log(res)
                if(res.success){
                    this.$message.success('修改成功');
                    this.tableListHttp();
                }else{
                    this.$message.success('修改失败')
                }
            })
        },
         //状态改变
        switchChange(text,record){
            // this.spinning=true;
            console.log(text,record);
            let recordData=JSON.parse(JSON.stringify(record))
            record.spin=true;

            let params=[];
            params.push({
                accountId:record.accountId,
                groupId:record.id,
                optStatus:record.optStatus=="DISABLED"?'ENABLE':'DISABLED'
            })
            postAction('/adlab/ctopAdlabProjectDetail/edit',params).then(res=>{
                console.log(res)
                record.spin=false;
                if(res.success){
                    this.$message.success('修改成功');
                    record.checkedStatus=!record.checkedStatus
                }else{
                    this.$message.success('修改失败')
                }
            })

        },

        // 新增投放项目
        addNewProject(){
            this.$router.push({path:'/LaunchHousekeeper/newProject'})
        },

        editProject(records){
            console.log(records);
            sessionStorage.setItem('editLHKProjectInfo',JSON.stringify(records));
            this.$router.push({path:'/LaunchHousekeeper/setProjectBudget'})
        },
        planAnalysis(records){
            console.log(records)
        },
        deleteProject(records){
            console.log(records)
        },

        // 请求账户的列表
        tableListHttp(){
            // let accountIds=JSON.stringify(this.accountIds)     
            // let createTime=JSON.stringify(this.dateString)      
            postAction('/adlab/ctopAdlabProjectDetail/list',{
                accountIds:this.accountIds,
                userId:this.userInfo.value.id,
                createTime:this.dateString,
                optStatus:this.statusValue==undefined?0:this.statusValue,
                name:this.name==undefined?'':this.name,
                pageNo:this.ipagination.current,
                pageSize:this.ipagination.pageSize
            }).then(res=>{
                console.log(res);
                this.loading=false;
                if(res.success){
                    this.data=res.result.records.map(item=>{
                        return {
                            ...item,
                            spin:false,
                            checkedStatus:item.optStatus=='DISABLED'?false:true,
                        }
                    });
                    this.ipagination.total=res.result.total;

                    console.log(this.data)
                }
            })
        },
    },
    mounted() {
        this.accountHttp()
        let userInfo=localStorage.getItem('pro__Login_Userinfo')
        if(userInfo){
            this.userInfo=JSON.parse(userInfo)        
        }
        this.tableListHttp();
    },
}
</script>

<style lang="scss" scoped>
.housekeeper{
    .OptinItem{
        display: inline-block;
        margin-right: 15px;
        .ok{
            margin-right: 15px;
        }
    }
    .OptinItem:first-child{
        margin-right: 10px;
    }
    .topOptions{
        padding: 15px 20px;
        background: white;
        border-radius: 2px;;
        .topOpt{
            width: 100%;
            margin-bottom: 10px;
        }
    }
    .optionBtn{
        // display: inline-block;
        
        float: right;
        .searchBtn{
            margin-right: 10px;
        }
    }
    .tableArea{
        margin-top: 12px;
        border-radius: 2px;
        padding: 0px 20px;
        background: white;
        .tableOption{
            padding: 20px 0;
        }
    }
}
</style>