<style lang="scss" scoped>
	.search-bar {
		display: flex;
		align-items: center;
	}
	.search-box p {
		display: inline-block;
		border: 1px solid #f2f2f2;
		border-radius: 5px;
		margin-right: 10px;
		padding: 5px 10px;
		cursor: pointer;
	}
</style>
<style>
	.showNumBox{
		margin: 10px 0;
	}
	.showNumBox .ant-card-body {
		display: flex;
		justify-content: center;
	}
	.showNumBox p,
	.showNumBox span {
		text-align: center;
		line-height: 40px;
		font-size: 30px;
		font-weight: 600;
		color: red;
		margin: 0;
	}
	.search-box .ant-card-body {
		padding: 5px 15px;
	}
	.showNumBox .ant-card-body .styleElse {
		line-height: 60px;
		height: 40px;
		font-size: 16px;
		font-weight: 400;
		margin-left: 10px;
	}
	.ant-modal-wrap .yincang .ant-modal-content .ant-modal-footer {
		display: none !important;
	}
	.yincang .ant-col-6 p {
		text-align: left;
		color: red;
		font-size: 16px;
		font-weight: 500;
	}
	.ant-table-thead div {
		font-weight: 700;
	}
	.tool-tip {
		position: absolute;
		top: 65px;
		right: 10px;
	}
</style>
<style lang='less'>
	.ant-card-head .ant-tabs-bar{
		padding: 0;
	}
	.search-box .ant-card-body {
		padding: 5px 15px;
	}
	.search-box{
		padding: 15px 10px;
	}
	.search-box p {
		display: inline-block;
		border: 1px solid #f2f2f2;
		border-radius: 5px;
		margin-right: 10px;
		padding: 5px 10px;
		cursor: pointer;
	}
	.statistics .ant-col-6 .ant-card-body .styleElse {
		line-height: 60px;
		height: 40px;
		font-size: 16px;
		font-weight: 400;
		margin-left: 10px;
	}
	.ant-modal-wrap .yincang .ant-modal-content .ant-modal-footer {
		display: none !important;
	}
	.yincang .ant-col-6 p {
		text-align: left;
		color: red;
		font-size: 16px;
		font-weight: 500;
	}
	.ant-table-thead div {
		font-weight: 700;
	}
	.tool-tip {
		position: absolute;
		top: 65px;
		right: 10px;
	}
	.statistics{
		.ant-card-bordered {
			border: none; 
		}
		.ant-card-head .ant-tabs {
			clear: both;
			margin-bottom: -13px;
			color: rgba(0, 0, 0, 0.65);
			font-weight: normal;
			font-size: 14px;
		}
		.duibi{
			position: absolute;
			right: 24px;
			top: 15px;
		}
		p {
			margin-bottom: 0;
		}
	}
</style>
<style lang="less">
	.newPlanStatic {
		.divider {
			height: 62px;
		}
		.showNumBox {
			background: white;
			overflow: hidden;
			margin: 15px 0;
			padding: 30px 0;
			text-align: center;
			.ant-card-body {
				padding-top: 0;
			}
			.title {
				font-size: 14px;
				font-family: PingFangSC-Regular, PingFang SC;
				font-weight: 400;
				color: #999999;
				line-height: 22px;
				display: inline-block;
			}
		}
		.tabbody {
			background: white;
			padding: 0 24px;
			margin-bottom: 15px;
			.ant-tabs-bar {
				margin: 0;
			}
		}
		.chartBox {
			background: white;
			padding: 20px 0;
		}
		.tableBody{
			background: white;
			padding: 20px ;
		}
	}
