<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="附件名称" prop="imageName">
        <el-input v-model="queryParams.imageName" placeholder="请输入附件名称" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="附件简介" prop="imageIntroduce">
        <el-input v-model="queryParams.imageIntroduce" placeholder="请输入附件简介" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <el-form-item label="附件类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择附件类型" clearable size="small">
          <el-option v-for="dict in dict.type.image_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="附件状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择附件状态">
          <el-option v-for="dict in dict.type.image_status" :key="dict.value" :label="dict.label"
            :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:image:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:image:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:image:remove']">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="imageList" @selection-change="handleSelectionChange" :max-height="tableMaxHeight">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="附件ID" align="center" prop="imageId" /> -->
      <el-table-column label="附件名称" align="center" prop="imageName" />
      <el-table-column label="附件内容" align="center" prop="imageContent" width="110px">
        <template slot-scope="scope">
          <img @click="imagew(scope.row.imageContent)" :src="defaultSettings.urls + '/prod-api' + scope.row.imageContent"
            style="width: 100px;height: 100px;" />
        </template>
      </el-table-column>
      <el-table-column label="附件简介" align="center" prop="imageIntroduce" />
      <el-table-column label="附件类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.image_type" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="附件状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.image_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:image:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:image:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改附件信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="附件名称" prop="imageName">
              <el-input v-model="form.imageName" placeholder="请输入附件名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="附件类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择附件类型">
                <el-option v-for="dict in dict.type.image_type" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>

          </el-col>
          <el-col :span="12">
            <el-form-item label="附件简介" prop="imageIntroduce">
              <el-input v-model="form.imageIntroduce" placeholder="请输入附件简介" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="附件状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择附件状态">
                <el-option v-for="dict in dict.type.image_status" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="附件内容">
              <fileUploads v-model="form.imageContent" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="图片预览" :visible.sync="opende" width="1000px" append-to-body style="text-align: center;">
      <img :src="defaultSettings.urls  + '/prod-api'+ urls" style="width: 80%;" v-if="jeuhse == false">
      <video-player v-if="jeuhse == true" style="width: 960px; " class="video-player vjs-custom-skin" ref="videoPlayer" name="videoPlayer" id="video"
        :playsinline="true"  :options="playerOptions" @play="onPlayerPlay($event)"
        @pause="onPlayerPause($event)" @ended="onPlayerEnded($event)" @waiting="onPlayerWaiting($event)"
        @timeupdate="onPlayerTimeupdate($event)" @statechanged="playerStateChanged($event)"
        @canplaythrough="onPlayerCanplaythrough($event)" @ready="playerReadied"></video-player>
    </el-dialog>

  </div>
</template>

