<template>
    <div class="video-manage-page">
        <div class="top-wrap">
            <el-button type="primary" @click="handleShowPop('')" v-if="navType!==2">添加视频</el-button>
            <div v-if="navType==2">
            <el-button type="primary" @click="handleShowImgPop('')" >添加视频封面</el-button>
            <el-select v-model="imgType" placeholder="请选择" clearable @change="imgTypeChange">
                <el-option label="线上路演" value="2"></el-option>
                <el-option label="5分钟小视频" value="1"></el-option>
            </el-select>
            </div>
            <el-input
                placeholder="关键词搜索"
                v-model="keyword"
                style="max-width:520px"
                @input="searchHandle"
                clearable
                v-if="navType!==2"
            >
				<i slot="prefix" class="el-input__icon el-icon-search"></i>
			</el-input>
        </div>
        <div class="list-wrap">
            <div class="nav-box">
                <span :class="navType==3?'active':''" @click="handleNavChange(3)">线上路演</span>
                <span :class="navType==1?'active':''" @click="handleNavChange(1)">5分钟小视频</span>
                <span :class="navType==2?'active':''" @click="handleNavChange(2)">视频封面库</span>
            </div>
            <el-table
                :data="list"
                border
                style="width: 100%"
                @sort-change="sortChangeHandle"
                v-if="navType!==2"
            >
                <el-table-column
                    prop="Title"
                    label="视频标题"
                    align="center"
                >
                    <template slot-scope="{row}">
                        <span style="cursor: pointer;color: #409eff;" @click="handlePreviewVideo(row)">{{row.Title}}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="VarietyTagName"
                    label="标签"
                    align="center"
                    v-if="navType==1"
                >
                </el-table-column>
                <el-table-column
                    prop="ChartPermissionNames"
                    label="品种"
                    align="center"
                    v-if="navType==3"
                >
                </el-table-column>
                <el-table-column
                    prop="AdminRealName"
                    label="创建人"
                    align="center"
                    v-if="navType==3"
                >
                </el-table-column>
                <el-table-column
                    prop="ModifyTime"
                    label="更新时间"
                    align="center"
                >
                </el-table-column>
                <el-table-column
                    prop="VideoSeconds"
                    label="时长"
                    align="center"
                >
                    <template slot-scope="{row}">
                        <span>{{row.VideoSeconds|formatDuration}}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="PublishState"
                    label="状态"
                    align="center"
                >
                    <template slot-scope="{row}">
                        <span :style="{color:row.PublishState==1?'#1dd411':''}">{{row.PublishState==1?'已发布':'未发布'}}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="ClickNum"
                    label="点击量"
                    sortable='custom'
                    align="center"
                >
                    <template slot-scope="{row}">
                        <span :style="{color:row.ClickNum?'#409eff':'',cursor: 'pointer'}" @click="handleShowClickNum(row)">{{row.ClickNum||'--'}}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="opt"
                    label="操作"
                    align="center"
                >
                    <template slot-scope="{row}">
                        <div v-if="row.PublishState==0">
                            <span style="cursor: pointer;color:#409eff;margin:0 5px;display: inline-block;" @click="handleOpt(row,'发布')">发布</span>
                            <span style="cursor: pointer;color:#409eff;margin:0 5px;display: inline-block;" @click="handleOpt(row,'编辑')">编辑</span>
                            <span style="cursor: pointer;color:#ff0000;margin:0 5px;display: inline-block;" @click="handleOpt(row,'删除')">删除</span>
                        </div>
                        <div v-else>
                            <span style="cursor: pointer;color:#ff0000;margin:0 5px;display: inline-block;" @click="handleOpt(row,'取消发布')">取消发布</span>
                            <span v-if="row.SendThsState==1&&row.SendTemplateState==1" style="cursor: pointer;color:#1dd411;margin:0 5px;display: inline-block;">已推送消息</span>
                            <span v-else style="cursor: pointer;color:#409eff;margin:0 5px;display: inline-block;" @click="handleOpt(row,'推送消息')">推送消息</span>

                            <!-- <span v-if="row.SendThsState==1" style="cursor: pointer;color:#1dd411;margin:0 5px;display: inline-block;">已推送客群</span>
                            <span v-else style="cursor: pointer;color:#409eff;margin:0 5px;display: inline-block;" @click="handleOpt(row,'推送客群')">推送客群</span>

                            <span v-if="row.SendTemplateState==1" style="cursor: pointer;color:#1dd411;margin:0 5px;display: inline-block;">已推送模版消息</span>
                            <span v-else style="cursor: pointer;color:#409eff;margin:0 5px;display: inline-block;" @click="handleOpt(row,'推送模版消息')">推送模版消息</span> -->
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <el-table
                :data="imgList"
                border
                style="width: 100%"
                v-if="navType==2"
            >
                <el-table-column
                    prop="CoverUrl"
                    label="封面图"
                    align="center"
                >
                    <template slot-scope="{row}">
                        <el-image 
                            style="width: 100px; height: 100px"
                            :src="row.CoverUrl" 
                            :preview-src-list="[row.CoverUrl]">
                        </el-image>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="CoverName"
                    label="封面名称"
                    align="center"
                />
                <el-table-column
                    prop="Type"
                    label="分类"
                    align="center"
                >
                    <template slot-scope="{row}">{{row.Type===1?'5分钟小视频':'线上路演'}}</template>
                </el-table-column>
                <el-table-column
                    prop="ModifyTime"
                    label="更新时间"
                    align="center"
                />
                <el-table-column
                    prop="opt"
                    label="操作"
                    align="center"
                >
                    <template slot-scope="{row}">
                        <span style="cursor: pointer;color:#409eff;margin:0 5px;display: inline-block;" @click="handleShowImgPop(row)">编辑</span>
                        <span style="cursor: pointer;color:#ff0000;margin:0 5px;display: inline-block;" @click="handleDelVideoCoverImg(row)">删除</span>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination 
				layout="total,prev,pager,next" 
				background
				:current-page="page"
				@current-change="handlePageChange"
				:page-size="pageSize" 
				:total="total"
				style="float:right;margin-top:20px">
			</el-pagination>
        </div>

        <!-- 添加/编辑视频弹窗 -->
        <el-dialog
            :visible.sync="showPop"
            :modal-append-to-body='false'
            v-dialogDrag
            width="50vw"
        >   
            <div slot="title">{{popData.type}}</div>
            <div>
                <el-form ref="form" :model="popData" label-width="80px" :rules="rules">
                    <el-form-item label="标题" prop="title">
                        <el-input v-model="popData.title" placeholder="请填写标题"></el-input>
                    </el-form-item>
                    <el-form-item label="标签" prop="tag" v-if="navType==1">
                        <el-cascader 
                            style="width:100%"
                            :options="options" 
                            :show-all-levels="false"
                            :props="{emitPath:false}"
                            v-model="popData.tag"
                            placeholder="请选择标签"
                        ></el-cascader>
                    </el-form-item>
                    <el-form-item label="品种" prop="permission" v-if="navType==3">
                        <el-cascader 
                            style="width:100%"
                            :options="perList" 
                            :show-all-levels="false"
                            :props="{emitPath:false,multiple: true,}"
                            v-model="popData.permission"
                            collapse-tags
                            placeholder="请选择品种"
                            :disabled="!!reportId && isReportHasPermission"
                        ></el-cascader>
                    </el-form-item>
                    <el-form-item label="视频" prop="videoUrl">
                        <div style="display:flex">
                        <el-input readonly v-model="popData.videoUrl" placeholder="请上传视频"></el-input>
                        <el-upload
                            style="display: inline-block;margin-left:10px"
                            action=""
                            accept=".mp4"
                            :http-request="handleUpload"
                            :before-upload="handelBeforeUploadVideo"
                            :show-file-list="false"
                            :disabled="startUpload"
                        >
                            <el-button type="primary" :loading="startUpload">上传视频</el-button>
                        </el-upload>
                        <el-progress type="circle" :percentage="percentage" width="40" style="margin-left:10px" v-if="startUpload"></el-progress>
                        </div>
                        <p style="color:#999">*注：要求视频格式为mp4，{{navType==1?'视频时长不超过10min，':''}}编码器为H.264</p>
                    </el-form-item>
                    <el-form-item label="关联报告" prop="reportUrl" v-if="navType==3">
                        <div style="display:flex">
                        <el-input readonly v-model="popData.reportUrl" placeholder="请选择关联报告">
                            <template slot='suffix' v-if="!!popData.reportUrl">
                                <i class="el-icon-circle-close" style="cursor: pointer;margin-right: 5px;" @click="reportRemove"></i>
                            </template>
                        </el-input>
                        <el-button type="primary" style="margin-left:10px;" @click="showReportDialog">关联报告</el-button>
                        </div>
                    </el-form-item>
                    <el-form-item label="封面" prop="imgUrl">
                        <!-- <el-input readonly v-model="popData.imgUrl" placeholder="请上传视频封面"></el-input>
                        <el-button type="primary">选择封面</el-button> -->
                        <el-image 
                            style="width: 120px; height: 120px"
                            :src="require('@/assets/img/icons/add-img.png')" 
                            v-if="!popData.imgUrl"
                            @click="handleshowChooseImgPop(navType==1?1:2)"
                        />
                        <div v-else class="pre-img-box">
                            <el-image 
                                style="width: 120px; height: 120px"
                                :src="popData.imgUrl" 
                                :preview-src-list="[popData.imgUrl]">
                            </el-image>
                            <span class="del" @click="popData.imgUrl=''">删除</span>
                        </div>
                        
                    </el-form-item>
                    <!-- <p style="padding-left:38px;color:#999">*注：视频格式支持mp4{{navType==1?'；视频时长不超过10min':''}}</p> -->
                    <div style="text-align:right;margin:50px 0">
                        <el-button type="primary" @click="handleSave">保存</el-button>
                        <el-button type="primary" plain @click="handleSave('publish')">发布</el-button>
                        <el-button @click="showPop=false">取消</el-button>
                    </div>
                </el-form>
            </div>
        </el-dialog>

        <!-- 点击量详情 -->
        <el-dialog
            :visible.sync="showClick"
            :modal-append-to-body='false'
            v-dialogDrag
            width="65vw"
            title="点击量详情"
        > 
            <div style="margin-bottom:118px">
                <div style="margin-bottom:10px">{{logVideoName}}</div>
                <div style="margin-bottom:10px">点击量：{{logCount}}</div>
                <el-table :data="logList" style="width: 100%; margin: 20px 0 30px" ref="clickNumberRef"
                border @sort-change="detailSortChange">
                    <el-table-column prop="RealName" label="用户姓名" align="center">
                        <template slot-scope="scope">
                            <span>{{scope.row.RealName||'--'}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="CompanyName" label="公司名称" align="center">
                        <template slot-scope="scope">
                            <span>{{scope.row.CompanyName||'--'}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="CompanyStatus" label="客户状态" align="center">
                        <template slot-scope="scope">
                            <span>{{scope.row.CompanyStatus||'--'}}</span>
                        </template>
                    </el-table-column>
                    <!-- <el-table-column prop="ClickNum" label="点击次数" align="center"> </el-table-column> -->
                    <el-table-column prop="SourceAgent" label="点击来源" align="center">
                        <template slot-scope="scope">
                            <span v-if="scope.row.SourceAgent==1">小程序</span>
                            <span v-else>pc</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="StopSeconds" label="播放时长" align="center" sortable="custom">
                        <template slot-scope="{row}">
                            {{row.StopSeconds|formatDuration}}
                        </template>
                    </el-table-column>
                    <el-table-column prop="CreateTime" label="点击时间" align="center" min-width="140"> </el-table-column>
                </el-table>
                <div>
                    <el-pagination 
                        layout="total,prev,pager,next" 
                        background
                        :current-page="logPage"
                        @current-change="handleLogPageChange"
                        :page-size="logPageSize" 
                        :total="logTotal"
                        style="float:right;margin-top:20px">
                    </el-pagination>
                </div>
            </div>
        </el-dialog>

        <!-- 上传视频封面弹窗 -->
        <el-dialog
            :visible.sync="showImgPop"
            :modal-append-to-body='false'
            v-dialogDrag
            width="50vw"
        > 
            <div slot="title">{{imgPopData.type}}</div>
            <div class="pop-wrap">
                <el-form ref="imgform" :model="imgPopData" label-width="80px" :rules="imgrules">
                    <el-form-item label="封面名称" prop="name">
                        <el-input v-model="imgPopData.name" placeholder="请填写封面名称"></el-input>
                    </el-form-item>
                    <el-form-item label="分类" prop="videoType">
                        <el-select v-model="imgPopData.videoType" placeholder="请选择" clearable style="width:60%">
                            <el-option label="线上路演" value="2"></el-option>
                            <el-option label="5分钟小视频" value="1"></el-option>
                        </el-select>
                    </el-form-item>
                
                    <el-form-item label="封面图" prop="imgUrl" :disabled="imgPopData.coverId!=0">
                            <el-input :disabled="imgPopData.coverId!=0" readonly v-model="imgPopData.imgUrl" placeholder="请上传视频封面"></el-input>
                            <el-upload
                                style="display: inline-block;"
                                action=""
                                accept="image/*"
                                :http-request="handleUploadImg"
                                :show-file-list="false"
                                :disabled="imgPopData.coverId!=0"
                            >
                                <el-button type="primary" :disabled="imgPopData.coverId!=0">选择封面</el-button>
                            </el-upload>
                    </el-form-item>
                    <div style="text-align:center;margin:50px 0">
                        <el-button @click="showImgPop=false">取消</el-button>
                        <el-button type="primary" @click="handleSaveImg">保存</el-button>
                    </div>
                </el-form>
            </div>
        </el-dialog>

        <!-- 选择视频封面弹窗 -->
        <el-dialog
            :visible.sync="chooseImgPop"
            :modal-append-to-body='false'
            v-dialogDrag
            width="60vw"
            title="视频封面库"
        >
            <div class="choose-img-wrap">
                <div style="margin-bottom:20px;font-size:16px;cursor: pointer;">
                    <span @click="handleshowChooseImgPop(2)" :style="{color:popImgType==2?'#2D8CF0':'#666666'}">线上路演</span> | 
                    <span @click="handleshowChooseImgPop(1)" :style="{color:popImgType==1?'#2D8CF0':'#666666'}">5分钟小视频</span>
                </div>
                <div class="list">
                    <div 
                        class="item" 
                        v-for="item in popImgList" 
                        :key="item.CommunityVideoCoverId"
                        @click="handleChooseImg(item)"
                    >
                        <el-image 
                            style="width: 120px; height: 120px"
                            :src="item.CoverUrl"
                        >
                        </el-image>
                        <div>{{item.CoverName}}</div>
                    </div>
                </div>
                <div>
                    <el-pagination 
                        layout="total,prev,pager,next" 
                        background
                        :current-page="imgPopPage"
                        @current-change="handleimgPopPageChange"
                        :page-size="imgPopPagesize" 
                        :total="imgPopTotal"
                        style="float:right;margin-top:20px">
                    </el-pagination>
                </div>
            </div>
            
        </el-dialog>
        <!-- 预览视频弹窗 -->
        <el-dialog
            :visible.sync="previewPop"
            :modal-append-to-body='false'
            v-dialogDrag
            width="60vw"
            :title="previewPopTitle"
            @close="endingPreview"
        >
         <video style="width: 100%;height: 100%;max-height: 70vh;outline: none;" 
         controls :src="previewVideoUrl" autoplay ref="previewVideo">
            您的浏览器暂不支持,请更换浏览器
         </video>   
        </el-dialog>

        <!-- 关联报告弹窗 -->
        <connective-report-dialog
          :isShow="isShowReportDialog"
          :reportId="this.reportId"
          @reportChange="setReportUrl"
          @cancel="isShowReportDialog=false"
        />
    </div>
</template>

<script>
import MD5 from 'js-md5'
import {getOSSSign} from '@/api/api.js'
import {customInterence,videoInterface,departInterence} from '@/api/api.js'
import connectiveReportDialog from './components/connectiveReportDialog.vue'
let ALOSSINS=null //阿里云上传实例
let ALOSSAbortCheckpoint=null //阿里云上传实例中断点
export default {
  components: { connectiveReportDialog },
    filters:{
        formatDuration(e){
            let tem=parseInt(e)
            let min=parseInt(tem/60)
            let sen=parseInt(tem%60)
            if(min>0){
                return `${min}分${sen}秒`
            }else{
                return `${sen}秒`
            }
        }
    },
    watch: {
        showPop(n){
            //关闭上传视频弹窗时取消正在上传的动作
            if(!n&&ALOSSAbortCheckpoint){
                console.log('终止上传');
                ALOSSINS.abortMultipartUpload(ALOSSAbortCheckpoint.name,ALOSSAbortCheckpoint.uploadId)
            }
        }
    },
    data() {
        return {
            keyword:'',
            list:[],
            page:1,
            pageSize:15,
            total:0,
            options:[],
            perList:[],
            SortParam:'',
            SortType:'',

            navType:3,//1视频库 2视频封面库 3线上路演
            showImgPop:false,
            imgList:[],
            imgType:'',
            imgPopData:{
                type:'添加封面',
                coverId:0,
                imgUrl:'',
                name:'',
                videoType:''
            },

            showPop:false,
            popData:{
                type:'添加视频',
                VideoId:0,
                title:'',
                tag:'',
                videoUrl:'',
                VideoSeconds:0,//时长
                imgUrl:'',
                permission:'',
                reportUrl:''
            },

            rules:{
                title:[{required: true, message: '请输入标题', trigger: 'blur'}],
                tag:[{required: true, message: '请选择标签', trigger: 'change'}],
                videoUrl:[{required: true, message: '请上传视频', trigger: 'change'}],
                imgUrl:[{required: true, message: '请上传视频封面', trigger: 'change'}],
                permission:[{required: true, message: '请选择品种', trigger: 'change'}]
            },
            imgrules:{
                name:[{required: true, message: '请输入封面名称', trigger: 'blur'}],
                imgUrl:[{required: true, message: '请上传视频封面', trigger: 'change'}],
                videoType:[{required: true, message: '请选择类型', trigger: 'change'}]
            },
            percentage:0,
            startUpload:false,//开始上传

            showClick:false,
            logVideoId:0,
            logVideoName:'',
            logPage:1,
            logPageSize:10,
            logTotal:0,
            logList:[],
            logCount:0,
            logSortType:'',

            chooseImgPop:false,
            imgPopPage:1,
            imgPopPagesize:20,
            imgPopTotal:0,
            popImgList:[],
            popImgType:1,
            // ---------------预览视频弹窗
            previewPop:false,
            previewPopTitle:"",
            previewVideoUrl:"",
            
            isShowReportDialog:false,//关联报告弹窗
            reportId:0,
            // 报告是否关联品种
            isReportHasPermission:false
        }
    },
    created() {
        this.getVideoList()
        this.getTagList()
        this.getPermissionList()
    },
    methods: {
        handleNavChange(type){
            this.page=1
            this.total=0
            this.navType=type
            this.keyword=''
            if(type==2){
                this.handleGetVideoCoverImgList()
            }else{
                this.getVideoList()
            }
            
        },

        searchHandle(){
            this.page=1
            this.getVideoList()
        },
        handlePageChange(page){
            this.page=page
            if(this.navType!==2){
                this.getVideoList()
            }else{
                this.handleGetVideoCoverImgList()
            }
            
        },
        async getVideoList(){
            const params={
                Keywords:this.keyword,
                PageSize:this.pageSize,
                CurrentIndex:this.page,
                SortParam:this.SortParam,
                SortType:this.SortType
            }
            const res=this.navType===1?await videoInterface.videoList(params):await videoInterface.roadVideoList(params)
            if(res.Ret===200){
                this.total=res.Data.Paging.Totals 
                this.list=res.Data.List||[]
            }
        },

        //获取标签数据
        async getTagList(){
            /* const res=await customInterence.authList({CompanyType:'ficc'})
            if(res.Ret===200){
                let arr=res.Data.List||[]
                this.options=arr.map(item => {
                    let obj={}
                    obj.value=item.ClassifyName
                    obj.label=item.ClassifyName
                    obj.children=item.Items.map(_item=>{
                        return {value:_item.ChartPermissionId,label:_item.PermissionName}
                    })
                    return obj
                }).filter(item=>item.value!='市场策略');
            } */
            //接口更换
            const res = await departInterence.getTagTree()
            if(res.Ret === 200){
                let arr=res.Data||[]
                this.options=arr.map(item => {
                    let obj={}
                    obj.value=item.classify_name
                    obj.label=item.classify_name
                    obj.children=item.tags.map(_item=>{
                        return {value:_item.tag_id,label:_item.tag_name}
                    })
                    return obj
                })
            }
        },

        //获取品种权限数据
        async getPermissionList(){
            const res=await videoInterface.getPermissionList()
            if(res.Ret===200){
                const arr=res.Data.List||[]
                this.perList=arr.map(item => {
                    if(!(item && item.List)){
                        // 无(子)品种
                        return null
                    }
                    let obj={}
                    obj.value=item.ClassifyName
                    obj.label=item.ClassifyName
                    obj.children=item.List.map(_item=>{
                        return {value:_item.ChartPermissionID,label:_item.ChartPermissionName}
                    })
                    return obj
                }).filter(Boolean)
            }
        },

        //新增\编辑视频
        handleShowPop(item){
            console.log(item);
            this.popData.title=''
            this.popData.tag=''
            this.popData.videoUrl=''
            this.popData.imgUrl=''
            this.popData.VideoSeconds=0
            this.popData.VideoId=0
            this.popData.permission=''
            this.popData.reportUrl=''
            this.isReportHasPermission=false
            if(!item){
                this.popData.type='添加视频'
            }else{
                this.popData.type='编辑视频'
                this.popData.title=item.Title
                this.popData.tag=item.VarietyTagId
                this.popData.videoUrl=item.VideoUrl
                this.popData.imgUrl=item.CoverImgUrl
                this.popData.VideoSeconds=item.VideoSeconds
                this.popData.VideoId=item.CommunityVideoId
                if(this.navType===3){
                    this.$nextTick(()=>{
                        this.popData.permission=item.ChartPermissionIds.split(',').map(it => +it)
                    })
                    this.popData.VideoId=item.RoadVideoId
                    this.setReportUrl({ReportId:item.ReportId || 0,Title:item.ReportTitle || '',
                                        PermissionIds:item.ChartPermissionIds?item.ChartPermissionIds.split(','):[]})
                }
            }
            this.showPop=true
            this.$nextTick(()=>{
                this.$refs.form.clearValidate();
            })
            
        },
        //获取视频时长的promise
        handleGetDuration(file){
            return new Promise((resolve,reject)=>{
                const fileUrl=URL.createObjectURL(file)
                const audioEl=new Audio(fileUrl)
                audioEl.addEventListener('loadedmetadata',(e)=>{
                    console.log('e.path',e.path)
                    console.log('e.composedPath',e.composedPath())
                    console.log('获取视频时长',e.composedPath()[0].duration);
                    console.log(audioEl.duration);
                    const t=e.composedPath()[0].duration
                    resolve(t)
                })
            })
        },

        //上传视频判断格式
        handelBeforeUploadVideo(e){
            if(e.type!='video/mp4'){
                this.$message.warning('上传失败，上传视频格式不正确')
                return false
            }
        },

        // 上传视频
        async handleUpload(e){
            const duration=await this.handleGetDuration(e.file)
            if(duration>600&&this.navType===1){
                this.$message.warning('视频时长不得超过10分钟')
                return 
            }
            console.log(e);
            this.popData.VideoSeconds=duration
            const res=await getOSSSign()
            if(res.Ret===200){
                let accessKeyId=res.Data.AccessKeyId
                let accessKeySecret=res.Data.AccessKeySecret
                let stsToken=res.Data.SecurityToken
                this.handleUploadToOSS(e.file,accessKeyId,accessKeySecret,stsToken)
            }
            
        },
        //上传到阿里云
        async handleUploadToOSS(file,accessKeyId,accessKeySecret,stsToken){
            this.startUpload=true
            ALOSSINS=new OSS({
                // yourRegion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
                region: "oss-cn-shanghai",
                // 从STS服务获取的临时访问密钥（AccessKey ID和AccessKey Secret）。
                accessKeyId: accessKeyId,
                accessKeySecret: accessKeySecret,
                // 从STS服务获取的安全令牌（SecurityToken）。
                stsToken: stsToken,
                // 填写Bucket名称，例如examplebucket。
                bucket: "hzchart",
                endpoint:'hzstatic.hzinsights.com',
                cname:true,
                timeout:600000000000
            });
            // 生成文件名
            const t=new Date().getTime().toString()
            const temName=`static/yb/video/${MD5(t)}.${file.type.split('/')[1]}`
            console.log(temName);

            const options = {
                // 获取分片上传进度、断点和返回值。
                progress: (p, cpt, res) => {
                    console.log(p);
                    ALOSSAbortCheckpoint=cpt
                    this.percentage=parseInt(p*100)
                },
                // 设置并发上传的分片数量。
                parallel: 10,
                // 设置分片大小。默认值为1 MB，最小值为100 KB。
                partSize: 1024 * 1024 * 10, // 10MB
            };
            try {
                const res=await ALOSSINS.multipartUpload(temName,file,{...options})
                console.log('上传结果',res);
                if(res.res.status===200){
                    this.popData.videoUrl='https://hzstatic.hzinsights.com/'+res.name
                    this.startUpload=false
                    this.percentage=0
                    ALOSSAbortCheckpoint=null
                }
            } catch (error) {
                console.log('上传到阿里云失败',error);
                if(error.name!=="cancel"){//不是取消上传的则给错误提示
                    this.$message.warning('上传失败，请刷新重试')
                }
                this.startUpload=false
                this.percentage=0
                ALOSSAbortCheckpoint=null
            }
        },

        //上传封面
        async handleUploadImg(e){
            console.log(e);
            let form = new FormData()
            form.append("file", e.file)
            const res=await customInterence.upload(form)
            if(res.Ret===200){
                this.imgPopData.imgUrl=res.Data.ResourceUrl
            }
        },

        // 保存
        handleSave(type){
            this.$refs.form.validate(async (valid)=>{
                if(valid){
                    let params={
                        VideoId: this.popData.VideoId,
                        Title: this.popData.title,
                        CoverImgUrl: this.popData.imgUrl,
                        VideoUrl: this.popData.videoUrl,
                        VideoSeconds: this.popData.VideoSeconds.toString(),
                        ReportId:this.reportId
                    }
                    let res=null
                    if(this.navType===1){
                        params.VarietyTagId=Number(this.popData.tag),
                        res=await videoInterface.saveVideo(params)
                    }else if(this.navType===3){
                        params.ChartPermissionIds=this.popData.permission.join(',')
                        res=await videoInterface.roadSaveVideo(params)
                    }
                    if(res.Ret===200){
                        if(type==='publish'){
                            this.handlePublished({VideoId:this.navType===1?res.Data.CommunityVideoId:res.Data.RoadVideoId,PublishState:1})
                        }else{
                            this.$message.success('保存成功')
                            this.getVideoList()
                        }
                        this.showPop=false
                    }
                }
            })
        },

        //发布\取消发布
        async handlePublished({VideoId,PublishState}){
            let res=this.navType===1?await videoInterface.published({VideoId,PublishState}):await videoInterface.roadPublished({VideoId,PublishState})
            if(res.Ret===200){
                if(PublishState==1){
                    this.$message.success('发布成功')
                }else{
                    this.$message.success('取消发布成功')
                }
                this.getVideoList()
            }
        },

        // 删除
        async handelDel(item){
            const res=this.navType===1?await videoInterface.delVideo({VideoId:item.CommunityVideoId}):await videoInterface.roadDelVideo({VideoId:item.RoadVideoId})
            if(res.Ret===200){
                this.$message.success('删除成功')
                this.getVideoList()
            }
        },

        //推送客群
        async handleSendMsg(item){
            const res=this.navType===1?await videoInterface.sendMsg({VideoId:item.CommunityVideoId}):await videoInterface.roadSendMsg({VideoId:item.RoadVideoId})
            if(res.Ret===200){
                this.$message.success('推送成功')
                this.getVideoList()
            }
        },

        //推送模版消息
        async handleSendTempMsg(item){
            const res=this.navType===1?await videoInterface.sendTempMsg({VideoId:item.CommunityVideoId}):await videoInterface.roadSendTempMsg({VideoId:item.RoadVideoId})
            if(res.Ret===200){
                this.$message.success('推送成功')
                this.getVideoList()
            }
        },

        //推送消息
        async handleMsgPush(item){
            const res=this.navType===1?await videoInterface.msgPush({VideoId:item.CommunityVideoId}):await videoInterface.roadMsgPush({VideoId:item.RoadVideoId})
            if(res.Ret===200){
                this.$message.success('推送成功')
                this.getVideoList()
            }
        },

        handleOpt(item,type){
            if(type==='发布'){
                this.handlePublished({VideoId:this.navType===1?item.CommunityVideoId:item.RoadVideoId,PublishState:1})
                return
            }

            if(type==='编辑'){
                this.handleShowPop(item)
                return
            }

            if(type==='删除'){
                this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.handelDel(item)
                }).catch(() => {
                             
                });
                return
            }

            if(type==='取消发布'){
                this.handlePublished({VideoId:this.navType===1?item.CommunityVideoId:item.RoadVideoId,PublishState:0})
                return 
            }

            if(type==='推送客群'){
                this.handleSendMsg(item)
                return  
            }

            if(type==='推送模版消息'){
                this.handleSendTempMsg(item)
                return  
            }

            if(type==='推送消息'){
                this.handleMsgPush(item)
            }

        },

        sortChangeHandle({prop,order}){
            console.log(prop,order)
            this.SortType = order==='ascending'?'asc':order==='descending'?'desc':''
            if(this.SortType.length){
                this.SortParam=prop
            }else{
                this.SortParam=''
            }
            this.getVideoList()
        },

        handleShowClickNum(item){
            this.logVideoId=this.navType===1?item.CommunityVideoId:item.RoadVideoId
            this.logVideoName=item.Title
            this.showClick=true
            this.logPage=1
            this.logList=[]
            this.logTotal=0
            this.logSortType=''
            this.$refs.clickNumberRef && this.$refs.clickNumberRef.clearSort()
            this.getVideoLogslist()
        },

        // 获取点击量详情
        async getVideoLogslist(){
            const params={
                CurrentIndex:this.logPage,
                PageSize:this.logPageSize,
                VideoId:Number(this.logVideoId),
                SortType: this.logSortType
            }
            const res=this.navType===1?await videoInterface.videoLogList(params):await videoInterface.roadVideoLogList(params)
            if(res.Ret===200){
                this.logTotal=res.Data.Paging.Totals 
                this.logCount=res.Data.Count
                this.logList=res.Data.List||[]
            }
        },
        // 点击量详情 - 表格排序
        detailSortChange({ order}){
            this.logSortType=order==='ascending'?'2':order==='descending'?'1':''
            this.getVideoLogslist()
        },
        handleLogPageChange(e){
            this.logPage=e
            this.getVideoLogslist()
        },

        //视频封面类型筛选
        imgTypeChange(){
            this.page=1
            this.imgList=[]
            this.handleGetVideoCoverImgList()
        },
        //获取视频封面列表
        async handleGetVideoCoverImgList(){
            const res=await videoInterface.videoCoverImgList({
                PageSize:this.pageSize,
                CurrentIndex:this.page,
                Type:this.imgType?this.imgType:0
            })
            if(res.Ret===200){
                this.total=res.Data.Paging.Totals 
                this.imgList=res.Data.List||[]
            }
        },

        //显示添加视频封面弹窗
        handleShowImgPop(item){
            this.imgPopData.name=''
            this.imgPopData.imgUrl=''
            this.imgPopData.coverId=0
            if(!item){
                this.imgPopData.type='添加封面'
            }else{
                this.imgPopData.type='编辑封面'
                this.imgPopData.name=item.CoverName
                this.imgPopData.imgUrl=item.CoverUrl
                this.imgPopData.coverId=item.CommunityVideoCoverId
                this.imgPopData.videoType=item.Type.toString()
            }
            this.showImgPop=true
            this.$nextTick(()=>{
                this.$refs.imgform.clearValidate();
            })
        },

        //保存视频封面
        handleSaveImg(){
            this.$refs.imgform.validate((valid)=>{
                if(valid){
                    let params={
                        CoverId:Number(this.imgPopData.coverId),
                        CoverName:this.imgPopData.name,
                        CoverUrl:this.imgPopData.imgUrl,
                        Type:Number(this.imgPopData.videoType)
                    }
                    videoInterface.videoCoverImgSave(params).then(res=>{
                        if(res.Ret==200){
                            this.handleGetVideoCoverImgList()
                            if(this.imgPopData.type=='添加封面'){
                                this.$message.success('添加成功')
                            }else{
                                this.$message.success('编辑成功')
                            }
                            this.showImgPop=false
                        }
                    })
                }
            })
        },

        //删除视频封面
        handleDelVideoCoverImg(item){
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                    videoInterface.videoCoverImgDel({
                        CoverId:Number(item.CommunityVideoCoverId)
                    }).then(res=>{
                        if(res.Ret===200){
                            this.$message.success('删除成功')
                            this.handleGetVideoCoverImgList()
                        }
                    })
            }).catch(() => {
                             
            });
        },
        
        //显示选择视频封面列表
        handleshowChooseImgPop(type){
            this.imgPopPage=1
            this.popImgType=type
            this.handleGetPopImgList()
            this.chooseImgPop=true
        },

        //弹窗中选择视频封面的列表数据
        async handleGetPopImgList(){
            const res=await videoInterface.videoCoverImgList({
                PageSize:this.imgPopPagesize,
                CurrentIndex:this.imgPopPage,
                Type:this.popImgType
            })
            if(res.Ret===200){
                this.imgPopTotal=res.Data.Paging.Totals 
                this.popImgList=res.Data.List||[]
            }
        },

        handleChooseImg(item){
            this.popData.imgUrl=item.CoverUrl
            this.chooseImgPop=false
        },

        handleimgPopPageChange(e){
            this.imgPopPage=e
            this.handleGetPopImgList()
        },
        // 预览视频
        handlePreviewVideo({Title,VideoUrl}){
            this.$refs.previewVideo && this.$refs.previewVideo.play()
            this.previewPopTitle = Title
            this.previewVideoUrl = VideoUrl
            this.previewPop = true
        },
        // 结束预览弹窗关闭回调 -- 暂停视频
        endingPreview(){
            this.$refs.previewVideo && this.$refs.previewVideo.pause()
        },
        // 删除关联的报告
        reportRemove(){
            this.popData.reportUrl=''
            this.reportId = 0
            this.popData.permission=''
        },
        //打开关联报告弹窗
        showReportDialog(){
          this.isShowReportDialog = true
        },
        //设置关联报告链接
        setReportUrl(item){
          this.reportId = item.ReportId
          this.popData.reportUrl = item.Title
          this.popData.permission=item.PermissionIds
          this.isReportHasPermission = item.PermissionIds && item.PermissionIds.length>0
          this.isShowReportDialog = false
        }
    },
}
</script>