</style>
<template>
	<div class="newPlanStatic">
		<div class="tabbody">
		<a-tabs v-model="tabKey" @change="tabChange">
			<a-tab-pane :key="1" tab="头条">        
			</a-tab-pane>
			<a-tab-pane :key="2" tab="快手">       
			</a-tab-pane>
		</a-tabs>
		</div>
		
		<a-row>
		<a-col :span="24">
			
			<a-card :bordered="false" class="search-box">
			<div style="margin-bottom:20px">
				

				<span style="margin-left:20px">编导：</span>
				<a-select
				v-model="planId"
				show-search
				placeholder="请输入名字"
				option-filter-prop="children"
				style="width: 200px"
				:filter-option="filterOption"
				@change="operateChange"
				:disabled='operateDisabled'
				allowClear
				>
				<a-select-option v-for="item in designList" :key="item.user_id" :value="item.id">
					{{item.realname+'_('+item.roleName+')'}}
				</a-select-option>
				</a-select> 
				<span style="margin-left:20px">剪辑：</span>
				<a-select
				v-model="clipId"
				show-search
				placeholder="请输入名字"
				option-filter-prop="children"
				style="width: 200px"
				:filter-option="filterOption"
				@change="operateChange"
				:disabled='operateDisabled'
				allowClear
				>
				<a-select-option v-for="item in designList" :key="item.user_id" :value="item.id">
					{{item.realname+'_('+item.roleName+')'}}
				</a-select-option>
				</a-select> 
				<span style="margin-left:20px">拍摄：</span>
				<a-select
				v-model="shotId"
				show-search
				placeholder="请输入名字"
				option-filter-prop="children"
				style="width: 200px"
				:filter-option="filterOption"
				@change="operateChange"
				:disabled='operateDisabled'
				allowClear
				>
				<a-select-option v-for="item in designList" :key="item.user_id" :value="item.id">
					{{item.realname+'_('+item.roleName+')'}}
				</a-select-option>
				</a-select> 
				<a-button type='primary' style="position:absolute;right:20px" @click="search">查询</a-button>
				
			</div>
			<div style="margin-bottom:20px">
					<span>日期选择：</span>
					<a-range-picker
						@change="dateChange"
						v-model="dateRange"
						:disabled-date="disabledDate" 
						style="width:200px"                    
					/>
					<span style="margin-left:20px">数据维度：</span>
					<a-radio-group v-model="value" @change="dataTypeChange">
						<a-radio value="valid">
							有效视频
						</a-radio>
						<a-radio value="hot">
							爆款视频
						</a-radio>
						<a-radio value="onlie">
							上线时间
						</a-radio>
						
					</a-radio-group>
			</div>
			<div class="time"   >
				
				
			</div>

			</a-card>
		</a-col>
		</a-row>
		
		
		<a-row style="margin-bottom:15px;margin-top:12px">
			<a-col :span="24">
				<div class="tableBody">
					<a-table
						:columns="columns"
						:dataSource="dataTable"
						:pagination="ipagination"
						:loading="loading"
						bordered
						:scroll="{x: 2400}"
						@change="tableChange"
					>  
						<span slot="createImg" slot-scope="text, record">  
							<a-popover placement="right">
								<template slot="content">
									<video :src="record.url" style="width:250px" controls></video>
								</template>
								<template slot="title">
								</template>                       
								<img :src="record.coverUrl || noImg" alt="" style="width: 80px;height: 142px;">
							</a-popover>
						</span> 
						<span slot='companyName' slot-scope="text">{{ text || '未知' }}</span>
						<span slot='planName' slot-scope="text">{{ text || '-' }}</span>
						<span slot='clipName' slot-scope="text">{{ text || '-' }}</span>
						<span slot='shotName' slot-scope="text">{{ text || '-' }}</span>
						<span slot='totalCost' slot-scope="text">{{ text |decimalsHandle }}</span>
						<span slot='activeNum' slot-scope="text">{{ text |formatCurrency }}</span>
						<span slot='clickNum' slot-scope="text">{{ text |formatCurrency }}</span>
						<span slot='convertNum' slot-scope="text">{{ text |formatCurrency }}</span>
						<span slot='showNum' slot-scope="text">{{ text |formatCurrency }}</span>
						<span slot='aclick' slot-scope="text">{{ text |formatCurrency }}</span>
						<span slot='bclick' slot-scope="text">{{ text |formatCurrency }}</span>
						<span slot='photoClick' slot-scope="text">{{ text |formatCurrency }}</span>
						<span slot='photoShow' slot-scope="text">{{ text |formatCurrency }}</span>
						<span slot="faddishDate" slot-scope="text, record">{{ record.faddishDayNum < 15 ? text : '' }}</span>
						<span slot="effectDate" slot-scope="text, record">{{ record.effectDayNum < 8 ? text : '' }}</span>
						<span slot="action" slot-scope="text, record">
							<a @click="handleUpdateFace(record)">换脸</a>
						</span>
					</a-table> 
				</div>
			</a-col>
		</a-row>
		<!-- 换脸模块 -->
		<change-face
			:status="faceTypeStatus"
			:defaultList="faceChangeList"
			@closeface="handleFaceCloseModal"
			@sureface="handleFaceSureModal"
		>
		</change-face>
	</div>