<script>
  import {
    listImage,
    getImage,
    delImage,
    addImage,
    updateImage
  } from "@/api/system/image";
  const defaultSettings = require("@/settings.js");
  import {
    videoPlayer
  } from "vue-video-player";
  import "video.js/dist/video-js.css";
  import "vue-video-player/src/custom-theme.css";
  export default {
    name: "showVideo",
    dicts: ['image_type', 'image_status' ,],
    components: {
                videoPlayer
            },
    data() {
      return {
        // 遮罩层
        loading: true,
        process: process.env.VUE_APP_BASE_API,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 附件信息表格数据
        imageList: [],
        del: [],
        urls: '',
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        defaultSettings,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          imageName: null,
          imageIntroduce: null,
          status: null,
          type: null,
          isDel: null,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          imageName: [{
            required: true,
            message: "附件名称不能为空",
            trigger: "blur"
          }],
        },
        opende: false,
        playTime: '',
        current: '',
        playerOptions: {
          playbackRates: [0.5, 1.0, 1.5, 2.0], // 可选的播放速度
          autoplay: false, // 如果为true,浏览器准备好时开始回放。
          muted: false, // 默认情况下将会消除任何音频。
          loop: false, // 是否视频一结束就重新开始。
          preload: "auto", // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
          language: "zh-CN",
          aspectRatio: "16:9", // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
          fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
          sources: [{
            type: "video/mp4", // 类型
            src: "" // url地址
          }],
          poster: "", // 封面地址
          notSupportedMessage: "此视频暂无法播放，请稍后再试", // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
          controlBar: {
            timeDivider: true, // 当前时间和持续时间的分隔符
            durationDisplay: true, // 显示持续时间
            remainingTimeDisplay: false, // 是否显示剩余时间功能
            fullscreenToggle: true ,// 是否显示全屏按钮
            }
          },
          jeuhse:false,
          tableMaxHeight:300
        };
      },
      created() {

          this.getList();
         window.onresize = () => {
               this.changeTableMaxHeight()
             }
             this.changeTableMaxHeight()
        },
        destroyed () {
            window.onresize = null
          },
        mounted() {
          window.onresize = () => {
                this.changeTableMaxHeight()
              }
              this.changeTableMaxHeight()
        },
        methods: {
          /** 查询附件信息列表 */
          getList() {
            this.loading = true;
            listImage(this.queryParams).then(response => {
              this.imageList = response.rows;
              // this.imageList.filter( router =>{
              //   // 　#响应成功的数据中提取url赋值给变量url
              //        this.url = router.imageContent;
              //   // 　　　　　　#将url赋值给src
              //   　　　　　　this.playerOptions['sources'][0]['src'] = defaultSettings.urls + this.url;
              // })
              this.total = response.total;
              this.loading = false;
            });
          },
          // 图片预览列表
          imagew(index) {
            this.urls = index
            this.opende = true
            var hyeowc = index
            console.log(hyeowc)
             var indexde =  index.lastIndexOf("\.");
            hyeowc=hyeowc.substring(indexde+1,hyeowc.length);
             console.log(hyeowc);
             if(hyeowc == "mp3" || hyeowc == "mp4"){
               this.jeuhse = true //视频
             }else{
               this.jeuhse = false  //图片
             }
          this.playerOptions['sources'][0]['src'] = defaultSettings.urls + this.urls;

          },
          // 取消按钮
          cancel() {
            this.open = false;
            this.reset();
          },
          // 表单重置
          reset() {
            this.form = {
              imageId: null,
              imageName: null,
              imageContent: null,
              imageIntroduce: null,
              status: null,
              type: null,
              isDel: null,
              createBy: null,
              createTime: null,
              updateBy: null,
              updateTime: null,
              remark: null
            };
            this.resetForm("form");
          },
          /** 搜索按钮操作 */
          handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
          },
          /** 重置按钮操作 */
          resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
          },
          // 多选框选中数据
          handleSelectionChange(selection) {
            this.ids = selection.map(item => item.imageId)
            this.single = selection.length !== 1
            this.multiple = !selection.length
          },
          /** 新增按钮操作 */
          handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加附件信息";
          },
          /** 修改按钮操作 */
          handleUpdate(row) {
            this.reset();
            const imageId = row.imageId || this.ids
            getImage(imageId).then(response => {
              this.form = response.data;
              this.open = true;
              this.title = "修改附件信息";
            });
          },
          /** 提交按钮 */
          submitForm() {
            this.$refs["form"].validate(valid => {
              if (valid) {
                if (this.form.imageId != null) {
                  updateImage(this.form).then(response => {
                    this.$modal.msgSuccess("修改成功");
                    this.open = false;
                    this.getList();
                  });
                } else {
                  addImage(this.form).then(response => {
                    this.$modal.msgSuccess("新增成功");
                    this.open = false;
                    this.getList();
                  });
                }
              }
            });
          },
          /** 删除按钮操作 */
          handleDelete(row) {
            const imageIds = row.imageId || this.ids;
            this.$modal.confirm('是否确认删除附件信息编号为"' + imageIds + '"的数据项？').then(function() {
              return delImage(imageIds);
            }).then(() => {
              this.getList();
              this.$modal.msgSuccess("删除成功");
            }).catch(() => {});
          },
          /** 导出按钮操作 */
          handleExport() {
            this.download('system/image/export', {
              ...this.queryParams
            }, `image_${new Date().getTime()}.xlsx`)
          },
          // 获取屏幕高度
          showFilterForm () {
                this.filterActive = !this.filterActive
                this.changeTableMaxHeight()
              },

              changeTableMaxHeight () {
                let height = document.body.offsetHeight // 网页可视区域高度
                // if (this.filterActive) {
                //   this.tableMaxHeight = height - 320
                // } else {
                  this.tableMaxHeight = height - 250
                // }
                console.log(height)
              },
          // 播放回调
                      onPlayerPlay(player) {
                          console.log("player play!", player);
                      },

                      // 暂停回调
                      onPlayerPause(player) {
                          console.log("player pause!", player);
                      },

                      // 视频播完回调
                      onPlayerEnded($event) {
                          // console.log(player);
                      },
                      // DOM元素上的readyState更改导致播放停止
                      onPlayerWaiting(player) {
                          let time = localStorage.getItem("cacheTime")
                          if(player.cache_.currentTime - Number(time) > 0.1){
                              this.current = Number(time)
                              this.playerReadied(player)
                          }else{
                              this.current = player.cache_.currentTime
                          }
                      },

                      // 已开始播放回调
                      onPlayerPlaying($event) {
                          // console.log(player)
                      },

                      // 当播放器在当前播放位置下载数据时触发
                      onPlayerLoadeddata($event) {
                          // console.log(player)
                      },

                      // // 当前播放位置发生变化时触发。
                      onPlayerTimeupdate(player) {
                          this.playTime = player.cache_.currentTime
                          let playTime = player.cache_.currentTime
                          setTimeout(function () {
                              localStorage.setItem("cacheTime",playTime)
                          },500)


                          let time = localStorage.getItem("cacheTime")
                          if(player.cache_.currentTime - Number(time) > 2){
                              this.current = Number(time)
                              this.playerReadied(player)
                          }else{
                              this.current = player.cache_.currentTime
                          }
                      },

                      //媒体的readyState为HAVE_FUTURE_DATA或更高
                      onPlayerCanplay(player) {
                          // console.log('player Canplay!', player)
                      },

                      //媒体的readyState为HAVE_ENOUGH_DATA或更高。这意味着可以在不缓冲的情况下播放整个媒体文件。
                      onPlayerCanplaythrough(player) {
                          // console.log('player Canplaythrough!', player)
                      },

                      //播放状态改变回调
                      playerStateChanged(playerCurrentState) {
                          // console.log('player current update state', playerCurrentState)
                      },

                      //将侦听器绑定到组件的就绪状态。与事件监听器的不同之处在于，如果ready事件已经发生，它将立即触发该函数。。
                      playerReadied(player) {
                          // console.log('example player 1 readied', player);
                          player.currentTime(this.current)
                      }
                      // }
        }
    };
</script>
<style type="text/css" lang="scss">
  .vjs-custom-skin > .video-js .vjs-big-play-button {
          background-color: rgba(0,0,0,0.45);
          font-size: 3.0em;
          /* border-radius: 50%; */
          height: 1.5em !important;
          line-height:1.5em !important;
          margin-top: -1em !important;
      }
      /*这里用了第三方vue-video-player插件，但这个插件有bug，设置globalSetting:{controls:true}隐藏进度条不生效，故可设置插件样式进行隐藏vjs-progress-contro*/
      .vjs-progress-control {
          /*visibility:hidden;       // 隐藏进度条*/
      }
</style>
