<template>
    <view class="pageContainer">
        <view style="width: 100%; min-height: 500rpx; background: #000000;">
            <view class="container" v-html="videoHtml"> </view>
        </view>
        <view class="well-cell">
            <view class="well-cell-hd">选择时间：</view>
            <view class="well-cell-bd">
                <view @click="showCalendar" class="time" style="">{{ timess }}</view>
                <!-- <u-input v-model="timess" placeholder="请选择时间" type="text" @click="show = true" /> -->
            </view>
            <u-icon name="arrow-right"></u-icon>
        </view>
        <view class="well-cell">
            <view class="well-cell-hd">通道选择：</view>
            <view class="well-cell-bd">
                <u-radio-group  @change="radioGroupChange" v-model="videoDevicesIdx">
                    <u-radio v-for="(item, index) in videoDevices" :key="index" :name="index">
                        {{ item.videoNumber }}
                    </u-radio>
                </u-radio-group>

            </view>
        </view>
        <view class="well-cell">
            <view class="well-cell-hd mt10">媒体类型：</view>
            <view class="well-cell-bd">
                <u-radio-group v-model="fordata.dataType">
                    <u-radio :name="0">音视频</u-radio>
                    <u-radio :name="1">音频</u-radio>
                    <u-radio :name="2">视频</u-radio>
                    <u-radio :name="3">视频或音视频</u-radio>
                </u-radio-group>
            </view>
        </view>
        <view class="well-cell">
            <view class="well-cell-hd mt10">流码类型：</view>
            <view class="well-cell-bd">
                <u-radio-group v-model="fordata.dataRate">
                    <u-radio :name="1">主流码</u-radio>
                    <u-radio :name="2">子码流</u-radio>
                </u-radio-group>
            </view>
        </view>
       
        <playBack @scrollEnd="scrollEnd" ref="playBack"  :timeSection="dateAndChannelData"></playBack>
        <view style="padding: 20rpx 30rpx;">
            <u-button type="primary" shape="circle" @click="btnplayback">回放</u-button>
            <u-button class="mt20" type="info" shape="circle" @click="btnoffback">关闭回放</u-button>
        </view>
        <u-calendar :show="show" mode="single" @close="show = false" ref="calendar" :formatter="formatter"
            :maxDate="maxDate"
            minDate="2023-10-01"
            monthNum="24" @confirm="confirm"></u-calendar>
        <u-toast ref="uToast" />
    </view>
</template>

