<template>
    <div class="toutiaoBatch">
        <div>
            <p class="breadcrumb">
                <a-breadcrumb style="display:block;width:100%">
                    <a-breadcrumb-item ><span class="muen" @click="goStrategyList()">策略列表</span></a-breadcrumb-item>
                    <a-breadcrumb-item><span class="muen" @click="goPlanList()">计划列表</span></a-breadcrumb-item>
                    <a-breadcrumb-item>组列表</a-breadcrumb-item>
                </a-breadcrumb>
            </p>
        </div>
        
        <div class="toolbox-automate-rules-create-content_title"><h3>广告组</h3></div>
        
        <div class="topOptions">
            
            <span class="OptinItem">
                <a-select  style="width: 200px" v-model="groupStatus" @change="statusChange" placeholder="请选择组状态">
                    <a-select-option value="" >
                        不限
                    </a-select-option>
                   <a-select-option :value="1" >
                        投放中
                    </a-select-option>
                    <!-- <a-select-option value="2" >
                        超预算
                    </a-select-option>
                    <a-select-option value="3">
                        余额不足
                    </a-select-option> -->
                    <a-select-option :value="0">
                        已关停
                    </a-select-option>
                </a-select>
            </span>

            <span class="OptinItem">
                <a-input-search placeholder="组名称" v-model="groupName" style="width: 300px"  />
            </span>
            <span class="OptinItem">
                <a-input-search placeholder="组ID" v-model="groupId" style="width: 300px"  />
            </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">
                    <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>
                
            </div>
            <div class="table">
                <a-table
                    :columns="columns"
                    :data-source="data"
                    :rowSelection="{selectedRowKeys: selectedRowKeys,...rowSelection}"
                    bordered
                    :pagination="ipagination"
                    :loading="loading"
                    @change="sort"
                    :scroll="{'x':scrollX}"
                    
                >
                   
                    <span slot="switchStatus" 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>    
                        
                    </span>

                    <span slot="createStatus" 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>
                        
                    </span>
                    <span slot="planStatus" 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>
                        
                    </span>
                   
                    <span slot="createImg" slot-scope="text,record">
                        
                        <a-popover placement="right">
                            <template slot="content">
                                
                                <video :src="record.videoId_dictText" style="width:250px" controls  ></video>
                            </template>
                            <template slot="title">
                           
                            </template>
                            
                            <img :src="record.imageId_dictText" alt="" style="width:100px">
                        </a-popover>
                        
                    </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="status" slot-scope="text">
                      {{text | handlerStatus}}
                    </span>
                </a-table>
            </div>
        </div>
        
       
              
    <!-- </a-spin> -->
    </div>
</template>

<script>
import moment from 'moment';
import { getAction, postAction, downFile, downFilePost } from '@/api/manage';
// import { JeecgListMixin } from '@/mixins/ipagination'
// import editableCell from './editableCell'
import Treeselect from '@/views/modules/Statistics/components/Treeselect.vue'
import qs from 'qs'
let typeValue='预算'



const groupColumns = [
  {
    title: '开关',
    dataIndex: 'switchStatus',
    key: 'switchStatus',
    align: 'center',
    scopedSlots: { customRender: 'switchStatus' },
    fixed: 'left' ,
    width:80,
  },
  {
    title: '广告组名称',
    dataIndex: 'unitName',
    key: 'unitName',
    align: 'center',
    scopedSlots: { customRender: 'unitName' },
    fixed: 'left' ,
    width:150,
  },
  {
    title: '广告组ID',
    dataIndex: 'unitId',
    key: 'unitId',
    align: 'center',
    scopedSlots: { customRender: 'unitId' },
    fixed: 'left' ,
     width:100,
  },
  
  {
    title: '所属计划',
    dataIndex: 'campaignName',
    key: 'campaignName',
    align: 'center',
    scopedSlots: { customRender: 'campaignName' },   
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    align: 'center',
    scopedSlots: { customRender: 'status' },    
  },
 
];

