<script setup>
import { videoInterence,customInterence } from '@/api/api.js'
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import {formatter} from '@/hooks/mixins'
import $ from 'jquery'
/* 处理秒为时分秒 */
function formmaterTime(value) {
    var secondTime = parseInt(value);// 秒
    var minuteTime = 0;// 分
    var hourTime = 0;// 小时
    if(secondTime > 60) {//如果秒数大于60，将秒数转换成整数
        //获取分钟，除以60取整数，得到整数分钟
        minuteTime = parseInt(secondTime / 60);
        //获取秒数，秒数取佘，得到整数秒数
        secondTime = parseInt(secondTime % 60);
        //如果分钟大于60，将分钟转换成小时
        if(minuteTime > 60) {
                //获取小时，获取分钟除以60，得到整数小时
                hourTime = parseInt(minuteTime / 60);
                //获取小时后取佘的分，获取分钟除以60取佘的分
                minuteTime = parseInt(minuteTime % 60);
        }
    }
    var result = "" + parseInt(secondTime) + "秒";
    if(minuteTime > 0) {
        result = "" + parseInt(minuteTime) + "分" + result;
    }
    if(hourTime > 0) {
        result = "" + parseInt(hourTime) + "小时" + result;
    }
    return result;
}
const uploadurl = import.meta.env.VITE_APP_API_ROOT + '/resource/image/upload'//上传图片
const configHeader = {
    Authorization:localStorage.getItem('auth')
}
let search_txt= ref('')//关键字搜索
let total= ref(0)
let pageSize= ref(10)
let page_no= ref(1)
let selectId= ref([])//选中的
let tableData= ref([])//表格数据
let isShowdia= ref(false)
let dialog_title= ref('添加视频')
let isEdit= ref(false)
let videoloading= ref(false)//上传中
let tagList= ref([])//标签
let diaform = reactive({
    id:'',
    title:'',
    tag:[],
    video_url:'',
    duration:'',//时长
    post:''
})
const diaRule = reactive({
    title:[{ required: true, message: '标题不能为空', trigger: 'blur' }],
    tag:[{ required: true, message: '标签不能为空', trigger: 'change' }],
    // video_url:[
    // 	{ required: true, message: '视频地址不能为空', trigger: 'blur' },
    // ],
    post:[{ required: true, message: '视频封面不能为空', trigger: 'blur' }]
})
/* 获取列表 */
function getDataList() {
    videoInterence.getVideoList({
        PageSize:pageSize.value,
        CurrentIndex:page_no.value,
        KeyWord:search_txt.value
    }).then(res => {
        if(res.Ret === 200) {
            total.value = res.Data.Paging.Totals||0
            tableData.value = res.Data?.List||[]
        }
    })
}
/* 获取标签分类 */
function getTag() {
    videoInterence.tagList().then(res => {
        if(res.Ret === 200) {
            tagList.value = res.Data.List || [];
        }
    })
}
/* 关键字搜索 */
function searchHandle() {
    page_no.value = 1;
    getDataList();
}
/* 选择项发生变化 */
function selectchange(arr) {
    selectId.value = arr.map((item)=>{ return item.VideoId});
}
// 页码改变
function handleCurrentChange(page) {
    page_no.value = page;
    getDataList()
}
/* 添加视频 */
function addVideo() {
    dialog_title.value = '添加视频';
    isShowdia.value = true;
}
/* 取消弹窗 */
let diaformRef = ref(null)
function cancelHandle() {
    Object.assign(diaform,{
        id:'',
        title:'',
        tag:[],
        video_url:'',
        post:''
    })
    isEdit.value = false;
    videoloading.value = false;
    isShowdia.value = false;
    diaformRef.value?.resetFields();
}
/* 图片上传 */
function fileSelected2() {
    if( document.getElementById('file2').files[0] ){
        let hostfile = document.getElementById('file2').files[0];
        let size = Math.floor(hostfile.size / 1024 / 1024);
        if( size>200 ){
            ElMessage.error('上传文件大小不能大于200M！');
            hostfile = {};
            return false
        }
        if( hostfile.name.toLowerCase().includes('.jpg') || hostfile.name.toLowerCase().includes('.png')|| hostfile.name.toLowerCase().includes('.gif')){
            let form = new FormData();
            form.append('file',hostfile);  //hostfile.name
            customInterence.upload(form).then((res) => {
                if( res.Ret === 200 ){
                    diaform.post = res.Data.ResourceUrl||''
                }
                $("#file2").val('');
                hostfile = {};
            });
        }else{
            ElMessage.error('上传文件格式不正确！');
        }
    } 
}
function fileSelected(){  //选择视频上传
    if( document.getElementById('file').files[0] ){
        let hostfile = document.getElementById('file').files[0];
        if( hostfile.name.toLowerCase().includes('.mp4') || hostfile.name.toLowerCase().includes('.avi')){
            let form = new FormData();
            form.append('file',hostfile);  //hostfile.name
            videoloading.value=true;
            videoInterence.upload(form).then((res) => {
                if( res.Ret === 200 ){
                    diaform.video_url = res.Data.ResourceUrl;
                    diaform.duration = res.Data.PlaySeconds;
                }
                videoloading.value=false;
                $("#file").val('');
                hostfile = {};
            });
        }else{
            ElMessage.error('上传文件格式不正确！');
        }
    } 
}
function clickinput(type){  //上传模拟点击
    type==1?$("#file").click():$("#file2").click();
}

