<template>
    <div class="player-webrtc">
        <el-row :gutter="10" style="margin-bottom: 16px">
            <el-col :span="1.5">
                <el-select v-model="channelId" :placeholder="$t('views.components.player.webrtc.08878-1')" @change="changeChannel()" clearable>
                    <el-option v-for="option in channelList" :key="option.value" :label="option.label" :value="option.value"></el-option>
                </el-select>
            </el-col>
        </el-row>
        <div class="trank-wrap">
            <el-button class="btn" @click="broadcastStatusClick()" :type="getBroadcastStatus()" :disabled="broadcastStatus === -2 || channelId === ''" circle icon="el-icon-microphone" />
            <div class="title-wrap">
                <span v-if="broadcastStatus === -2">{{ $t('views.components.player.webrtc.08878-2') }}</span>
                <span v-if="broadcastStatus === -1">{{ $t('views.components.player.webrtc.08878-3') }}</span>
                <span v-if="broadcastStatus === 0">{{ $t('views.components.player.webrtc.08878-4') }}</span>
                <span v-if="broadcastStatus === 1">{{ $t('views.components.player.webrtc.08878-5') }}</span>
            </div>
        </div>
    </div>
</template>

<script>
import { getPushUrl, listChannel, startBroadcast, stopBroadcast } from '@/api/iot/channel';

export default {
    name: 'webrtc',
    components: {},
    props: {
        device: {
            type: Object,
            default: null,
        },
    },
    watch: {
        // 获取到父组件传递的device后
        device: function (newVal, oldVal) {
            this.deviceInfo = newVal;
            if (this.deviceInfo.channelId) {
                this.channelId = this.deviceInfo.channelId;
            }
            if (this.deviceInfo && this.deviceInfo.deviceId !== 0) {
                this.queryParams.deviceSipId = this.deviceInfo.serialNumber;
                this.deviceId = this.device.serialNumber;
            }
        },
    },
    data() {
        return {
            deviceInfo: null,
            deviceId: '',
            channelId: '',
            broadcastMode: true,
            broadcastRtc: null,
            broadcastStatus: -1, // -2 正在释放资源 -1 默认状态 0 等待接通 1 接通成功
            channelList: [],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                deviceSipId: null,
                channelSipId: null,
            },
        };
    },
    created() {
        this.queryParams.deviceSipId = this.device.serialNumber;
        this.deviceId = this.device.serialNumber;
        this.getList();
    },
    destroyed() {},
    methods: {
        getList() {
            listChannel(this.queryParams).then((response) => {
                this.channelList = response.rows.map((item) => {
                    return { value: item.channelSipId, label: item.channelName };
                });
                console.log(this.channelList);
            });
        },
        changeChannel() {},
        getBroadcastStatus() {
            if (this.broadcastStatus == -2) {
                return 'primary';
            }
            if (this.broadcastStatus == -1) {
                return 'primary';
            }
            if (this.broadcastStatus == 0) {
                return 'warning';
            }
            if (this.broadcastStatus == 1) {
                return 'danger';
            }
        },
        broadcastStatusClick() {
            if (this.broadcastStatus == -1) {
                // 默认状态， 开始
                this.broadcastStatus = 0;
                // 发起语音对讲
                getPushUrl(this.deviceId, this.channelId).then((res) => {
                    console.log(res);
                    if (res.code === 200) {
                        let streamInfo = res.data;
                        if (document.location.protocol.includes('https')) {
                            this.startwebrtc(streamInfo.rtcs);
                        } else {
                            this.startwebrtc(streamInfo.rtc);
                        }
                    } else {
                        this.$message({
                            showClose: true,
                            message: res.msg,
                            type: 'error',
                        });
                    }
                });
            } else if (this.broadcastStatus === 1) {
                this.broadcastStatus = -1;
                this.broadcastRtc.close();
            }
        },
        startwebrtc(url) {
            // 获取推流鉴权Key
            this.broadcastRtc = new ZLMRTCClient.Endpoint({
                debug: true, // 是否打印日志
                zlmsdpUrl: url, //流地址
                simulecast: false,
                useCamera: false,
                audioEnable: true,
                videoEnable: false,
                recvOnly: false,
            });
            this.broadcastRtc.on(ZLMRTCClient.Events.WEBRTC_NOT_SUPPORT, (e) => {
                // 获取到了本地流
                console.error('不支持webrtc', e);
                this.$message({
                    showClose: true,
                    message: this.$t('views.components.player.webrtc.08878-6'),
                    type: 'error',
                });
                this.broadcastStatus = -1;
            });

            this.broadcastRtc.on(ZLMRTCClient.Events.WEBRTC_ICE_CANDIDATE_ERROR, (e) => {
                // ICE 协商出错
                console.error('ICE 协商出错');
                this.$message({
                    showClose: true,
                    message: this.$t('views.components.player.webrtc.08878-7'),
                    type: 'error',
                });
                this.broadcastStatus = -1;
            });

            this.broadcastRtc.on(ZLMRTCClient.Events.WEBRTC_OFFER_ANWSER_EXCHANGE_FAILED, (e) => {
                // offer anwser 交换失败
                console.error('offer anwser 交换失败', e);
                this.$message({
                    showClose: true,
                    message: this.$t('views.components.player.webrtc.08878-8') + e,
                    type: 'error',
                });
                this.broadcastStatus = -1;
            });
            this.broadcastRtc.on(ZLMRTCClient.Events.WEBRTC_ON_CONNECTION_STATE_CHANGE, (e) => {
                // offer anwser 交换失败
                console.log('状态改变', e);
                if (e === 'connecting') {
                    this.broadcastStatus = 0;
                } else if (e === 'connected') {
                    this.broadcastStatus = 1;
                    startBroadcast(this.deviceId, this.channelId).then((res) => {
                        if (res.code === 200) {
                            console.log('开始推流！');
                        }
                    });
                } else if (e === 'disconnected') {
                    this.broadcastStatus = -1;
                }
            });
            this.broadcastRtc.on(ZLMRTCClient.Events.CAPTURE_STREAM_FAILED, (e) => {
                // offer anwser 交换失败
                console.log('捕获流失败', e);
                this.$message({
                    showClose: true,
                    message: this.$t('views.components.player.webrtc.08878-9') + e,
                    type: 'error',
                });
                this.broadcastStatus = -1;
            });
        },

        stopBroadcast() {
            this.broadcastRtc.close();
            this.broadcastStatus = -1;
            stopBroadcast(this.deviceId, this.channelId).then((res) => {
                if (res.code == 200) {
                    this.broadcastStatus = -1;
                    this.broadcastRtc.close();
                } else {
                    this.$message({
                        showClose: true,
                        message: res.msg,
                        type: 'error',
                    });
                }
            });
        },
    },
};
</script>

<style lang="scss" scoped>
.player-webrtc {
    .trank-wrap {
        text-align: center;
        margin-top: 100px;

        .btn {
            font-size: 63px;
        }

        .title-wrap {
            font-size: 16px;
            margin-top: 10px;
        }
    }
}
</style>