<script>
import playBack from '@/components/playBack'
import createFlvPlayer from "./FlvPlayerVideo.js";
import { uniqueId } from 'lodash'
import { getDetail, dayStat, playbackPull, playbackPlay } from "@/api/system/video";
export default {
    components: {
        playBack
    },
    data() {
        return {
            flvServer: '',
            show: false,
            mode: 'date',
            vehicleId: '',
            maxDate: this.dayjs().add(365, 'day').format('YYYY-MM-DD'),
            datatimes: {
                deviceId: '',
                startDate: '',
                endDate: '',
            },
            timess: '',
            dayStatList: [],//存在视频日期
            Datelist: [],//存在视频时间
            videoNumber: [1, 2, 3, 4],
            videoDevices:[],
            videoDevicesIdx:0,
            fordata: {
                channel: 1,//路数
                dataType: 0,//媒体类型
                dataRate: 1,//码流
                deviceId: '',//设备id
                endTime: '',//结束时间
                startTime: '',//开始时间
                storageType: 0,
            },
            flvform: '',
            player: '',
            videoHtml: "",
            videoItem: {
                url: '',
                dataNumber: '',
                dataDeviceId: '',
                dataCameraId: ''
            },
            dateAndChannelData: []
        };
    },
    computed: {},
    watch: {},
    created() { },
    mounted() {
        window.closeMaker = this.closeMaker
    },
    onLoad(option) {
        console.log('参数', option)
        //组装当月的第一天和最后一天获取是否有数据
        this.datatimes.startDate = this.dayjs().startOf('month').format('YYYY-MM-DD');
        this.datatimes.endDate = this.dayjs().endOf('month').format('YYYY-MM-DD');
        //废弃
        // if (option.deviceId) {
        //     this.fordata.deviceId = option.deviceId
        //     this.videoId = uniqueId('flv_video_')
        //     this.getDayStat();
        // }
        if (option.vehicleId) {
            this.vehicleId=option.vehicleId
            this.getDetail()
        }

    },
    onReady() {
        // 如果需要兼容微信小程序的话，需要用此写法
        this.$refs.calendar.setFormatter(this.formatter)
    },
    methods: {
        // 获取车辆信息
        async getDetail() {
            console.log('获取车辆信息',this.vehicleId)
            let { data } = await getDetail({
                vehicleId: this.vehicleId
            })
            if(data.videoDevices.length>0){
                this.videoDevices = data.videoDevices
                this.fordata.deviceId =  data.videoDevices[0].deviceId
                this.fordata.channel =  data.videoDevices[0].videoNumber
                this.videoId = uniqueId('flv_video_')
                this.getDayStat();
            }else{
                uni.showToast({
                    title: '设备号不存在',
                    duration: 2000,
                    icon:'none'
                });
            }
        },
        // 获取设备有回放日期
        async getDayStat() {
            let { data } = await dayStat({
                deviceId: this.fordata.deviceId,//设备号
                startDate: '2023-10-01',
                endDate: this.dayjs().add(365, 'day').format('YYYY-MM')// 
            })
            this.dayStatList = data.map(e => {
                return e.statDate
            })
            console.log('数据', this.dayStatList)
        },

        showCalendar() {
            this.show = true
        },
        formatter(day) {
            let date = this.dayjs(day.date).format('YYYY-MM-DD')
            if (this.dayStatList.includes(date)) {
                day.bottomInfo = '有记录'
                day.dot = true
            }
            return day
        },
        //切换月份的时候拉取数据 旧版
        // async tomonth(date2) {
        //     var date = new Date(date2);
        //     var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
        //     var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
        //     this.datatimes.startDate = this.$moment(firstDay).locale("zh-cn").format("YYYY-MM-DD");
        //     this.datatimes.endDate = this.$moment(lastDay).locale("zh-cn").format("YYYY-MM-DD");
        //     for (var k in this.datatimes) {
        //         console.log(this.datatimes)
        //         if (this.datatimes[k] == null) {
        //             this.$refs.uToast.show({ title: "参数不完整", type: "error" });
        //             return
        //         }
        //     }
        //     this.Datelist = [];
        //     //根据设备号获取当月有那一下视频数据
        //     let url2 = this.$u.api.vehContainer.findVideoResByDate;
        //     let res2 = await this.$u.post(url2, this.datatimes);
        //     //组装数据
        //     if (res2.errorCode == '0') {
        //         for (var i = 0; i < res2.data.length; i++) {
        //             this.Datelist.push(res2.data[i].statDate);
        //         }
        //     }
        // },
        // async findVideoResByDate() {

        //     let obj = {
        //         vehicle_id: this.vehicleId,
        //     };
        //     this.Datelist = [];
        //     //获取车辆信息
        //     let url = this.$u.api.vehContainer.queryVideoInfoById;
        //     let res = await this.$u.post(url, obj, { showLoading: false });
        //     if (res.errorCode == '0') {
        //         this.flvform = res.data;
        //         //多设备
        //         if (res.data.videoDeviceId == null) {
        //             this.datatimes.deviceId = res.data.deviceId;
        //         } else {
        //             this.datatimes.deviceId = res.data.videoDeviceId;
        //         }
        //         this.fordata.deviceId = this.datatimes.deviceId;//设备id
        //         //获取设置的通道号
        //         if (res.data.videoDeviceId != null) {
        //             var nubervideo = res.data.videoDeviceId.split(',');
        //             if (nubervideo.length > 0) {
        //                 for (var i = 0; i < nubervideo.length; i++) {
        //                     if (nubervideo[i] == '') {
        //                         nubervideo.splice(i, 0);
        //                     }
        //                 }
        //             }
        //             this.videoNumber = nubervideo;
        //         }
        //         for (var k in this.datatimes) {
        //             console.log(this.datatimes)
        //             if (this.datatimes[k] == null) {
        //                 this.$refs.uToast.show({ title: "参数不完整", type: "error" });
        //                 return
        //             }
        //         }
        //         //根据设备号获取当月有那一下视频数据
        //         let url2 = this.$u.api.vehContainer.findVideoResByDate;
        //         let res2 = await this.$u.post(url2, this.datatimes);
        //         //组装数据
        //         if (res2.errorCode == '0') {
        //             for (var i = 0; i < res2.data.length; i++) {
        //                 this.Datelist.push(res2.data[i].statDate);
        //             }
        //         }
        //         console.log('组装数据', this.Datelist)
        //     }
        // },
        confirm(e) {
            console.log('confirm', e)
            let result = e[0];
            this.show = false
            this.timess = result;
            this.fordata.startTime = result + ' 00:00:00';
            this.fordata.endTime = result + ' 23:59:59';
        },
        // 选中任一radio时，由radio-group触发videoOneDayResource
        radioGroupChange(e) {
            this.fordata.channel = this.videoDevices[e].videoNumber;
            this.fordata.deviceId = this.videoDevices[e].deviceId;
        },
        async btnplayback() { //查询可回放时间资源并播放
            console.log(123)
            if (this.timess == '' || this.timess == undefined || this.timess == null) {
                uni.showToast({
                    title: '请选择时间',
                    duration: 2000,
                    icon: 'none'
                });
                return
            }
            for (var k in this.fordata) {
                console.log(this.fordata)
                if (this.fordata[k] == null) {
                    uni.showToast({
                        title: '参数不完整',
                        duration: 2000,
                        icon: 'none'
                    });
                    return
                 }
            }
            let { data, code } = await playbackPull({
                ...this.fordata,
            })
            this.dateAndChannelData = data.resources
            //获取资源信息
            // let url = this.$u.api.vehContainer.videoOneDayResource;
            // let res = await this.$u.post(url, this.fordata, { methodType: "body" });
            // if (res.errorCode == '0') {
            //     this.findResByDateAndChannel();
            // }
        },
        async findResByDateAndChannel() {
            let url = this.$u.api.vehContainer.findResByDateAndChannel;
            let obj = {
                deviceId: this.fordata.deviceId,//设备id
                fileDate: this.timess,//时间
                channel: this.fordata.channel,//通道号
            }

            let res = await this.$u.post(url, obj);
            if (res.errorCode == '0') {
                this.dateAndChannelData = res.data[this.fordata.channel]
                console.log('视频段', this.dateAndChannelData)
                //下发指令
                this.postVideoHis()

            }
        },
        generatePlayVideo(flvUrl) {
            console.log("flvPlayBox" + this.fordata.channel, '播放视频地址', flvUrl)

            this.flvServer = createFlvPlayer(`#${this.videoId}`, flvUrl);



        },
        checkResultData(data) {
            // 检测数据
            return data == null || data == undefined ? "" : data;
        },
        //关闭回放
        async btnoffback() {
            this.videoHtml = '';
            this.$refs.playBack.resetComponents();
            this.flvServer.destroyVideo()
        },
        // 下发视频录像回放
        async postVideoHis() {
            let videoHtml = ''
            let url2 = this.$u.api.vehContainer.videoHis;
            this.fordata.fastTimes = 0;
            this.fordata.playback = 0;
            let res2 = await this.$u.post(url2, this.fordata, { methodType: "body" });
            if (res2.errorCode == '0') {
                this.$refs.uToast.show({ title: "指令下发成功", type: "success" });
                this.$nextTick(() => {
                    // 指令下发成功
                    let videoIp = this.checkResultData(this.flvform.videoIp);//视频ip
                    let videoPort = this.checkResultData(this.flvform.videoPort);//视频端口
                    let cameraId = this.checkResultData(this.flvform.cameraId); //设备id
                    let channel = this.checkResultData(this.fordata.channel);//通道号
                    let timestamp = new Date().getTime();
                    let flvUrl = `https://${videoIp}:${videoPort}/video/history/${cameraId}-${channel}/time${timestamp}`// 视频流地址
                    console.log(flvUrl)
                    this.videoItem = {
                        url: `https://${videoIp}:${videoPort}/video/now/${cameraId}-${channel}`,
                        dataNumber: channel,
                        dataDeviceId: cameraId,
                        dataCameraId: cameraId + channel
                    }
                    videoHtml += `
                        <view class="videoBox">
                          <div 
                              class="flvPlayBox"
                              id="${this.videoId}" 
                            ></div>
                            <view class="videoTips" style="color: #fff;">
                              ${channel}路
                              <i class="online"></i>
                              <text class="text">在线</text>
                            </view>
                        </view>
                      `;
                    this.videoHtml = videoHtml;
                    this.$nextTick(() => {
                        this.generatePlayVideo(flvUrl);
                    });

                });

            }
            // 

        },
        //滚动进度条
        async scrollEnd(e) {
            console.log('开始进度条',e)
            if (!e) return;
            let { data } = await playbackPlay({
                ...this.fordata,
                startTime: this.timess + ' ' + e.itemTime,
                endTime: e.endTime
            })

            let flvUrl = this.$getImages(data.videoUrl)
            let channel = this.fordata.channel
            let cameraId = this.fordata.deviceId

            let videoHtml = ''
            videoHtml += `
                        <view class="videoBox">
                          <div 
                              class="flvPlayBox"
                              id="${this.videoId}" 
                            ></div>
                            <view class="videoTips" style="color: #fff;">
                              ${channel}路
                              <i class="online"></i>
                              <text class="text">在线</text>
                            </view>
                        </view>
                      `;
            this.videoHtml = videoHtml;
            this.$nextTick(() => {
                this.generatePlayVideo(flvUrl);
            });
        }

    },
};
</script>

<style scoped lang="scss">
.well-cell {
    padding: 20rpx 20rpx 16rpx 20rpx;
    display: flex;
    align-items: center;
    box-sizing: border-box;


    .well-cell-bd {
        flex: 1;
        margin-left: 30rpx;

        .time {
            width: 100%;
            height: 40rpx;
            padding-left: 24rpx;
        }

        /deep/ .u-radio-group {
            flex-wrap: wrap;

            .u-radio {
                margin-left: 20rpx;
                margin-bottom: 10rpx;
            }
        }
    }
}



.mt10 {
    margin-top: 10rpx;
}

.centeredVideo {
    width: 100%;
    height: 100%;
}

.mt20 {
    margin-top: 20rpx;
}

.videoTips {
    color: #fff;
}
</style>