<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="报价单" prop="uuid">
        <el-select v-model="queryParams.uuid" placeholder="请选择" clearable>
          <el-option
            v-for="dict in releaseOptions"
            :key="dict.uuid"
            :label="dict.offerName"
            :value="dict.uuid"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="项目名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类型" prop="typeVal">
        <el-select v-model="queryParams.typeVal" placeholder="请选择" clearable>
          <el-option
            v-for="dict in dict.type.tuya_supplier_play_state"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </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="['tuya:play: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="['tuya:play: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="['tuya:play:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['tuya:play:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="playList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="项目名称" align="center" prop="name" :show-overflow-tooltip="true" />
      <el-table-column label="类型" align="center" prop="typeVal">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.tuya_supplier_play_state" :value="scope.row.typeVal"/>
        </template>
      </el-table-column>
      <el-table-column label="内容" align="center" prop="content" :show-overflow-tooltip="true" />
      <el-table-column label="图片" align="center" prop="imgUrl">
        <template slot-scope="scope">
          <image-preview :src="scope.row.imgUrl" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="视频" align="center" prop="videoUrl" width="90">
        <template slot-scope="scope">
          <el-button
            @click="openVideo(scope.row)"
            size="small"
          >查看视频</el-button>
        </template>
      </el-table-column>
      <el-table-column label="天数" align="center" prop="dayNum" />
      <el-table-column label="修改内容" align="center" prop="updateContent" :show-overflow-tooltip="true" />
      <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="['tuya:play:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['tuya:play: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="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="24">
          <el-col :span="12">
            <div class="grid-content bg-purple">
              <el-form-item label="路线编号" prop="uuid">
                <el-input v-model="form.uuid" placeholder="请输入" :disabled="true" />
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="grid-content bg-purple">
              <el-form-item label="项目名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入" />
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="grid-content bg-purple">
              <el-form-item label="类型" prop="typeVal">
                <el-radio-group v-model="form.typeVal">
                  <el-radio
                    v-for="dict in dict.type.tuya_supplier_play_state"
                    :key="dict.value"
                    :label="dict.value"
                  >{{ dict.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="grid-content bg-purple">
              <el-form-item label="天数" prop="dayNum">
                <el-input-number v-model="form.dayNum" controls-position="right" :min="0" :precision="1"/>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="grid-content bg-purple">
              <el-form-item label="图片" prop="imgUrl">
                <div class="update-Img">
                  <el-upload
                    action="#"
                    list-type="picture-card"
                    :limit="1"
                    :auto-upload="false"
                    :on-change="uploadImage"
                    :on-remove="handeRemove"
                    :on-exceed="handleExceed"
                    :on-preview="handlePictureCardPreview"
                    :file-list="fileList"
                    accept=".jpg, .jpeg, .gif, .webp, .png"
                  >
                    <i class="el-icon-plus"></i>
                  </el-upload>
                  <el-dialog :visible.sync="dialogVisible">
                    <img width="100%" v-if="imageUrl" :src="imageUrl" alt="">
                  </el-dialog>
                </div>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="grid-content bg-purple">
              <el-form-item label="视频" prop="videoUrl">
                <div class="update-video">
                  <el-input v-model="form.videoUrl" placeholder="请输入"/>
                  <el-upload
                    class="video-uploader"
                    action="#"
                    :on-change="uploadVideo"
                    :limit="1"
                    :auto-upload="false"
                    :show-file-list="false"
                    accept=".mp4"
                  >
                    <el-button class="uploader-button" size="small">
                      选择
                      <i class="el-icon-upload el-icon--right"></i>
                    </el-button>
                  </el-upload>
                </div>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="24">
            <div class="grid-content bg-purple">
              <el-form-item label="内容" prop="content">
                <el-input v-model="form.content" type="textarea" placeholder="请输入内容" :rows="5"/>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="24">
            <div class="grid-content bg-purple">
              <el-form-item label="修改内容" prop="updateContent">
                <el-input v-model="form.updateContent" type="textarea" placeholder="请输入内容" :rows="5"/>
              </el-form-item>
            </div>
          </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
      :visible.sync="videoDialog"
      width="70%"
      center
      class="videoPlayer"
    >
      <div>
        <video-player
          style="width: 100%; height: 500px"
          class="video-player vjs-custom-skin"
          ref="videoPlayer"
          :playsline="false"
          :options="playerOptions"
        ></video-player>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPlay, getPlay, delPlay, addPlay, updatePlay } from "@/api/tuya/supplierPlay";
import {selectlist} from "@/api/tuya/supplierPlay";
import {uploadAvatar} from "@/api/tuya/stiesinfo";
import { videoPlayer } from "vue-video-player";
import "video.js/dist/video-js.css";

export default {
  name: "Play",
  dicts: ['sys_normal_disable','tuya_supplier_play_state'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 平台报价单项目表格数据
      playList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        uuid: null,
        typeVal: null,
        content: null,
        imgUrl: null,
        videoUrl: null,
        name: null,
        dayNum: null,
        updateContent: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      //报价单下拉
      releaseOptions: [],
      videoDialog:false,
      srcList: [],
      playerOptions: {
        playbackRates: [0.7, 1.0, 1.5, 2.0], // 播放速度
        autoplay: false, // 如果true,浏览器准备好时开始回放。
        controls: 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", // 这里的种类支持很多种：基本视频格式、直播、流媒体等，具体可以参看git网址项目
            src: "", // url地址
          },
        ],
        // poster: "../../../../static/full_res.jpg", // 你的封面地址
        width: document.documentElement.clientWidth, // 播放器宽度
        notSupportedMessage: "此视频暂无法播放，请稍后再试", // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true,
          durationDisplay: true,
          remainingTimeDisplay: false,
          fullscreenToggle: true, // 全屏按钮
        },
      },
      fileList: [],
      //图片地址
      imageUrl: "",
      dialogVisible: false,
    };
  },
  created() {
    this.getList();
    this.getSelect();
  },
  methods: {
    // 上传视频
    uploadVideo(file) {
      const isMP4 = file.raw.type === "video/mp4";
      const isLt2M = file.size / 1024 / 1024 < 50;
      if (!isMP4) {
        this.$message.error("只能上传视频格式为mp4！");
      } else if (!isLt2M) {
        this.$message.error('图片大小不能超过 10MB!');
      } else {
        let fd = new FormData()
        fd.append('file', file.raw)
        uploadAvatar(fd).then(response => {
          this.form.videoUrl = response.data;
        });
      }
    },
    // 上传图片
    uploadImage(file) {
      const isJPG = file.raw.type === "image/jpg";
      const isJPEG = file.raw.type === "image/jpeg";
      const isPNG = file.raw.type === "image/png";
      const isGIF = file.raw.type === "image/gif";
      const isBMP = file.raw.type === "image/bmp";
      const isLt2M = file.size / 1024 / 1024 < 5;
      if (!isJPG && !isJPEG && !isPNG && !isGIF && !isBMP) {
        this.$message.error("只能上传图片格式为jpg,jpeg,png,gif,bmp！");
      } else if (!isLt2M) {
        this.$message.error('图片大小不能超过 5MB!');
      } else {
        let fd = new FormData()
        fd.append('file', file.raw)
        uploadAvatar(fd).then(response => {
          this.form.imgUrl = response.data;
        });
      }
    },
    //图片预览
    handlePictureCardPreview(file) {
      this.imageUrl = file.url;
      this.dialogVisible = true;
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传图片数量不能超过1个!`);
    },
    handeRemove(file) {
      this.form.imgUrl = "";
    },
    openVideo(row) {
      this.videoDialog = true;
      this.row = row;
      this.playerOptions.sources[0].src = row.videoUrl;
    },
    /** 查询报价单下拉 */
    getSelect() {
      selectlist().then(response => {
        this.releaseOptions = response.data;
      });
    },
    /** 查询平台报价单项目列表 */
    getList() {
      this.loading = true;
      listPlay(this.queryParams).then(response => {
        this.playList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        uuid: null,
        typeVal: null,
        content: null,
        imgUrl: null,
        videoUrl: null,
        name: null,
        dayNum: null,
        updateContent: null
      };
      this.fileList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加平台报价单项目";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getPlay(id).then(response => {
        this.form = response.data;
        if (response.data.imgUrl != '' && response.data.imgUrl != null) {
          this.fileList.push({url: response.data.imgUrl})
        }
        this.open = true;
        this.title = "修改平台报价单项目";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePlay(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPlay(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除平台报价单项目编号为"' + ids + '"的数据项？').then(function() {
        return delPlay(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('tuya/play/export', {
        ...this.queryParams
      }, `play_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped lang="scss">
.update-video {
  display: flex;
  align-items: center;
}

.video-uploader {
  padding-left: 13px;
}

.uploader-button {
  height: 37px;
}
.my-img:hover{//使鼠标悬浮在图片上时出现手的形状
cursor:pointer;
}
.video-js .vjs-icon-placeholder {
  width: 50%;
  height: 50%;
  display: block;
}
.videoPlayer ::v-deep .el-dialog,
.el-pager li {
  background: none !important;
  margin-top: 6vh !important;
}
.my-img:hover{
  cursor:pointer;
}
</style>