const publicColumns = [
    {
          title: '消耗(元)',
          dataIndex: 'cost',
          width:150,
          tip: '广告在投放期间的花费总额',
          align: 'center',
          scopedSlots: { customRender: 'cost' },
        //   sorter: () => {}
        },
        {
          title: '封面曝光数',
          dataIndex: 'photoShow',
          tip: '广告在瀑布流被观看次数',
          align: 'center',       
          scopedSlots: { customRender: 'photoShow' },
        //   sorter:() => {}
        },
        {
          title: '封面点击数',
          dataIndex: 'photoClick',
          tip: '用户点击封面进入视频播放页的次数(数据会进行反作弊去重)',
          align: 'center',
        
          scopedSlots: { customRender: 'photoClick' },
        //   sorter: () => {}
        },
        {
          title: '素材曝光数',
          dataIndex: 'aclick',
          tip: '用户进入视频播放页观看的次数(数据会进行反作弊去重)',
          align: 'center',
       
          scopedSlots: { customRender: 'aClick' },
        //   sorter:() => {}
        },
        {
          title: '行为数',
          dataIndex: 'bclick',
          tip: '用户在视频播放页单击转化按钮的次数/展示数*100%',
          align: 'center',
        
          scopedSlots: { customRender: 'bClick' },
        //   sorter:() => {}
        },
        {
          title: '封面点击率',
          dataIndex: 'clickRate',
          tip: '封面点击数占封面展示数百分比',
          align: 'center',    
          scopedSlots: { customRender: 'clickRate' },
        //   sorter:() => {}
        },
        {
          title: '行为率',
          dataIndex: 'bClickRate',
          tip: '行为数占素材曝光数百分比',
          align: 'center',    
          scopedSlots: { customRender: 'bClickRate' },
        //   sorter:() => {}
        },
        {
          title: '平均千次封面曝光花费（元）',
          dataIndex: 'cpm',
          tip: '花费/封面曝光数*1000',
          align: 'center',    
          scopedSlots: { customRender: 'cpm' },
        //   sorter:() => {}
        },
        {
          title: '平均封面点击单价（元）',
          dataIndex: 'cpc',
          tip: '花费／封面点击数',
          align: 'center',    
          scopedSlots: { customRender: 'cpc' },
        //   sorter:() => {}
        },
        
        {
          title: '激活数',
          dataIndex: 'active',
          tip: '广告主回传的应用激活次数',
          align: 'center',    
          scopedSlots: { customRender: 'active' },
        //   sorter:() => {}
        },
        {
          title: '激活单价',
          dataIndex: 'activeCost',
          tip: '花费/激活数',
          align: 'center',    
          scopedSlots: { customRender: 'activeCost' },
        //   sorter:() => {}
        },
        {
          title: '下载完成激活率',
          dataIndex: 'activeRate',
          tip: '激活数/安卓下载完成数',
          align: 'center',    
          scopedSlots: { customRender: 'activeRate' },
        //   sorter:() => {}
        },
        {
          title: '注册数',
          dataIndex: 'register',
          tip: '付费金额/当日消耗',
          align: 'center',    
          scopedSlots: { customRender: 'register' },
        //   sorter:() => {}
        },
        {
          title: '注册成本',
          dataIndex: 'activeRegisterCost',
          tip: '当日消耗/当日回传注册数',
          align: 'center',    
          scopedSlots: { customRender: 'activeRegisterCost' },
        //   sorter:() => {}
        },
        {
          title: '注册率',
          dataIndex: 'activeRegisterRate',
          tip: '当日回传注册数/当日激活数',
          align: 'center',    
          scopedSlots: { customRender: 'activeRegisterRate' },
        //   sorter:() => {}
        },
        {
            title: '次留数',
            dataIndex: 'nextDayOpen',
            tip: '前一日激活用户在次日继续访问的PV',
            align: 'center',    
            scopedSlots: { customRender: 'nextDayOpen' },
            // sorter:() => {}
        },
        
        {
            title: '次留率',
            dataIndex: 'nextDayOpenRate',
            tip: '前一日激活用户在次日继续访问的PV/前一日激活数',
            align: 'center',    
            scopedSlots: { customRender: 'nextDayOpenRate' },
            // sorter:() => {}
        },
]