/* 保存视频 新增视频*/
function saveHandle() {
    diaformRef.value?.validate((valid) => {
        if (valid) {
            if(!isEdit.value) {
                videoInterence.saveVideo({
                    PlaySeconds:Number(diaform.duration),
                    TagsIdStr:diaform.tag.join(','),
                    Title:diaform.title,
                    VideoCoverUrl:diaform.post,
                    VideoUrl:diaform.video_url
                }).then(res => {
                    if(res.Ret === 200) {
                        ElMessage.success('新增视频成功')
                        cancelHandle();
                        page_no.value = 1;
                        getDataList();
                    }
                })
            }else {
                videoInterence.editVideo({
                    VideoId:Number(diaform.id),
                    PlaySeconds:Number(diaform.duration),
                    TagsIdStr:diaform.tag.join(','),
                    Title:diaform.title,
                    VideoCoverUrl:diaform.post,
                    VideoUrl:diaform.video_url
                }).then(res => {
                    if(res.Ret === 200) {
                        ElMessage.success('修改视频成功')
                        cancelHandle();
                        page_no.value = 1;
                        getDataList();
                    }
                })
            }
        }
    })
}
/* 编辑 */
function editHandle(item) {
    let tagArr = item.TagsId.split(',').map(item => {
        return Number(item);
    })
    Object.assign(diaform,{
        id:item.VideoId,
        title:item.Title,
        tag:tagArr,
        video_url:item.VideoUrl,
        duration:item.PlaySeconds,//时长
        post:item.VideoCoverUrl
    })
    isEdit.value = true;
    dialog_title.value = '修改视频';
    isShowdia.value = true;
}
/* 删除 */
function delHandle(item) {
    ElMessageBox.confirm('确认删除这条视频吗?','提示',{
        type:'warning'
    }).then(() => {
        videoInterence.delVideo({VideoId:parseInt(item.VideoId)}).then(res =>{
            if( res.Ret === 200 ){
                ElMessage.success( res.Msg );
                page_no.value = 1;
                getDataList();
            }
        });
    }).catch(() => {});
}
/* 取消发布 */
function canclepublish(item) {
    videoInterence.cancelPublish({
        VideoIds:String(item.VideoId)
    }).then(res => {
        if(res.Ret === 200) {
            ElMessage.success('取消发布成功！');
            item.Status = 0;
        }
    })
}
/* 弹窗发布 先保存再发布 */
function publishDia() {
    diaformRef.value?.validate((valid) => {
        if (valid) {
            if(!isEdit.value) {
                videoInterence.saveVideo({
                    PlaySeconds:Number(diaform.duration),
                    TagsIdStr:diaform.tag.join(','),
                    Title:diaform.title,
                    VideoCoverUrl:diaform.post,
                    VideoUrl:diaform.video_url
                }).then(res => {
                    if(res.Ret === 200) {
                        videoInterence.publish({
                            VideoIds:String(res.Data.VideoId)
                        }).then(res2 => {
                            if(res2.Ret === 200) {
                                ElMessage.success('视频发布成功！');
                                cancelHandle();
                                page_no.value = 1;
                                getDataList();
                            }
                        })
                    }
                })
            }else {
                videoInterence.publish({
                    VideoIds:String(diaform.id)
                }).then(res => {
                    if(res.Ret === 200) {
                        ElMessage.success('视频发布成功！');
                        cancelHandle();
                        page_no.value = 1;
                        getDataList();
                    }
                })
            }
        }
    })
}
/* 单条发布 */
function publishOwn(item) {
    videoInterence.publish({
        VideoIds:String(item.VideoId)
    }).then(res => {
        if(res.Ret === 200) {
            ElMessage.success('视频发布成功！');
            page_no.value = 1;
            getDataList();
        }
    })
}
/* 群发布 */
function publishHandle() {
    if(selectId.length) {
        videoInterence.publish({
            VideoIds:selectId.join(',')
        }).then(res => {
            if(res.Ret === 200) {
                ElMessage.success('视频发布成功！');
                page_no.value = 1;
                getDataList();
            }
        })
    }else {
        ElMessage.warning('请选择需要发布的视频！')
    }
}
onMounted(()=>{
    getTag();
    getDataList();
})
</script>
<template>
	<div class="videoList_contaier">
		<div class="videoList_top">
			<div>
				<el-button type="primary" @click="addVideo" style="margin-right:10px;width:80px;">添加</el-button>
				<!-- <el-button type="primary" style="width:80px;marginRight:10px;" @click="publishHandle">发布</el-button> -->
			</div>
			<el-input
			placeholder="关键字搜索"
			v-model="search_txt"
			style="max-width:520px"
			:prefix-icon="Search"
			@input="searchHandle"
			clearable>
			</el-input>
		</div>
		<div class="videoList_bot">
			<el-table
			:data="tableData" 
			@selection-change="selectchange" 
			element-loading-text="数据加载中..." 
			border
			style="width:100%;">
				<!-- <el-table-column type="selection" width="40" align="center"></el-table-column> -->
				<el-table-column prop="VideoCoverUrl" label="封面" align="center" width="240">
					<template #default="scope">
						<img :src="scope.row.VideoCoverUrl" alt="" style="width:150px;height:70px">
					</template>
				</el-table-column>
				<el-table-column label="标签" align="center" min-width="100">
					<template #default="scope">{{scope.row.TagsName}}</template>
				</el-table-column>
				<el-table-column label="标题" align="center" min-width="120">
					<template #default="scope">
						<span>{{scope.row.Title}}</span>
					</template>
				</el-table-column>
				<el-table-column prop="ModifyTime" label="更新时间" min-width="150" :formatter="formatter" align="center"></el-table-column>
				<el-table-column label="时长" min-width="110" align="center">
					<template #default="scope">
						<span>{{formmaterTime(scope.row.PlaySeconds)}}</span>
					</template>
				</el-table-column>
				<el-table-column label="状态" align="center">
					<template #default="scope">
						<span v-if="scope.row.Status===1" style="color:#46C371;">已发布</span>
						<span v-else>未发布</span>
					</template>
				</el-table-column>
				<el-table-column label="操作" align="center" min-width="130">
					<template #default="scope">
						<div v-if="scope.row.Status===0" style="color:#4099ef; font-size:24px;">
							<span class="editsty" style="marginRight:10px;" @click="publishOwn(scope.row)">发布</span>
							<span class="editsty" style="marginRight:10px;" @click="editHandle(scope.row)">编辑</span>
							<span class="deletesty" @click="delHandle(scope.row)">删除</span>
						</div>
						<div v-else>
							<span @click="canclepublish(scope.row)" style="color:red; cursor:pointer;">取消发布</span>
						</div>
					</template>
				</el-table-column>
			</el-table>
			<el-col :span="24" class="toolbar">
				<el-pagination 
				layout="total,prev,pager,next,jumper" 
				background 
				:current-page="page_no"
				@current-change="handleCurrentChange"
				:page-size="pageSize"
				:total="total"
				style="justify-content: flex-end;">
				</el-pagination>
			</el-col>
		</div>
		<!-- 添加视频弹窗 -->
		<el-dialog
		v-model="isShowdia"
		:close-on-click-modal="false"
		:modal-append-to-body='false'
		@close="cancelHandle"
		center
		width="700px">
			<template #header>
				<div style="display:flex;align-items:center;">
					<!-- <img :src="title=='添加视频'?$icons.pick:title=='申请解冻'?$icons.lock:title=='申请延期'?$icons.delay:''" style="color:#fff;width:16px;height:16px;marginRight:5px;"> -->
					<span style="font-size:16px;">{{dialog_title}}</span>
				</div>
			</template>
			<el-form 
			:model="diaform" 
			:rules="diaRule" 
			ref="diaformRef" 
			label-position="right" 
			label-width="100px"
			 @submit.native.prevent>
				<el-form-item prop="title" label="标题">
					<el-input type="text" v-model="diaform.title" placeholder="请输入标题" style="width:330px;"></el-input>
				</el-form-item>
				<el-form-item prop="tag" label="标签">
					 <el-checkbox-group v-model="diaform.tag">
						<el-checkbox-button v-for="item in tagList" :label="item.TagsId" :key="item.TagsId" >{{item.TagsName}}</el-checkbox-button>
					</el-checkbox-group>
				</el-form-item>
				<el-form-item prop="video_url" label="视频">
					<input type="file" name="file" @change="fileSelected()" id="file" class="true-file" style="display:none;">
					<el-input type="text" v-model="diaform.video_url" placeholder="上传视频" style="width:330px;"></el-input>
					<el-button type="primary" size="medium" @click.native="clickinput(1)" :loading="videoloading">{{videoloading?'上传中':'选择视频'}}</el-button>
					<span style="display:block;font-size:12px;height:24px;line-height:24px;color:#f00;" v-if="diaform.duration">(时长{{formmaterTime(diaform.duration)}})</span>
				</el-form-item>
				<el-form-item prop="post" label="封面">
					<input type="file" name="file2" @change="fileSelected2()" id="file2" class="true-file" style="display:none;">
					<el-button type="primary" @click="clickinput(2)" style="display:block;">选择封面</el-button>
					<img :src="diaform.post" alt="" v-if="diaform.post" width="215" height="100" style="margin-top:10px;">
				</el-form-item>
			</el-form>
			<div style="display:flex;justify-content:flex-end;margin:75px 0 50px;">
				<el-button type="primary" style="width:80px;margin-right:10px;" @click="saveHandle">保存</el-button>
				<el-button type="primary" plain style="width:80px;margin-right:10px;" @click="publishDia">发布</el-button>
				<el-button style="width:80px;" @click="cancelHandle">取消</el-button>
			</div>
		</el-dialog>
	</div>
</template>


<style lang='scss' scoped>
.videoList_contaier {
	.videoList_top {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 28px;
		padding: 20px 30px;
		background: #fff;
		border: 1px solid #ECECEC;
		border-radius: 4px;
		box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
	}
	.videoList_bot {
		min-height: calc(100vh - 335px);
		padding: 30px 30px 80px;
		background: #fff;
		position: relative;
		border: 1px solid #ECECEC;
		border-radius: 4px;
		box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
	}
}
</style>