<style lang="scss">
.video-manage-page{
    .list-wrap{
        .el-image:hover{
            border:1px solid #409eff;
        }
    }
}
</style>

<style lang="scss" scoped>
.video-manage-page{
    .top-wrap{
        height: 80px;   
        border: 1px solid #DCDFE6;
        background-color: #fff;
        border-radius: 4px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 30px;
    }
    .list-wrap{
        border: 1px solid #DCDFE6;
        background-color: #fff;
        border-radius: 4px;
        margin-top: 30px;
        padding: 30px;
        padding-bottom: 80px;
        .nav-box{
            margin-bottom: 30px;
            span{
                padding-bottom: 5px;
                font-size: 16px;
                display: inline-block;
                margin-right: 30px;
                cursor: pointer;
            }
            .active{
                color: #409eff;
                border-bottom: 2px solid #409eff;
            }
        }
    }
    // .pop-wrap{

    // }
    .choose-img-wrap{
        padding-bottom: 80px;
        .list{
            display:flex;
        flex-wrap:wrap;
        }
        .item{
            flex-shrink:0;
            text-align:center;
            margin-right:20px;
            margin-bottom:20px;
            border: 1px solid rgb(199, 198, 198);
            padding: 5px;
            border-radius: 4px;
        }
    }
    .pre-img-box{
        position: relative;
        width: 120px;
        height: 120px;
        .del{
            display: none;
            color: #fff;
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            text-align: center;
            line-height: 24px;
            background-color: rgba($color: #000000, $alpha: 0.8);
            cursor: pointer;
        }
        &:hover{
            .del{
                display: block;
            }
        }
    }
}
</style>