<template>
  <div class="yqrange-index-wrapper">
    <!--<bread-crumb :curmbFirst="curmbFirst" :curmbSecond="curmbSecond"></bread-crumb>-->
    <div class="yqrange-index-content" id="screenSet">
      <!--<div class="header-title">直播管理</div>-->
      <el-form
        ref="searchForm"
        :model="searchForm"
        label-width="75px"
        label-suffix=":"
        :inline="true"
      >
        <el-row :gutter="30" type="flex" style="margin-top: 10px">
          <el-col :span="8">
            <el-form-item label="直播名称">
              <el-input
                v-model="searchForm.liveName"
                size="small"
                placeholder="请输入直播名称"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item label="直播状态">
              <el-select
                v-model="searchForm.liveStatus"
                id="statusSelector"
                placeholder="请选择发布状态"
                clearable
                style="margin-left: 20px; height: 32px; line-height: 32px"
              >
                <el-option
                  v-for="item in statusList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7" style="text-align: right">
            <el-button type="primary" size="small" @click="search"
              >搜索</el-button
            >
            <el-button
              type="default"
              size="small"
              @click="resetForm"
              style="margin-left: 0"
              >取消搜索</el-button
            >
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" style="text-align: right">
            <el-button type="primary" size="small" @click="createLive"
              >新建直播</el-button
            >
          </el-col>
        </el-row>
      </el-form>
      <el-table
        :data="tableData"
        class="item-table"
        style="width: 100%; margin-top: 10px"
      >
        <el-table-column
          prop="name"
          label="直播名称"
          min-width="100"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="liveStatus"
          label="直播状态"
          min-width="100"
          align="center"
        >
          <template v-slot="scope">
            <span>{{ $filters.liveStatusFilter1(scope.row.liveStatus) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="streamType"
          label="直播方式"
          min-width="100"
          align="center"
        >
          <template v-slot="scope">
            <span>{{ $filters.streamTypeFilter(scope.row.streamType) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="createdTime"
          label="创建时间"
          min-width="100"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="openTime"
          label="开始时间"
          min-width="100"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="endTime"
          label="结束时间"
          min-width="100"
          align="center"
        ></el-table-column>
        <el-table-column label="操作" min-width="300" align="center">
          <template v-slot="scope">
            <!-- <el-button @click="reviewLive(scope.row)" type="text" size="small">设置回放</el-button> -->
            <el-button
              @click="setPlayback(scope.row)"
              type="text"
              size="small"
              v-if="
                scope.row.playbackSetFlag == 1 && scope.row.canPlayback == 0
              "
              >设置回放</el-button
            >
            <el-button
              @click="closePlayback(scope.row)"
              type="text"
              size="small"
              v-if="
                scope.row.playbackSetFlag == 1 && scope.row.canPlayback == 1
              "
              >关闭回放</el-button
            >
            <!--<el-button @click="setPlayback(scope.row)" type="text" size="small" >设置回放</el-button>-->
            <!--<el-button @click="closePlayback(scope.row)" type="text" size="small" >关闭回放</el-button>-->
            <!-- 1.拉流直播，如果是非公开的话，在直播列表不显示直播链接入口;2.网页直播，非公开，已经结束，不显示直播链接入口 -->
            <el-button
              @click="liveLink(scope.row)"
              type="text"
              size="small"
              v-if="
                !(
                  (scope.row.liveStatus == 4 && scope.row.scope == 1) ||
                  (scope.row.streamType == 2 && scope.row.scope == 1)
                )
              "
              >直播链接</el-button
            >

            <el-button
              @click="updatelive(scope.row)"
              type="text"
              size="small"
              v-if="scope.row.liveStatus == 2 && scope.row.streamType == 2"
              >结束直播</el-button
            >
            <el-button
              @click="countLive(scope.row)"
              type="text"
              size="small"
              v-if="scope.row.liveStatus == 4"
              >数据统计</el-button
            >
            <el-button @click="editLive(scope.row)" type="text" size="small"
              >编辑</el-button
            >
            <el-button @click="delLive(scope.row)" type="text" size="small"
              >删除</el-button
            >
            <!--<el-button @click="setPlayback(scope.row)" type="text" size="small" v-if="scope.row.playbackSetFlag == 1">设置回放</el-button>-->

            <!--<el-button @click="setPlayback(scope.row)" type="text" size="small" v-if="scope.row.playbackSetFlag == 1">关闭回放</el-button>-->
            <!-- <el-button @click="deleteLive(scope.row)" type="text" size="small">删除</el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleNumChange"
          :current-page="searchForm.pageNo"
          :page-sizes="[10, 30, 50, 100, 200]"
          :page-size="searchForm.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalRows"
        ></el-pagination>
      </div>

      <el-dialog
        title="数据统计"
        v-model="dialogStatisticsVisible"
        width="500px"
        :close-on-click-modal="false"
        @close="handleStatisticsClose"
        center
      >
        <el-table :data="dialogStatisticsData" align="center">
          <el-table-column
            property="peopleNum"
            label="观看人数"
            align="center"
          ></el-table-column>
          <el-table-column
            property="signNum"
            v-if="isSign == 1"
            label="签到人数"
            align="center"
          >
            <template v-slot="scope">
              <el-link @click="downlodExcel()">{{ scope.row.signNum }}</el-link>
            </template>
          </el-table-column>
          <el-table-column
            property="liveDuration"
            label="直播时长（分钟）"
            align="center"
          ></el-table-column>
        </el-table>
      </el-dialog>

      <el-dialog
        title="直播链接"
        v-model="dialogLivelinkVisible"
        width="700px"
        :close-on-click-modal="false"
        @close="handleLivelinkClose"
        center
      >
        <input type="text" id="copyInput" class="hidden-input" />

        <div
          class="live_url_style"
          v-if="
            streamType == 1 && (this.liveStatus == 1 || this.liveStatus == 2)
          "
        >
          <div class="href_style">主播链接 {{ lecturerUrl }}</div>
          <el-col class="href_outer_border">
            <el-link
              type="primary"
              @click="copyTxt(1)"
              size="small"
              class="href_button_style"
              >复制</el-link
            >
            <el-link type="primary">|</el-link>
            <el-link type="primary" @click="jumpUrl(1)" size="small"
              >进入直播</el-link
            >
          </el-col>
        </div>

        <div
          class="live_url_style"
          v-if="
            streamType == 1 && (this.liveStatus == 1 || this.liveStatus == 2)
          "
        >
          <el-col class="href_style">嘉宾链接 {{ guestUrl }}</el-col>
          <el-col class="href_outer_border">
            <el-link
              type="primary"
              @click="copyTxt(2)"
              size="small"
              class="href_button_style"
              >复制</el-link
            >
            <el-link type="primary">|</el-link>
            <el-link type="primary" @click="jumpUrl(2)" size="small"
              >进入直播</el-link
            >
          </el-col>
        </div>

        <div class="live_url_style" v-if="streamType == 2 || this.scope == 2">
          <div class="href_style">观众链接 {{ audienceUrl }}</div>
          <el-col class="href_outer_border">
            <el-link
              type="primary"
              @click="copyTxt(3)"
              size="small"
              class="href_button_style"
              >复制</el-link
            >
            <el-link type="primary">|</el-link>
            <el-link type="primary" @click="previewQrcode()" size="small"
              >预览二维码</el-link
            >
          </el-col>
          <!--<el-col class="href_outer_border">-->
          <!--<el-link type="primary" @click="previewQrcode(3)" size="small" class="href_button_style">预览二维码</el-link>-->
          <!--</el-col>-->
        </div>
      </el-dialog>

      <el-dialog
        title="设置回放"
        v-model="dialogLivePlaybackVisible"
        width="500px"
        :close-on-click-modal="false"
        @close="handleLivePlaybackClose"
        center
      >
        <el-form ref="playbackForm" :model="playbackForm">
          <!--<input type="text" id="copyInput" class="hidden-input" />-->

          <div class="live_url_style" v-if="selectFlag">
            <el-radio-group
              size="small"
              style="line-height: 30px"
              v-model="playbackForm.videoSource"
              @change="changeVideoSource"
            >
              <el-radio label="1">使用直播原视频播放</el-radio>
              <el-radio label="2"
                >上传回放视频（下载原视频编辑后上传）</el-radio
              >
            </el-radio-group>
          </div>

          <div v-if="uploadFlag" style="line-height: 40px">
            <div v-if="numberShowFlag">
              <span style="margin-left: 25px">存在</span
              ><span style="color: #449284">"{{ videoNumber }}段"</span
              ><span>直播原视频，请下载合并后上传</span>
            </div>
            <div style="margin-left: 30px" v-if="downloadVideoFlag">
              <span>①下载原视频</span>

              <!--<el-col :span="1">-->

              <!--</el-col>-->
              <el-button @click="downloadV('model')" size="small" type="text"
                ><img
                  style="
                    vertical-align: middle;
                    margin-left: 56px;
                    width: 25%;
                    height: 25%;
                  "
                  src="../../assets/image/icon_download.png"
                />下载</el-button
              >
            </div>

            <div style="margin-left: 30px">
              <span v-show="downloadVideoFlag">②上传回放视频</span>
              <span v-show="!downloadVideoFlag">①上传回放视频</span>
              <el-upload
                style="float: right"
                action="#"
                accept="*/*"
                ref="upload"
                :limit="1"
                :show-file-list="false"
                :before-upload="beforeUploadVideo"
              >
                <!--<el-col :span="1">-->

                <!--</el-col>-->
                <el-button
                  type="text"
                  size="small"
                  style="margin-top: -10px"
                  v-if="fileFlag"
                  ><img
                    style="vertical-align: middle; width: 13%; height: 13%"
                    src="../../assets/image/icon_upload.png"
                  />上传（仅支持mp4,限制大小2G）</el-button
                >
                <!--<video class="video-mg-url" controls preload :src="cleatBroadcast.liveInfo.mgUrl"></video>-->
                <!-- <img v-if="!cleatBroadcast.liveInfo.mgUrl" class="video-bg-img" src="../../../static/img/small.png"> -->
              </el-upload>
              <el-progress
                :text-inside="true"
                :stroke-width="20"
                :percentage="uploadProgress1"
                status="success"
                v-show="
                  uploadProgress1 > 0 && uploadProgress1 < 100 && deleteFileFlag
                "
              >
              </el-progress>

              <div v-if="deleteFileFlag">
                <span v-show="playbackForm.videos[0].videoSource == 2"
                  >{{ videoToName(playbackForm.videos[0].videoName, 6) }}({{
                    videoToSize(playbackForm.videos[0].videoSize, 1)
                  }}M)</span
                >
                <el-button
                  v-show="
                    playbackForm.videos[0].videoSource == 2 &&
                    (deleteFileFlag || uploadProgress1 > 0)
                  "
                  @click="delVideo"
                  style="margin-left: 100px"
                  size="small"
                  type="text"
                  >{{
                    uploadProgress1 && uploadProgress1 < 100
                      ? '取消上传'
                      : '删除'
                  }}</el-button
                >
              </div>
              <!--<div v-if="fileFlag">-->
              <!---->
              <!--<el-progress-->
              <!--:text-inside="true"-->
              <!--:stroke-width="16"-->
              <!--:percentage="uploadProgress1"-->
              <!--status="success"-->
              <!--v-show="uploadProgress1 > 0 && uploadProgress1 < 100">-->
              <!--</el-progress>-->

              <!--</div>-->
            </div>
          </div>
        </el-form>

        <template v-slot:footer>
          <div class="dialog-footer" style="text-align: right">
            <el-button
              type="primary"
              @click="submitPlayback(1)"
              :disabled="disabledOpenFlag && uploadProgress1 < 100"
              right
              >开启回放</el-button
            >
          </div>
        </template>
      </el-dialog>
      <!--预览二维码-->
      <el-dialog
        title="预览"
        v-model="dialogVisible"
        width="50%"
        :before-close="handleClose"
      >
        <div id="qrcode" class="qrcode-wrap"></div>
        <template v-slot:footer>
          <span class="dialog-footer"></span>
        </template>
      </el-dialog>
      <!--<el-dialog-->
      <!--title="关闭回放"-->
      <!--:visible.sync="closePlaybackVisible"-->
      <!--width="500px"-->
      <!--:close-on-click-modal="false"-->
      <!--@close="handleLivePlaybackClose"-->
      <!--center>-->

      <!--<div slot="footer" class="dialog-footer" style="text-align: right;">-->
      <!--<el-button @click="closePlaybackVisible = false">取 消</el-button>-->
      <!--<el-button type="primary" @click="submitPlayback(0)" right>结束回放</el-button>-->
      <!--</div>-->

      <!--</el-dialog>-->
    </div>
  </div>
</template>

<script>
import { openLoading, closeLoading } from '../../utils/utils'
import DownloadJS from '@/utils/download/download4'

let vm = null
import BreadCrumb from '@/components/breadcrumb.vue'
import {
  getPlayback,
  postPlayback,
  updateLiveStatus,
  downloadSigninfo,
} from '../../utils/yqrange/yqrangeApi'
import { doUpload, getFilePath, unsubscribe } from '../../utils/qiniu-util'
import QRCode from 'qrcodejs2'
import ElLink from 'element-ui/packages/link/src/main'
export default {
  components: {
    ElLink,
    BreadCrumb,
    QRCode,
  },
  data() {
    return {
      rtcId: null,
      curmbFirst: '云鹊专区',
      curmbSecond: '直播管理',
      dialogStatisticsVisible: false,
      dialogLivelinkVisible: false,
      dialogLivePlaybackVisible: false,
      // closePlaybackVisible: false,
      playbackSetFlag: 1,
      canPlayback: '1',
      uploadFlag: false,
      selectFlag: true,
      numberShowFlag: false,
      videoNumber: 0,
      playbackUrl: '',
      searchForm: {
        liveName: '',
        liveStatus: '',
        pageNo: 1,
        pageSize: 10,
      },
      totalRows: 0,
      statusList: [
        {
          value: '1',
          label: '预告',
        },
        {
          value: '2',
          label: '直播中',
        },
        {
          value: '4',
          label: '已结束',
        },
      ],
      tableData: [
        // {
        //   liveName: "浙江医学大会第二场",
        //   scope: 1, //直播范围 1-非公开 2-公开
        //   liveStatus: 1, //直播状态 1-未开始 2-直播中 3-暂停中 4-已结束 5-回放中目前只能用到1，2，4
        //   createTime: "",
        //   startTime: "",
        //   endTime: "",
        //   rtcId: 0
        // }
      ],
      dialogStatisticsData: [
        {
          peopleNum: 0,
          liveDuration: '',
          signNum: 0,
        },
      ],
      scope: 1,
      liveStatus: 1,

      lecturerUrl: '',
      guestUrl: '',
      audienceUrl: '',
      playbackForm: {
        canPlayback: 0,
        playbackUrls: {
          downloadUrls: [], //下载地址,已按时间正序排序
          originalUrls: [],
        },
        rtcId: '',
        videoSource: '1',
        videos: [
          {
            seqNo: '',
            videoName: '',
            videoSize: '',
            videoSource: '',
            videoType: '',
            videoUrl: '',
          },
        ],
      },
      disabledOpenFlag: false, // 开启回放是否可点
      downloadVideoFlag: true, // 拉流直播不显示下载
      videoNumber: 0,
      uploadProgress1: 0,
      fileName: '',
      fileSize: 0,
      fileFlag: true,
      deleteFileFlag: false,
      circleId: null,
      streamType: 1,
      downloadSuccessStatus: 1,
      videoSize: 0,
      link: '', //预览的链接
      qrcodeBox: null,
      dialogVisible: false,
      isSign: 0, // 是否签到
    }
  },
  props: {
    circleName: {
      type: String,
    },
  },
  created() {
    vm = this
    this.circleId = this.$route.query.id
    console.log('circleName: ' + this.circleName)
    vm.getLiveList('', '')
  },
  methods: {
    // 搜索按钮
    search() {
      this.searchForm.pageNo = 1
      this.searchList()
    },

    searchList() {
      console.log('查询')
      var searchStatusString
      var searchStatusInt
      searchStatusString = this.searchForm.liveStatus
      if (searchStatusString == '预告') {
        searchStatusInt = 1
      } else if (searchStatusString == '直播中') {
        searchStatusInt = 2
      } else if (searchStatusString == '已结束') {
        searchStatusInt = 4
      } else {
        searchStatusInt = null
      }
      console.log('searchList() : searchStatusInt = ' + searchStatusInt)
      this.getLiveList(this.searchForm.liveName, searchStatusInt)
    },
    resetForm() {
      console.log('重置alex')
      // this.$router.push({
      //   path: '/role-manage',
      // })
      this.searchForm.liveName = ''
      this.searchForm.liveStatus = ''
      this.search()
    },
    //新建直播
    createLive() {
      this.$router.push({
        path: '/create-live',
        query: {
          circleId: this.circleId,
          circleName: this.circleName,
        },
      })

      // this.$emit("setActive", 4);
    },
    //弹出直播链接弹窗
    liveLink(row) {
      this.dialogLivelinkVisible = true
      this.scope = row.scope
      this.liveStatus = row.liveStatus
      this.streamType = row.streamType
      console.log(
        'liveLink() : scope = ' +
          this.scope +
          ', liveStatus = ' +
          this.liveStatus
      )

      vm.GET('rtc/liveAdmin/url/' + row.id, '').then((res) => {
        if (res.code == '000000') {
          this.lecturerUrl = res.data.lecturerUrl
          this.guestUrl = res.data.guestUrl
          this.audienceUrl = res.data.audienceUrl
          this.dialogLivelinkVisible = true
        } else {
          //
        }
      })
    },
    //关闭直播链接弹窗
    handleLivelinkClose() {
      vm.dialogLivelinkVisible = false
    },

    // // 查询回放信息
    // getPlayback(){
    //
    // }

    //设置回放
    setPlayback(row) {
      vm.dialogLivePlaybackVisible = true

      const rtcId = row.id

      vm.streamType = row.streamType

      // 拉流直播不显示选择区域
      if (vm.streamType == 2) {
        vm.selectFlag = false
        vm.uploadFlag = true
        vm.downloadVideoFlag = false
      } else {
        vm.selectFlag = true
      }

      openLoading(this)
      getPlayback({ rtcId })
        .then((res) => {
          closeLoading(this)
          if (res.code == '000000') {
            vm.playbackForm = res.data
            if (vm.playbackForm.playbackUrls != null) {
              // if(vm.playbackForm.playbackUrls.originalUrls != null){

              vm.playbackForm.videoSource = String(vm.playbackForm.videoSource)

              // if(vm.playbackForm.videos != null && vm.playbackForm.videos.length > 0){
              //   vm.playbackForm.videos[0].videoSize = vm.videoSize(vm.playbackForm.videos[0].videoSize, 1);
              // }

              // 拉流直播 不显示两个选择按钮；只显示①上传回放视频
              if (vm.streamType == 2) {
                vm.playbackForm.videoSource = '2'
                vm.selectFlag = false
                vm.downloadVideoFlag = false
              }
              // 网页直播
              else {
                // 存在多个原视频,如果直播原视频有大于1段，不显示两个选择按钮，而显示“存在..直播原视频，请下载合并后上传”
                if (vm.playbackForm.playbackUrls.downloadUrls.length > 1) {
                  vm.uploadFlag = true
                  vm.selectFlag = false
                  vm.numberShowFlag = true
                  vm.videoNumber =
                    this.playbackForm.playbackUrls.downloadUrls.length
                  vm.playbackForm.videoSource = '2'
                  vm.downloadVideoFlag = true
                } else {
                  vm.selectFlag = true
                  vm.changeVideoSource()
                  vm.numberShowFlag = false

                  // 当选择第二个按钮“上传回放视频”时，显示①下载②上传
                  if (vm.playbackForm.videoSource == '2') {
                    vm.downloadVideoFlag = true
                  }
                }
              }
              // 如果回放视频有，则显示删除，不显示上传
              if (
                vm.playbackForm.videos != null &&
                vm.playbackForm.videos.length > 0
              ) {
                // 当选择第二个按钮“上传回放视频”时，显示①下载②上传,如果videoSource等于1，原视频直播，要显示上传，不显示删除
                if (vm.playbackForm.videoSource == '1') {
                  vm.fileFlag = true
                  vm.deleteFileFlag = false
                }
                // 当选择第二个按钮“上传回放视频”时，显示①下载②上传,如果videoSource等于2，回放视频，要显示删除，不显示上传
                else {
                  vm.fileFlag = false
                  vm.deleteFileFlag = true
                }
              }

              // // 初始化
              // vm.uploadProgress1 = Number("0.00");
              // vm.uploadProgress = Number("0.00");
              // if(row.streamType == 1){
              //
              //   vm.downloadVideoFlag = true;
              //   vm.changeVideoSource();
              // }
              // else {
              //   vm.playbackForm.videoSource = "2";
              // }

              // }
            }
          }
        })
        .catch((error) => {
          vm.$message({
            message: '请重试',
            type: 'error',
          })
        })
    },
    //关闭设置回放弹窗
    handleLivePlaybackClose() {
      vm.dialogLivePlaybackVisible = false
      vm.uploadFlag = false
      vm.delVideo()
      closeLoading(this)
    },

    // 设置回放方式
    changeVideoSource() {
      if (vm.playbackForm.videoSource == '2') {
        vm.uploadFlag = true
      } else {
        vm.uploadFlag = false
      }
    },

    // 下载
    downloadV(type) {
      if (vm.downloadSuccessStatus == 1 || vm.downloadSuccessStatus == 3) {
        vm.$message.warning('正在下载中...')
      }

      let downloadUrl = ''
      if (type == 'model') {
        if (vm.numberShowFlag) {
          for (
            let i = 0;
            i < vm.playbackForm.playbackUrls.downloadUrls.length;
            i++
          ) {
            vm.downloadVideo(vm.playbackForm.playbackUrls.downloadUrls[i])
          }
        } else {
          // downloadUrl = "http://1302268825.vod2.myqcloud.com/22ae71e7vodcq1302268825/317cf9115285890804733258933/f0.mp4";
          downloadUrl = vm.playbackForm.playbackUrls.downloadUrls[0]
          console.log('下载', type, downloadUrl)
          setTimeout(() => {
            vm.downloadVideo(downloadUrl)
          }, 500)
        }
      } else if (type == 'fail') {
        // downloadUrl = vm.failExcelUrl;
      }
    },

    downloadVideo(downloadUrl) {
      // downloadUrl = "http://test1-videos.yunqueyi.com/video/mp4/protal/project/20200708120235951.mp4"
      // downloadUrl = "http://1302268825.vod2.myqcloud.com/22ae71e7vodcq1302268825/987e98325285890805188214568/f0.mp4"

      if (downloadUrl == null || downloadUrl == '') {
        vm.$message.warning('下载地址不正确')
        return
      }

      // var link = document.createElement("a");
      // downloadUrl = "http://1302268825.vod2.myqcloud.com/22ae71e7vodcq1302268825/317cf9115285890804733258933/f0.mp4";
      // var url = downloadUrl;
      // link.href = url;
      // if(navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion .split(";")[1].replace(/[ ]/g,"")=="MSIE9.0" ||
      //   navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion .split(";")[1].replace(/[ ]/g,"")=="MSIE10.0"){
      //   window.open(url,'blank')
      // }else if (navigator.userAgent.indexOf("Firefox/") > -1){
      //   window.open(url,'blank')
      // } else{
      //   window.open(url,'_blank')
      // }
      // let url = window.URL.createObjectURL(new Blob([data]))
      // let link = document.createElement('a')
      // link.style.display = 'none'
      // link.href = "https://test1-videos.yunqueyi.com/video/mp4/protal/project/20200708120235951.mp4";
      // link.setAttribute('download', '20200708120235951.mp4')
      //
      // document.body.appendChild(link)
      // link.click()
      // let fileName = "20200708120235951.mp4";
      let fileName = vm.getFileName(downloadUrl)
      if (downloadUrl.indexOf('http://') != -1) {
        let downArray = downloadUrl.split('://')
        downloadUrl = downArray[0] + 's://' + downArray[1]
      }

      vm.downloadfile(downloadUrl, fileName, vm.getFileType(fileName))
    },

    // // 上传
    // upload(){
    //
    // },

    // 视频Size转换
    videoToSize(fileSize, number) {
      return (fileSize / 1024 / 1024).toFixed(number)
    },

    videoToName(fileName, number) {
      if (fileName != null && fileName != '') {
        const index = fileName.indexOf('.mp4')
        const str = fileName.slice(0, index)
        if (str.length > number) {
          return str.slice(0, number + 1) + '...' + '.mp4'
        } else {
          return fileName
        }
      }
      return fileName
    },

    // // 上传视频
    // uploadVideo(file, fileList){
    //  console.log("uploadVideo: file path is :" + file.name);
    // },

    //上传直播简介
    beforeUploadVideo(file) {
      let fileLimit = {
        // width: 750,
        // height: 3000,
        size: 2048,
        sizeText: '2048Mb',
        key: 'imageContent',
        more: 'imgUrl1More',
        show: 'uploadImgMessage1',
      }
      this.beforeUploadMore(file, fileLimit)
    },

    // 上传视频
    beforeUploadMore(file, fileLimit) {
      const isMp4 = file.type === 'video/mp4'
      vm.videoSize = file.size / 1024 / 1024
      const isSize = vm.videoSize < fileLimit.size
      if (!isMp4) {
        this.$refs.upload.clearFiles()
        vm.$message.error('上传回放视频只能是mp4格式!')
        // vm.isDisabledIns = false;
        file = null
        return
      }
      if (!isSize) {
        // this.$refs.upload.abort();
        this.$refs.upload.clearFiles()
        vm.$message.error('视频大小不符合规范，请根据规范上传视频')
        // vm.isDisabledIns = false;
        file = null
        return
      }

      vm.disabledOpenFlag = true

      vm.fileFlag = false
      vm.deleteFileFlag = true
      // vm.fileName = file.name;
      // if(file.size != null){
      //   vm.fileSize = vm.videoSize(file.size, 1);
      // }
      // else {
      //   vm.fileSize = file.size;
      // }
      vm.playbackForm.videos = [
        {
          seqNo: 0,
          videoName: file.name,
          videoSize: file.size,
          videoSource: 2,
          videoType: 1,
          videoUrl: '',
        },
      ]

      // 初始化
      vm.uploadProgress1 = Number('0.00')
      vm.uploadProgress = Number('0.00')
      // vm.$message.success('开始上传')
      doUpload(
        vm,
        file,
        getFilePath(file, null),
        'preview4',
        'uploadProgress1',
        ''
      ).then(function (path) {
        if (
          vm.playbackForm.videos != null &&
          vm.playbackForm.videos[0] != null
        ) {
          vm.playbackForm.videos[0].videoUrl = path.fullPath
        }
        // vm.playbackForm.videos[0].videoSize =
        // vm.playbackForm.videos[0].seqNo = 0;
        // vm.playbackForm.videos[0].videoName = vm.fileName;
        // vm.playbackForm.videos[0].videoSize = file.size();
        // vm.playbackForm.videos[0].videoSource = 2;
        // vm.playbackForm.videos[0].videoType = 1;
        // vm.playbackForm.videos[0].videoUrl = path.fullPath;
        vm.fileFlag = false

        vm.deleteFileFlag = true
        //
        // vm.uploadProgress1 = Number("0.00");
        // vm.uploadProgress = Number("0.00");

        vm.$message.success('上传成功')
      })
    },

    // 删除视频
    delVideo() {
      if (vm.uploadProgress1 > 0 && vm.uploadProgress1 < 100) {
        openLoading(this)
        this.$refs.upload.abort() // 取消上传请求(element)
        this.$refs.upload.clearFiles()
        unsubscribe() // 取消七牛上传请求
        // if(vm.videoSize > 500){
        //   setTimeout(() => {
        //     closeLoading(this);
        //     vm.$message.success('取消成功');
        //   }, 2000);
        // }
        // else {
        //   closeLoading(this);
        //   vm.$message.success('取消成功');
        // }
        closeLoading(this)
        vm.$message.success('取消成功')
        vm.uploadProgress1 = Number('0.00')
        vm.uploadProgress = Number('0.00')
      }
      // vm.uploadProgress1 = 0;
      vm.fileFlag = true
      vm.deleteFileFlag = false
      vm.playbackForm.videos = []
      vm.disabledOpenFlag = false
    },

    // 开启回放/结束回放
    submitPlayback(canPlayback) {
      if (
        vm.playbackForm.videoSource == 1 &&
        vm.playbackForm.originalUrls != null &&
        vm.playbackForm.originalUrls.length > 0
      ) {
        this.$message.warning('原视频地址不正确，请确认')
        return
      }

      if (vm.uploadFlag && canPlayback == 1) {
        if (
          vm.playbackForm.videos == null ||
          vm.playbackForm.videos.length == 0 ||
          (vm.playbackForm.videos != null &&
            vm.playbackForm.videos[0].videoSize == null)
        ) {
          this.$message.warning('请上传回放视频')
          return
        }
      }
      openLoading(this)
      // 开启回放
      this.playbackForm.canPlayback = canPlayback

      let params = this.playbackForm

      postPlayback(params)
        .then((res) => {
          closeLoading(this)
          if (res.code == '000000') {
            if (canPlayback == 1) {
              this.$message.success('开启成功')
            } else {
              this.$message.success('关闭成功')
            }
            vm.dialogLivePlaybackVisible = false
            vm.getLiveList('', '')
          } else {
            if (canPlayback == 1) {
              this.$message.error('开启失败，请重试')
            } else {
              this.$message.error('关闭失败，请重试')
            }
          }
        })
        .catch((error) => {
          this.$message.error('请重试')
        })
    },

    // 关闭回放
    closePlayback(row) {
      this.$confirm(`确定关闭回放吗？`, '', {
        confirmButtonText: '关闭回放',
        cancelButtonText: '取消',
        type: 'warning',
        // customClass: 'range-make-box',
      })
        .then(() => {
          openLoading(this)

          // vm.submitPlayback(0);

          let params = { rtcId: row.id, canPlayback: 0 }

          postPlayback(params)
            .then((res) => {
              closeLoading(this)
              if (res.code == '000000') {
                // if(canPlayback == 0){
                vm.$message.success('关闭成功')
                vm.getLiveList('', '')
              } else {
                this.$message.error('关闭失败，请重试')
              }
            })
            .catch((error) => {
              vm.$message.error('请重试')
            })
        })
        .catch(() => {})
    },

    // 结束直播
    updatelive(row) {
      this.$confirm(`确定结束直播吗？`, '', {
        confirmButtonText: '结束直播',
        cancelButtonText: '取消',
        type: 'warning',
        // customClass: 'range-make-box',
      })
        .then(() => {
          openLoading(this)
          //  confirm
          let params = { rtcId: row.id, liveStatus: 4 }

          updateLiveStatus(params)
            .then((res) => {
              closeLoading(this)
              if (res.code == '000000') {
                this.$message.success('结束成功')
                vm.getLiveList('', '')
              } else {
                this.$message.error('结束失败，请重试')
              }
            })
            .catch((error) => {
              this.$message.error('请重试')
            })
        })
        .catch(() => {})
    },

    //数据统计
    countLive(row) {
      this.rtcId = row.id
      this.isSign = row.isSign
      this.dialogStatisticsVisible = true
      console.log('getStatisticsData() : this.circleId = ' + this.circleId)
      vm.GET('rtc/liveAdmin/data/' + row.id, '').then((res) => {
        if (res.code == '000000') {
          let listData = []
          let obj = {
            peopleNum: res.data.viewedPersonTime,
            liveDuration: res.data.liveDuration,
            signNum: res.data.signNum,
          }
          listData.push(obj)
          this.dialogStatisticsData = listData
        } else {
          this.dialogStatisticsData = []
        }
      })
    },
    handleStatisticsClose() {
      this.dialogStatisticsVisible = false
    },
    //编辑直播
    editLive(row) {
      this.$router.push({
        path: '/create-live',
        query: {
          // rtcId: "1"
          rtcId: row.id,
          circleId: this.circleId,
          circleName: this.circleName,
        },
      })
    },
    //删除直播
    delLive(row) {
      // 直播中
      if (row.liveStatus == 2) {
        vm.$message({
          type: 'warning',
          message: '直播中无法删除，请直播结束后重试',
        })
      }
      // 1:直播预告；4:直播结束后，可以删除
      else if (row.liveStatus == 1 || row.liveStatus == 4) {
        this.$confirm(`确定删除“${row.name}”吗？`, '', {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning',
          // customClass: 'range-make-box',
        })
          .then(() => {
            //  confirm
            vm.DELETE('rtc/liveAdmin/' + row.id, {}).then((res) => {
              if (res.code == '000000') {
                vm.$message({
                  type: 'success',
                  message: '删除成功',
                })
                this.getLiveList('', '')
              } else {
                vm.$message({
                  type: 'warning',
                  message: res.message,
                })
              }
            })
          })
          .catch(() => {})
      }
    },
    // //编辑直播
    // editLive(row) {
    //   this.$router.push({
    //     path: "/create-live",
    //     query: {
    //       // rtcId: "16"
    //       rtcId: row.id,
    //
    //     }
    //   });
    // },
    handleSizeChange(val) {
      this.searchForm.pageSize = val
      this.searchForm.pageNo = 1
      this.searchList()
    },
    handleNumChange(val) {
      this.searchForm.pageNo = val
      this.searchList()
    },
    //查询直播列表
    getLiveList(name, status) {
      let req = {
        circleId: this.circleId,
        name: name,
        liveStatus: status,
        pageNo: this.searchForm.pageNo,
        pageSize: this.searchForm.pageSize,
      }
      vm.POST('rtc/liveAdmin/list', req).then((res) => {
        if (res.code == '000000') {
          // console.log(res);
          let listData = []
          if (res.data.pageContents == null) {
            return
          }
          // for (let i = 0; i < res.data.pageContents.length; i++) {
          //   let obj = {
          //     // liveName: res.data.pageContents[i].name,
          //     // liveScope: res.data.pageContents[i].scope,
          //     // liveStatus: res.data.pageContents[i].liveStatus,
          //     // streamType: res.data.pageContents[i].streamType,
          //     // playbackSetFlag: res.data.pageContents[i].playbackSetFlag,
          //     // canPlayback: res.data.pageContents[i].canPlayback,
          //     // createTime: res.data.pageContents[i].createdTime,
          //     // startTime: res.data.pageContents[i].openTime,
          //     // endTime: res.data.pageContents[i].endTime,
          //     // rtcId: res.data.pageContents[i].id,
          //     // isSign: res.data.pageContents[i].isSign
          //   };
          //   listData.push(obj);
          // }
          this.tableData = res.data.pageContents

          this.totalRows = res.data.totalRows
        } else {
          this.tableData = []
        }
      })
    },
    copyTxt(type) {
      let txt = document.getElementById('copyInput')
      if (type == 1) {
        txt.value = this.lecturerUrl
      } else if (type == 2) {
        txt.value = this.guestUrl
      } else {
        txt.value = this.audienceUrl
      }
      // if (navigator.userAgent.match(/(iPhone|iPod|iPad|Mac);?/i)) {
      if (
        navigator.userAgent.indexOf('Safari') > -1 &&
        navigator.userAgent.indexOf('Chrome') < 1
      ) {
        var el = document.createElement('input')
        el.value = txt.value //要复制的内容
        el.style.opacity = '0'
        document.body.appendChild(el)
        var editable = el.contentEditable
        var readOnly = el.readOnly
        el.contentEditable = true
        el.readOnly = false
        const range = document.createRange()
        range.selectNodeContents(el)
        var sel = window.getSelection()
        sel.removeAllRanges()
        sel.addRange(range)
        el.setSelectionRange(0, 999999)
        el.contentEditable = editable
        el.readOnly = readOnly
        var ret = document.execCommand('copy')
        el.blur()
      } else {
        txt.select() //选择对象
        document.execCommand('copy')
      }

      vm.$message({
        type: 'success',
        message: '分享链接已复制，快分享给好友吧',
      })
    },

    //预览二维码
    previewQrcode() {
      vm.link = this.audienceUrl

      vm.dialogVisible = true
      vm.$nextTick(() => {
        vm.qrcode()
      })
    },
    //  生成二维码
    qrcode() {
      if (vm.qrcodeBox) {
        vm.qrcodeBox.makeCode(vm.link)
        return
      }
      vm.qrcodeBox = new QRCode('qrcode', {
        width: 400,
        height: 400,
        text: vm.link, // 二维码内容
        // render: 'canvas' ,   // 设置渲染方式（有两种方式 table和canvas，默认是canvas）
        // background: '#f0f',   // 背景色
        // foreground: '#ff0'    // 前景色
      })
    },

    // 关闭预览弹框
    handleClose() {
      vm.dialogVisible = false
    },

    downlodExcel() {
      let params = {
        rtcId: this.rtcId,
        // rtcId: 372
      }
      downloadSigninfo(params)
        .then((res) => {
          // vm.GET(`rtc/liveAdmin/download/signInfo/` + params.rtcId, { responseType: 'blob' }).then((res) => {
          closeLoading(this)
          // const aLink = document.createElement("a");
          // let blob = new Blob([res], {type: "application/vnd.ms-excel;charset=utf-8"});
          // // let downloadUrl = URL.createObjectURL(blob);
          // // window.location.href = downloadUrl;
          // aLink.href = URL.createObjectURL(blob);
          // aLink.setAttribute('download', '123' + '.xlsx'); // 设置下载文件名称
          // aLink.click();
          // this.$refs.loadElement.appendChild(aLink);

          // setTimeout(() => {
          //   window.open(downloadUrl);
          // }, 500);

          if (res.code == '000000') {
            this.downloadExcelFile(res.data)
            this.$message.success('下载成功')
            // vm.getLiveList("", "");
          } else {
            this.$message.error('下载失败，请重试')
          }
        })
        .catch((error) => {
          this.$message.error('请重试')
        })
    },

    /* 文件下载*/
    downloadExcelFile(base64) {
      let a = document.createElement('a')
      vm.uploadHref = 'data:application/xls;base64,' + base64
      a.setAttribute('href', vm.uploadHref)
      a.setAttribute(
        'download',
        '签到人数统计' + new Date().getTime() + '.xlsx'
      )
      // if (flag && flag == 2) {
      //   a.setAttribute('download',vm.exportFileName);
      // } else {
      //   a.setAttribute('download',vm.uploadFileName);
      // }
      a.click()
    },

    jumpUrl(type) {
      var url
      if (type == 1) {
        url = this.lecturerUrl
      } else if (type == 2) {
        url = this.guestUrl
      }
      window.open(url)
    },
    /*
     * 使用download.js 强制浏览器下载图片、视频等文件
     * @param {any} url url链接地址
     * @param {any} strFileName 文件名
     * @param {any} strMimeType 文件类型
     */
    downloadfile(url, strFileName, strMimeType) {
      let xmlHttp = null
      if (window.ActiveXObject) {
        // IE6, IE5 浏览器执行代码
        xmlHttp = new ActiveXObject('Microsoft.XMLHTTP')
      } else if (window.XMLHttpRequest) {
        // IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
        xmlHttp = new XMLHttpRequest()
      }
      //2.如果实例化成功，就调用open（）方法：
      if (xmlHttp != null) {
        xmlHttp.open('get', url, true)
        xmlHttp.responseType = 'blob' //关键
        xmlHttp.send()
        xmlHttp.onreadystatechange = doResult //设置回调函数
      }
      vm.downloadSuccessStatus = 3 // 下载中...

      function doResult() {
        if (xmlHttp.readyState == 4) {
          //4表示执行完成

          if (xmlHttp.status == 200) {
            //200表示执行成功
            DownloadJS(xmlHttp.response, strFileName, strMimeType)
            vm.downloadSuccessStatus = 5 // 下载成功
            vm.$message.success('下载成功')
            vm.downloadSuccessStatus = 1 // 重置
          }
          // else {
          //   vm.$message.error("下载失败");
          // }
        }
      }
    },

    getFileName(url) {
      const urlArray = url.split('/')
      const length = urlArray.length
      const fileName = urlArray[length - 1]

      return fileName
    },

    getFileType(fileName) {
      // 后缀获取
      let suffix = ''
      // 获取类型结果
      let result = ''
      try {
        const flieArr = fileName.split('.')
        suffix = flieArr[flieArr.length - 1]
      } catch (err) {
        suffix = ''
      }
      // fileName无后缀返回 false
      if (!suffix) {
        return false
      }
      suffix = suffix.toLocaleLowerCase()
      // 图片格式
      const imglist = ['png', 'jpg', 'jpeg', 'bmp', 'gif']
      // 进行图片匹配
      result = imglist.find((item) => item === suffix)
      if (result) {
        return 'image'
      }
      // 匹配txt
      const txtlist = ['txt']
      result = txtlist.find((item) => item === suffix)
      if (result) {
        return 'txt'
      }
      // 匹配 excel
      const excelist = ['xls', 'xlsx']
      result = excelist.find((item) => item === suffix)
      if (result) {
        return 'excel'
      }
      // 匹配 word
      const wordlist = ['doc', 'docx']
      result = wordlist.find((item) => item === suffix)
      if (result) {
        return 'word'
      }
      // 匹配 pdf
      const pdflist = ['pdf']
      result = pdflist.find((item) => item === suffix)
      if (result) {
        return 'pdf'
      }
      // 匹配 ppt
      const pptlist = ['ppt', 'pptx']
      result = pptlist.find((item) => item === suffix)
      if (result) {
        return 'ppt'
      }
      // 匹配 视频
      const videolist = [
        'mp4',
        'm2v',
        'mkv',
        'rmvb',
        'wmv',
        'avi',
        'flv',
        'mov',
        'm4v',
      ]
      result = videolist.find((item) => item === suffix)
      if (result) {
        return 'video'
      }
      // 匹配 音频
      const radiolist = ['mp3', 'wav', 'wmv']
      result = radiolist.find((item) => item === suffix)
      if (result) {
        return 'radio'
      }
      // 其他 文件类型
      return 'other'
    },
  },
}
</script>

<style lang="scss">
.yqrange-index-wrapper {
  .yqrange-index-content {
    background: #fff;
    padding: 10px;
    .header-title {
      padding: 10px 12px;
      font-size: 12px;
      color: #449284;
      border-bottom: 1px solid #efefef;
    }
  }
  .el-button--text {
    color: #449284;
    font-size: 14px;
    &::after {
      content: '';
      position: relative;
      height: 14px;
      /*border-right: 1px solid #EBEEF5;*/
      border-right: 1px solid #aaaaaa;
      padding-right: 10px;
    }
    &:last-of-type {
      &::after {
        content: '';
        position: relative;
        width: 1px;
        height: 14px;
        border-right: none;
      }
    }
  }
}
.live_url_style {
  display: flex;
  padding: 10px;
}
.href_outer_border {
  margin-top: 10px;
}
.href_style {
  width: 1500px;
  background-color: #d8d8d8;
  padding: 10px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.href_button_style {
  margin-left: 35px;
}
.hidden-input {
  height: 0;
}
.qrcode-wrap {
  width: 400px;
  height: 400px;
  margin: 0 auto;
}
.el-select .el-input__inner {
  height: 32px;
  line-height: 32px;
}
</style>