export default {
    name:'group-list',
    components: {
        // editableCell,
        Treeselect,
    },
    // mixins: [JeecgListMixin],
    data() {
        return {
            groupId:undefined,
            groupName:'',
            groupStatus:undefined,
            scrollX:3500,
            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;
                }
            },
            currentGroup:{},
            currentPlan:{},           

            spinning:false,
            moment,
           
            accountID:undefined,
            openID:undefined,
            treeData:[],
            // account:'',//媒体账号
            optionId:'',//input输入的id或关键词
            statusValue:undefined,
            dateValue:[],//日期选择框选择
            dateString:[],//--我赋值的是dateString
            tabkey:'group',//tab选中的页
            selectDisable:true,
            optValue:'',//操作设置的值 删除 暂停 开启
            visible: false,//出价里的弹出框
            
            
           
            //主页的表格
            data:[],
            columns:[...groupColumns,...publicColumns],
            selectedRowKeys:[],
            selectedRows:[],
            loading:false,
            editID:0,
            


            
            url: {
                planList: "/ai/list/pageCampaign",
                groupList:'/ai/list/pageUnit',
                strategyList:'/ai/list/pageStrategy'

            },


            xiugaiData:[],//存分别修改时候的数组
        }
    },
    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: {
        goStrategyList(){
            this.$parent.currentTabComponent='strategyList';
            this.$parent.currentStrategyId='';
            this.$parent.currentPlanId='';
            this.$parent.currentGroupId='';

        },
        goPlanList(){
            this.$parent.currentTabComponent='planList';
            this.$parent.currentGroupId='';
            this.$parent.currentPlanId='';

        },
        
        

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

        },
        //日期改变
        dateChange(date, dateString) {
            console.log(date, dateString);
            this.dateString=dateString;
        },
        disabledDate(current) {
            // console.log(current)
            return current && current > moment().subtract(1, 'day')
        },
        
        //查询按钮事件
        search(){
            this.ipagination.current=1
           this.getGroupList() 
        },
        //点击分页
        sort(pagination, filters, sorter, { currentDataSource }){
            
            this.ipagination.current=pagination.current;

            this.ipagination.pageSize=pagination.pageSize;
            this.getGroupList()
        },
      
        //状态改变
        switchChange(text,record){
            // this.spinning=true;
            console.log(text,record);
            
            record.spin=true;

            
            let ids=record.id;
            let putStatus=text?2:1;
            postAction('/kuaishou/batch/batchUpdateUnitStatus',{
                    accountId:record.accountId,
                    putStatus,
                    unitIds:[record.id],
                    userId:this.$parent.userId
            }).then((res)=>{
                    
                    record.spin=false;
                if(res.success){
                    this.getplanList()
                    this.$message.success(res.message)
                }else{
                    this.$message.error(res.message)
                }
            })
        },


        //改变批量操作的按钮
        changeSelectStatus(){
            this.selectDisable=false;
        },
        //批量操作下的启动 删除 暂停
        optChange(value){
            // console.log(value)
            this.optValue=value;
        },
        editGroupStatus(url){
            let ids='';
            this.selectedRows.forEach((item,index)=>{
                if(index==0){
                    ids=`${item.id}`
                }else{
                        ids+=`,${item.id}`
                }

            })
            let status=''
            if(this.optValue=='pause'){
                status='disable'
            }else if(this.optValue=='open'){
                status='enable'
            }else if(this.optValue=='delete'){
                status='delete'
            }
            postAction(url,qs.stringify({
                accountId:this.accountID,
                ids,
                status,
            })).then((res)=>{
                console.log(res);
                // this.loading=false
                this.optValue=undefined;
                if(res.success){
                    this.$message.success(res.message)
                    // this.data=[];
                    this.refreshCampaignList({
                        accountId:this.accountID,
                        name:this.optionId,
                        status:this.statusValue,
                        startDate:this.dateString[0],
                        endDate:this.dateString[1],
                        pageNo:this.ipagination.current,
                        pageSize:this.ipagination.pageSize,
                    })
                }else{
                    this.loading=false
                    // if(this.selectedRows.length>0){
                    //     this.selectedRows.forEach(item=>{
                    //         item.spin=false;
                    //     })
                    // }
                    this.selectedRowKeys=[];
                    this.selectedRows=[];
                    this.optValue=undefined;
                    this.$message.error(res.message)
                }
                
                
                
            })
        },
        //批量操作的确定按钮
        isOkHandle(){
            console.log(this.optValue&&this.selectedRowKeys.length>0)
            if(this.optValue&&this.selectedRowKeys.length>0){
                // this.selectedRows.forEach(item=>{
                //     item.spin=true;
                // })
            
                if(this.optValue=='pause'){   
                    this.loading=true;

                    postAction('/kuaishou/batch/batchUpdateUnitStatus',{
                            accountId:record.accountId,
                            putStatus:2,
                            unitIds:this.selectedRowKeys,
                            userId:this.$parent.userId
                    }).then((res)=>{
                            
                            record.spin=false;
                        if(res.success){
                            this.getGroupList()
                            this.$message.success(res.message)
                        }else{
                            this.$message.error(res.message)
                        }
                    })

                }else if(this.optValue=='open'){
                    this.loading=true;
                    postAction('/kuaishou/batch/batchUpdateUnitStatus',{
                        accountId:record.accountId,
                        putStatus:1,
                        unitIds:this.selectedRowKeys,
                        userId:this.$parent.userId
                    }).then((res)=>{
                            
                        record.spin=false;
                        if(res.success){
                            this.getGroupList()
                            this.$message.success(res.message)
                        }else{
                            this.$message.error(res.message)
                        }
                    })

                }
              
                // this.selectedRows=[];
                // this.selectedRowKeys=[];
                
            }
            
        },
        //确定删除
        confirm(e) {
            // console.log(e);
                this.loading=true;
                if(this.optValue=='delete'){
                    
                     if(this.tabkey=='group'){
                         this.editGroupStatus('/ctop/byteDanceCampaign/editStatus')
                    }else if(this.tabkey=='plan'){
                        if(this.selectedRowKeys.length>0){
                            this.selectedRows.forEach((item)=>{
                                item.optStatus='AD_STATUS_DELETE'
                            })
                        }
                        this.batchEditHttp('status',this.selectedRows)
                        this.$message.success('删除成功');
                    }else if(this.tabkey=='idea'){
                        this.editGroupStatus('/ctop/byteDanceCreative/editStatus');
                    }

                }



        },
        //取消删除
        cancel(e) {
            // console.log(e);
            // this.$message.error('删除成功');
        },

        getGroupList(){
            this.loading=true;
            postAction(this.url.groupList,{
                campaignId:this.$parent.currentPlanId,
                unitId:this.groupId,
                campaignName:this.groupName,
                campaignStatus:this.groupStatus,               
                pageNo:this.ipagination.current,
                pageSize:this.ipagination.pageSize
            }).then((res)=>{
                this.data=[]
                console.log(res)
                this.loading = false
                if(res.success){
                    this.ipagination.total = res.result.total
                    
                    res.result.list.forEach((item)=>{
                        item.key=item.id
                    })

                    this.data = res.result.list.map(item=>{

                        return {
                            ...item,
                            spin:false,
                            switchStatus:item.strategyState=='1'?true:false,
                        }
                    });
                    // console.log(this.data)
                    this.selectedRowKeys=[];
                }
            })
        },
        
    },
    mounted() {
       this.getGroupList()
    },
    
    activated() {
         this.getGroupList()
    },
    beforeDestroy() {
       
       

    },
    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 '-'
            }

        },

        handlerStatus(val){
            let str=''
            switch (val) {
                case 1:
                    str='投放中'
                    break;
                case 1:
                    str='已暂停'
                    break;
                case 1:
                    str='已删除'
                    break;
            
                default:
                    break;
            }
            return str
        }
    }
}
</script>
<style lang="less">
    .toutiaoBatch{
        .ant-timeline-item-head{
            background: rgb(240,242,245);
        }
        .muen{
            cursor: pointer;
        }
        .muen:hover{
            color: #1890ff;
        }

        .ant-steps-item-content{
            width: 160px;
        }
    }
