<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="直播名称" prop="liveName">
        <el-input
          v-model="queryParams.liveName"
          placeholder="请输入直播名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </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="['live:live: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="['live:live:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['live:live:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="liveList">
      <el-table-column label="直播封面" align="center" prop="liveImgUrl" width="180">
        <template slot-scope="scope">
          <el-image style="width: 180px;" :src="scope.row.liveImgUrl" mode="aspectFill" :preview-src-list="[scope.row.liveImgUrl]" />
        </template>
      </el-table-column>
      <el-table-column label="直播名称" align="center" prop="liveName" />
      <el-table-column label="显示类型" align="center" prop="showType">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.showType == 1">横屏</el-tag>
          <el-tag v-if="scope.row.showType == 2">竖屏</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="直播状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status == 1">待直播</el-tag>
          <el-tag v-if="scope.row.status == 2">直播中</el-tag>
          <el-tag v-if="scope.row.status == 3">已结束</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="主播ID" align="center" prop="anchorId" />
      <el-table-column label="直播类型" align="center" prop="liveType">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.liveType == 1">直播</el-tag>
          <el-tag v-if="scope.row.liveType == 2">录播</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startTime" width="180" />
      <el-table-column label="结束时间" align="center" prop="finishTime" width="180" />
      <el-table-column label="上下架" align="center" prop="isShow">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isShow == 1">上架</el-tag>
          <el-tag v-if="scope.row.isShow == 2">下架</el-tag>
        </template>
      </el-table-column>
      <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="['live:live:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['live:live: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="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="直播名称" prop="liveName">
          <el-input v-model="form.liveName" placeholder="请输入直播名称" />
        </el-form-item>
        <el-form-item label="显示类型" prop="showType">
          <el-radio-group v-model="form.showType">
            <el-radio :label="1">横屏</el-radio>
            <el-radio :label="2">竖屏</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="直播类型" prop="liveType">
          <el-radio-group disabled v-model="form.liveType">
            <el-radio :label="1">直播</el-radio>
            <el-radio :label="2">录播</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="直播描述" prop="liveDesc">
          <Editor ref="myeditor" :height="300" @on-text-change="updateText"/>
<!--          <Editor v-model="form.liveDesc" :height="300" placeholder="直播描述" />-->
        </el-form-item>
        <el-form-item label="录播视屏" prop="videoUrl">
          <file-upload v-model="form.videoUrl" :limit="1" :file-size="3" :file-type="['mp4']" />
          <el-button @click="getVideoDuration" v-loading="timeLoading">读取视屏时长</el-button>
          <p style="margin: 0;padding: 0;" v-loading="timeLoading">视屏时长：<span style="color: #ff4949;">{{form.durationTime}}</span></p>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker size="small"
            v-model="form.startTime"
            @change="timeChange"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="finishTime" v-loading="timeLoading">
          <el-date-picker size="small"
            v-model="form.finishTime"
            type="datetime"
            disabled
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="视屏播放结束">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="直播封面" prop="liveImgUrl">
          <image-upload v-model="form.liveImgUrl" :limit="1" />
        </el-form-item>
        <el-form-item label="上下架" prop="isShow">
          <el-radio-group v-model="form.isShow">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="2">下架</el-radio>
          </el-radio-group>
        </el-form-item>
      </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>
  </div>
</template>

<script>
import { listLive, getLive, delLive, addLive, updateLive, exportLive } from "@/api/live/live";
import Editor from '@/components/Editor/wang';
import articleDetails from "@/views/components/his/doctorArticleDetails.vue";

export default {
  name: "Live",
  components: { Editor },
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      timeLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 直播表格数据
      liveList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        liveName: null,
        liveDesc: null,
        showType: null,
        status: null,
        anchorId: null,
        liveType: null,
        startTime: null,
        finishTime: null,
        liveImgUrl: null,
        liveConfig: null,
        isShow: null,
        isDel: null,
        qwQrCode: null,
        rtmpUrl: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        liveName: [
          { required: true, message: "不能为空", trigger: "burl" }
        ],
        showType: [
          { required: true, message: "不能为空", trigger: "burl" }
        ],
        liveType: [
          { required: true, message: "不能为空", trigger: "burl" }
        ],
        videoUrl: [
          { required: true, message: "不能为空", trigger: "burl" }
        ],
        startTime: [
          { required: true, message: "不能为空", trigger: "burl" }
        ],
        liveImgUrl: [
          { required: true, message: "不能为空", trigger: "burl" }
        ],
        isShow: [
          { required: true, message: "不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询直播列表 */
    getList() {
      this.loading = true;
      listLive(this.queryParams).then(response => {
        this.liveList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    urlChange(url) {
      this.form.videoUrl = url;
      this.getVideoDuration();
    },
    getVideoDuration() {
      this.timeLoading = true;
      const videoElement = document.createElement('video');
      videoElement.src = this.form.videoUrl;
      videoElement.onloadedmetadata = () => {
        this.form.duration = Math.floor(videoElement.duration);  // 秒
        this.form.durationTime = this.secondsToTime(this.form.duration);
        this.timeChange();
        this.timeLoading = false;
      };
    },
    changeDuration(e){
      this.form.duration = e.duration;
      this.form.durationTime = e.time;
      this.$forceUpdate();
      this.timeChange();
    },
    timeChange(){
      if(!this.form.startTime) return;
      if(!this.form.duration) return;
      console.info(this.form.startTime)
      const startDateTime = new Date(this.form.startTime);
      // 将视频时长（秒）加到开始时间
      const endDateTime = new Date(startDateTime.getTime() + this.form.duration * 1000); // 毫秒为单位
      // 格式化为年月日 时分秒
      this.form.finishTime = this.formatDate(endDateTime);
      this.$forceUpdate();
    },
    // 将秒数转换为时分秒
    secondsToTime(seconds) {
      const hours = Math.floor(seconds / 3600);
      const minutes = Math.floor((seconds % 3600) / 60);
      const secs = Math.floor(seconds % 60);
      return `${this.pad(hours)}:${this.pad(minutes)}:${this.pad(secs)}`;
    },
    // 补零处理
    pad(number) {
      return number < 10 ? `0${number}` : number;
    },
    // 格式化日期为 年月日 时分秒
    formatDate(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      const seconds = date.getSeconds().toString().padStart(2, '0');

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        showType: 1,
        liveType: 2,
        isShow: 1,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.liveId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      setTimeout(() => {
        this.$refs.myeditor.setText("");
      }, 100);
      this.title = "添加直播";
    },
    updateText(text){
      this.form.liveDesc=text
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const liveId = row.liveId || this.ids
      getLive(liveId).then(response => {
        this.form = response.data;
        if(this.form.duration){
          this.form.durationTime = this.secondsToTime(this.form.duration)
        }
        setTimeout(() => {
          if(this.form.liveDesc==null){
            this.$refs.myeditor.setText("");
          }else{
            this.$refs.myeditor.setText(this.form.liveDesc);
          }
        }, 1);
        this.open = true;
        this.title = "修改直播";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.liveId != null) {
            updateLive(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addLive(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const liveIds = row.liveId || this.ids;
      this.$confirm('是否确认删除直播编号为"' + liveIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delLive(liveIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有直播数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportLive(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>