</template>
<script>
import changeFace from '@/views/modules/Statistics/change-face/change-face';
import {TreeSelect} from 'ant-design-vue';
const SHOW_PARENT = TreeSelect.SHOW_PARENT;
import ARow from 'ant-design-vue/es/grid/Row';
import ACol from 'ant-design-vue/es/grid/Col';
import moment from 'moment';

import {getKsAccountReport, getKsDetail, getReportList} from '@api/video.js';
import {
    getAction,
    postAction,
    downFile,
    downFilePost
} from '@/api/manage';
import qs from 'qs';

let TTcolumns = [
    {
		title: '视频',
		dataIndex: 'createImg',
		scopedSlots: {customRender: 'createImg'},
		align: 'center',
		key:'userNcreateImgame'
  	},
	{
		title: '视频ID',
		dataIndex: 'videoCode',
		scopedSlots: {customRender: 'videoCode'},
		align: 'center',
		key: 'videoCode'
		
	},
	{
		title: '视频上线时间',
		dataIndex: 'stateDate',
		scopedSlots: {customRender: 'stateDate'},
		align: 'center',
		key: 'stateDate',
		width: 200
	},
	{
		title: '爆款达成日期',
		dataIndex: 'faddishDate',
		scopedSlots: {customRender: 'faddishDate'},
		align: 'center',
		key: 'faddishDate',
		width: 200
	},
	{
		title: '有效达成日期',
		dataIndex: 'effectDate',
		scopedSlots: {customRender: 'effectDate'},
		align: 'center',
		key: 'effectDate',
		width: 200
	},
	{
		title: '所属公司',
		dataIndex: 'companyName',
		scopedSlots: {customRender: 'companyName'},
		align: 'center',
		key: 'companyName',
		width: 200
	},
	{
		title: '策划名称',
		dataIndex: 'planName',
		scopedSlots: {customRender: 'planName'},
		align: 'center',
		key: 'planName',
		width: 200
	},
	{
		title: '剪辑名称',
		dataIndex: 'clipName',
		scopedSlots: {customRender: 'clipName'},
		align: 'center',
		key: 'clipName',
		width: 200
	},
	{
		title: '拍摄名称',
		dataIndex: 'shotName',
		scopedSlots: {customRender: 'shotName'},
		align: 'center',
		key: 'shotName',
		width: 200
	},
	{
		title: '总消耗',
		dataIndex: 'totalCost',
		scopedSlots: { customRender: 'totalCost' },
		align: 'center',
		key: 'totalCost'
	},
	{
		title: '点击数',
		dataIndex: 'clickNum',
		scopedSlots: {customRender: 'clickNum'},
		align: 'center',
		key: 'clickNum'
	},
	{
		title: '曝光数',
		dataIndex: 'showNum',
		scopedSlots: {customRender: 'showNum'},
		align: 'center',
		key: 'showNum'
	},
	{
		title: '激活数',
		dataIndex: 'activeNum',
		scopedSlots: {customRender: 'activeNum'},
		align: 'center',
		key: 'activeNum'
	},
	{
		title: '转化数',
		dataIndex: 'convertNum',
		scopedSlots: {customRender: 'convertNum'},
		align: 'center',
		key: 'convertNum'
	},
	{
		title: '操作',
		dataIndex: 'action',
		align: 'center',
		width: 120,
		fixed: 'right',
		scopedSlots: {customRender: 'action'}
	}
];
let KScolumns = [
	{
		title: '视频',
		dataIndex: 'createImg',
		scopedSlots: {customRender: 'createImg'},
		align: 'center',
		key: 'userNcreateImgame'
	},
	{
		title: '视频ID',
		dataIndex: 'videoCode',
		scopedSlots: {customRender: 'videoCode'},
		align: 'center',
		key: 'videoCode'
	},
	{
		title: '视频上线时间',
		dataIndex: 'stateDate',
		scopedSlots: {customRender: 'stateDate'},
		align: 'center',
		key: 'stateDate'
	},
	{
		title: '爆款达成日期',
		dataIndex: 'faddishDate',
		scopedSlots: {customRender: 'faddishDate'},
		align: 'center',
		key: 'faddishDate'
	},
	{
		title: '有效达成日期',
		dataIndex: 'effectDate',
		scopedSlots: {customRender: 'effectDate'},
		align: 'center',
		key: 'effectDate'
	},
	{
		title: '所属公司',
		dataIndex: 'companyName',
		scopedSlots: {customRender: 'companyName'},
		align: 'center',
		key: 'companyName'
	},
	{
		title: '策划名称',
		dataIndex: 'planName',
		scopedSlots: {customRender: 'planName'},
		align: 'center',
		key: 'planName'
	},
	{
		title: '剪辑名称',
		dataIndex: 'clipName',
		scopedSlots: {customRender: 'clipName'},
		align: 'center',
		key: 'clipName'
	},
	{
		title: '拍摄名称',
		dataIndex: 'shotName',
		scopedSlots: {customRender: 'shotName'},
		align: 'center',
		key: 'shotName'
	},
	{
		title: '总消耗',
		dataIndex: 'totalCost',
		scopedSlots: {customRender: 'totalCost'},
		align: 'center',
		key: 'totalCost'
	},
	{
		title: '封面曝光',
		dataIndex: 'photoShow',
		scopedSlots: {customRender: 'photoShow'},
		align: 'center',
		key: 'photoShow'
	},
	{
		title: '封面点击',
		dataIndex: 'photoClick',
		scopedSlots: {customRender: 'photoClick'},
		align: 'center',
		key: 'photoClick'
	},
	{
		title: '素材曝光',
		dataIndex: 'aclick',
		scopedSlots: {customRender: 'aclick'},
		align: 'center',
		key: 'aclick'
	},
	{
		title: '行为数',
		dataIndex: 'bclick',
		scopedSlots: {customRender: 'bclick'},
		align: 'center',
		key: 'bclick'
	},
	{
		title: '操作',
		dataIndex: 'action',
		align: 'center',
		width: 120,
		fixed: 'right',
		scopedSlots: {customRender: 'action'}
	}
];
export default {
    components: {
		changeFace,
        ACol,
        ARow
    },
    data() {
        return {
			faceChangeList: {},
			faceTypeStatus: false,
            exportloading: false,
            planId: undefined,
            shotId: undefined,
            clipId: undefined,
            dateRange: [moment().subtract(1,'weeks'),moment()],
            noImg: require('@/assets/noImg.png'),
            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;
					this.getNewPlan();
                }
            },
            value: 'valid',
            KSaccountList: [],
            TTaccountList: [],
            KSdesignList: [],
            TTdesignList: [],
            operateDisabled: false,
            userId: JSON.parse(localStorage.getItem('pro__Login_Userinfo')).value.id,
            duration: 1000,
            // treeselect的参数
            treeValue: [],
            treeData: [],
            SHOW_PARENT,
            type: 3,
            dateValue:[moment().subtract(7,'days'), moment()],
            operate: '',
            designList: [],
            tabKey: 1,
            loading: false,
            TTcolumns,
            KScolumns,
            columns: [...TTcolumns],    
            dataTable: [],
            tableTab: 1,
            newPlan: 0,
            effectPlan: 0,
            openOptions: false,
            target: '',
            order: 'desc'
        }
    },
    methods: {
        moment,
		handleUpdateFace(data) {
			this.faceTypeStatus = true;
			this.faceChangeList = data;
		},
		handleFaceCloseModal() {
			this.faceTypeStatus = false;
		},
		handleFaceSureModal() {
			this.search();
		},
        disabledDate(current) {           
            return current && current > moment();
        }, 
        dateChange(date, dateString) {
            // console.log(date,dateString)               
        },
        //导出报表
        exportExcel() {
            this.exportloading=true;
            let url='';
            if(this.tabKey==1){
                url='/ctop/bytedanceVideoEtlInfo/exportXls';
            }else {
                url='/ctop/kuaishouVideoEtlInfo/exportXls'
            }
            let nameType=''
            if(this.value=='valid'){
                nameType='有效视频'
            }else if(this.value=='hot'){
                nameType='爆款视频'
            }else if(this.value=='online'){
                nameType='视频上线时间'
            }

            downFilePost(url,qs.stringify({
                type:this.value,
                clipId:this.clipId,
                shotId:this.shotId,
                planId:this.planId,
                startData:this.dateRange[0].format('YYYY-MM-DD'),
                endData:this.dateRange[1].format('YYYY-MM-DD'),  
            })).then(res => {
                this.exportloading=false;
                let blob = new Blob([res], {
                    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                })
                let downloadElement = document.createElement('a')
                let href = window.URL.createObjectURL(blob) //创建下载的链接
                downloadElement.href = href
                downloadElement.download = moment().format('YYYY-MM-DD') + nameType+'.xlsx' //下载后文件名
                document.body.appendChild(downloadElement)
                downloadElement.click() //点击下载
                document.body.removeChild(downloadElement) //下载完成移除元素
                window.URL.revokeObjectURL(href) //释放掉blob对象
            })
        },
        dataTypeChange(e){
            this.getNewPlan()
        },
        filterOption(input, option){
            // console.log(input, option)
            return (
                option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
                );
        },
        // 快手头条的切换
        tabChange(key){
            this.treeValue=[];
            this.ipagination.current=1
           this.columns=this.tabKey==1?[...TTcolumns]:[...KScolumns]
            this.$nextTick(() => {
				this.getNewPlan();
			});
            
        },
        operateChange(value){
        console.log(value);
        if(value){
            this.accountDisabled=true;
            this.accountId=''
        }else{
            this.accountDisabled=false
        }
        },
        tableChange(pagination, filters, sorter, { currentDataSource }){
            console.log(pagination)
            this.ipagination.current=pagination.current;
            this.ipagination.pageSize=pagination.pageSize;
            this.getNewPlan()
        },
        // table区域的tab切换
        tableTabChange(key){
            if(key==1){
            
                this.columns=this.tabKey==1?[...TTcolumns]:[...KScolumns]
                this.target='new'
            }else{
                
                this.columns=this.tabKey==1?[...TTcolumnsVaild]:[...KScolumnsVaild]
                this.target='valid'
            }
            this.getNewPlan()
        },
        // 获取所有运营
        getAllOperator(key){
            let url='/sys/user/getAllDesigner'
            this.designList=[]
            getAction(url,{}).then(res=>{
                console.log(res);
                if(res.success){
                    this.designList=res.data
                }
            })
        },
        // 获取展示数据
        getNewPlan() {
			this.dataTable = [];
            let url = '';
            if(this.tabKey == 1) {
                // 头条
                url = '/ctop/bytedanceVideoEtlInfo/list';
            }
			else {
                // 快手
                url = '/ctop/kuaishouVideoEtlInfo/list';
            }
			this.ipagination.total = 0;
            this.loading = true;
            getAction(url, {
                type: this.value,
                clipId: this.clipId==''?null:this.clipId,
                shotId: this.shotId==''?null:this.shotId,
                planId: this.planId==''?null:this.planId,
                startDate: this.dateRange[0].format('YYYY-MM-DD'),
                endDate: this.dateRange[1].format('YYYY-MM-DD'),
                pageSize: this.ipagination.pageSize,
                pageNo: this.ipagination.current
            }).then(res => {
                this.loading = false;
                if(res.success) {
                    if(res.result) {
						this.dataTable = [...res.result.records];
                        this.ipagination.total = res.result.total;
                    }
                }
            })
        },
        // 查询按钮
        search(){
            // if(this.accountId || this.operate){
            //     this.echartSpinning=true;
            //     this.getNewPlan()
            // }else{
            //     this.$message.error('请选择具体账户或者运营')
            // }
            this.ipagination.current = 1;
            this.getNewPlan();
        },
    },
    watch: {
        dateValue(newName,oldName){
            this.search()
        },
    },
    computed: {
        newDate() {
        var myDate = new Date()
        myDate.getYear() //获取当前年份(2位)
        var n = myDate.getFullYear() //获取完整的年份(4位,1970-????)
        var m = myDate.getMonth() //获取当前月份(0-11,0代表1月)
        var d = myDate.getDate() //获取当前日(1-31)
        var day = myDate.getHours()
        return day
        }
    },
    mounted() {
        this.getNewPlan();
        this.getAllOperator()
    },
    filters: {
        toPercentage(val) {
			if (typeof val !== 'string') {
				return (val * 100).toFixed(2) + '%';
			}
			else {
				return val;
			}
        },
        //保留两位小数并且变成货币格式
        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) {
            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{
            return '-'
        }
            
        }
    }
}
</script>