</style>
<style lang="scss">

    #closeIcon{
         color: #0E74D2;
    }
    .toutiaoBatch{
        .ant-tag .anticon-close {      
            color: #1890ff;        
        }
        .ant-tag .anticon-close:hover{      
            color: rgba(0, 0, 0, 0.85);    
        }

    }
    
    .ant-tooltip-inner,.ant-tooltip,.ant-tooltip-arrow::before{
        background-color: #fff;
        color: #333;
    }
    #batchModal{
        .rules,.totalPrice{
            font-weight: 600;
        }

        .selectePlan{
            font-size: 14px;
            font-weight: 700;
            color: #333;
            padding: 20px 0;
        }
        .totalPrice{
            margin-left: 20px;
        }
        .modifyTable{
            margin-top: 20px;
            width: 100%;
            height: 400px;
            overflow: auto;
            font-weight: 600;
        }
    }
    #copyModal{
        .ant-modal-header{
            text-align: center;
        }
        .copyTip{
            font-size: 12px;
            color: #999;
        }
        .copyName{
            width: 118px;
            display: inline-block;
            text-align: right;
            .copyKeyStart{
                color: red;
            }
        }
        // font-weight: 600;
    }
</style>
<style lang="scss" scoped>
.toutiaoBatch{
    .breadcrumb{
            height: 22px;
            font-size: 12px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #000000;
            line-height: 22px;
        }
    background-color: #fff;
    padding: 10px 20px;
    position: relative;
    width: 100%;
    .OptinItem{
        display: inline-block;
        margin-right: 15px;
        .ok{
            margin-right: 15px;
        }
    }
    .OptinItem:first-child{
        margin-right: 10px;
    }
    .topOptions{
        padding: 15px 0;
        .topOpt{
            width: 100%;
            margin-bottom: 10px;
        }
    }
    .optionBtn{
        // display: inline-block;
        float: right;
        .searchBtn{
            margin-right: 10px;
        }
    }
    .tableArea{
        .tableOption{
            padding: 20px 0;
        }
    }
    .toolbox-automate-rules-create-content_title {
        background-color: #fff;
        display: flex;
        flex-flow: row nowrap;
        justify-content: flex-start;
        align-items: center;
        margin-bottom: 28px;
        h3 {
            font-size: 22px;
            margin: 0;
            font-weight: 400;
            height: 30px;
            line-height: 30px;
        }
    }

}

</style>