<template>
  <div class="app-container">
    <el-row :gutter="2">
      <el-col :span="6">
        <el-card>
          <div slot="header">
            <span>课程分类</span>
            <el-button
              type="primary"
              @click="handleAddCourse"
              size="small"
              style="margin-left: 8px"
              >新增</el-button
            >
          </div>
          <el-table :data="courseList" :show-header="false">
            <el-table-column label="分类名">
              <template slot-scope="scope">{{ scope.row.name }}</template>
            </el-table-column>
            <el-table-column align="center" label="操作" fixed="right">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  plain
                  size="small"
                  @click="handleUpdateCourse(scope)"
                  icon="el-icon-edit"
                ></el-button>
                <el-button
                  type="danger"
                  plain
                  size="small"
                  @click="handleDeleteCourse(scope)"
                  icon="el-icon-delete"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      <el-col :span="18">
        <el-card>
          <div slot="header" class="clearfix">
            <span>视频列表</span>
          </div>
          <el-button type="primary" @click="handleAddVideo" size="small"
            >新增</el-button
          >
          <el-table :data="videoList.results">
            <el-table-column label="名称">
              <template slot-scope="scope">
                <el-link type="primary" :href="scope.row.mediaurl" target="_blank">{{ scope.row.name }}</el-link>
              </template>
            </el-table-column>
            <el-table-column label="描述">
              <template slot-scope="scope">{{
                scope.row.description
              }}</template>
            </el-table-column>
            <el-table-column label="观看数">
              <template slot-scope="scope">{{scope.row.viewsp}}/{{scope.row.views}}</template>
            </el-table-column>
            <el-table-column label="创建时间">
              <template slot-scope="scope">{{
                scope.row.create_time
              }}</template>
            </el-table-column>
         <el-table-column align="center" label="操作" fixed="right">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  plain
                  size="small"
                  @click="handleUpdateVideo(scope)"
                  icon="el-icon-edit"
                ></el-button>
                <el-button
                  type="danger"
                  plain
                  size="small"
                  @click="handleDeleteVideo(scope)"
                  icon="el-icon-delete"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="videoList.count > 0"
            :total="videoList.count"
            @pagination="getVideoList"
          />
        </el-card>
      </el-col>
    </el-row>
    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogType === 'update' ? '编辑分类' : '新增分类'"
    >
      <el-form :model="course" label-width="80px" ref="courseForm">
        <el-form-item label="名称" prop="name">
          <el-input v-model="course.name" placeholder="名称" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="danger" @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmCourse('courseForm')"
          >确认</el-button
        >
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="dialogVisible2"
      :destory-on-close="true"
      :title="dialogType2 === 'update' ? '编辑视频' : '新增视频'"
      v-if="dialogVisible2"
    >
      <el-form :model="video" label-width="80px" ref="videoForm">
        <el-form-item label="分类" prop="course" required>
          <el-select
            v-model="video.course"
            placeholder="请选择课程分类"
            style="width: 100%"
          >
            <el-option
              v-for="item in courseList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="name" required>
          <el-input v-model="video.name" placeholder="名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="video.description"
            placeholder="描述"
            type="textarea"
            :rows="2"
          />
        </el-form-item>
        <el-row v-if="dialogType2=='create'">
          <el-col :span="12">
                    <el-form-item label="封面" prop="coverurl" required>
          <input
            type="file"
            ref="posterInput"
            accept="image/*"
            v-if="!uploading && video.coverurl == null"
          />
          <el-progress
            :percentage="uploaderInfo.coverProgress"
            v-if="uploading"
          ></el-progress>
        </el-form-item>
          </el-col>
          <el-col :span="12">
        <el-form-item label="视频" prop="mediaurl" required>
          <input
            type="file"
            ref="videoInput"
            accept=".mp4,.m3u8,.avi,.rmvb"
            v-if="!uploading && video.mediaurl == null"
          />
          <el-progress
            :percentage="uploaderInfo.progress"
            v-if="uploading"
          ></el-progress>
        </el-form-item>
          </el-col>
                  <div style="text-align: center">
          <video
            :src="video.mediaurl"
            :poster="video.coverurl"
            controls
            style="width: 224; height: 140px"
            v-if="video.mediaurl != null"
          ></video>
          <el-button type="primary" size="small" @click="startUpload" v-if="showStart"
            >开始上传封面和视频</el-button
          >
        </div>
        </el-row>



      </el-form>
      <div slot="footer">
        <el-button type="danger" @click="dialogVisible2 = false"
          >取消</el-button
        >
        <el-button type="primary" @click="confirmVideo('videoForm')"
          >确认</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
const defaultCourse = { name: "" };
const defaultVideo = { name: "", mediaurl: null, coverurl: null };
import {
  getCourseList,
  createCourse,
  deleteCourse,
  updateCourse,
} from "@/api/course";
import {
  getVideoList,
  getSignature,
  createVideo,
  deleteVideo,
  updateVideo,
} from "@/api/video";
import Pagination from "@/components/Pagination";
import TcVod from "vod-js-sdk-v6";
import checkPermission from "@/utils/permission";
export default {
  components: { Pagination },
  data() {
    return {
      courseList: [],
      dialogVisible: false,
      dialogType: "create",
      course: { name: "" },
      videoList: { count: 0, results: [] },
      dialogVisible2: false,
      dialogType2: "create",
      video: { name: "" },
      uploading: false,
      posterPg: 20,
      videoPg: 20,
      showStart:true,
      uploaderInfo: {
        isVideoUploadSuccess: false,
        progress: 0,
        isCoverUploadSuccess: false,
        coverProgress: 0,
      },
    };
  },
  created() {
    this.getCourseList();
    this.getVideoList();
  },
  methods: {
    checkPermission,
    async getSignature() {
      const { data } = await getSignature();
      console.log(data);
      return data.signature;
    },
    startUpload() {
      var that = this;
      that.uploading = true;
      var mediaFile = that.$refs["videoInput"].files[0];
      var coverFile = that.$refs["posterInput"].files[0];
      const tcVod = new TcVod({
        getSignature: that.getSignature, // 前文中所述的获取上传签名的函数
      });
      const uploader = tcVod.upload({
        mediaFile: mediaFile,
        coverFile: coverFile,
      });
      that.showStart = false
      // 视频上传完成时
      uploader.on("media_upload", function (info) {
        that.uploaderInfo.isVideoUploadSuccess = true;
      });
      // 视频上传进度
      uploader.on("media_progress", function (info) {
        that.uploaderInfo.progress = parseInt(info.percent * 100);
      });
      // 封面上传完成时
      uploader.on("cover_upload", function (info) {
        that.uploaderInfo.isCoverUploadSuccess = true;
      });
      // 封面上传进度
      uploader.on("cover_progress", function (info) {
        that.uploaderInfo.coverProgress = parseInt(info.percent * 100);
      });
      uploader.done().then(function (doneResult) {
        // deal with doneResult
        that.uploading = false;
        that.video.fileid = doneResult.fileId;
        that.video.coverurl = doneResult.cover.url;
        that.video.mediaurl = doneResult.video.url;
      });
    },
    getCourseList() {
      getCourseList({ pageoff: true }).then((res) => {
        this.courseList = res.data;
      });
    },
    getVideoList() {
      getVideoList().then((res) => {
        this.videoList = res.data;
      });
    },
    handleAddCourse() {
      this.course = Object.assign({}, defaultCourse);
      this.dialogType = "create";
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs["courseForm"].clearValidate();
      });
    },
    handleUpdateCourse(scope) {
      this.course = Object.assign({}, scope.row); // copy obj
      this.dialogType = "update";
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs["courseForm"].clearValidate();
      });
    },
    handleDeleteCourse(scope) {
      this.$confirm("确认删除该分类吗?将丢失数据!", "警告", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "error",
      })
        .then(async () => {
          await deleteCourse(scope.row.id);
          this.getCourseList();
          this.$message.success("成功删除");
        })
        .catch((err) => {
          // console.error(err);
        });
    },
    async confirmCourse(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          const isEdit = this.dialogType === "update";
          if (isEdit) {
            updateCourse(this.course.id, this.course).then(res => {
              this.getCourseList();
              this.dialogVisible = false;
              this.$message.success("成功");
            });
          } else {
            createCourse(this.course).then((res) => {
              this.getCourseList();
              this.dialogVisible = false;
              this.$message.success("成功");
            });
          }
        } else {
          return false;
        }
      });
    },
    handleAddVideo() {
      this.video = Object.assign({}, defaultVideo);
      this.dialogType2 = "create";
      this.dialogVisible2 = true;
      this.$nextTick(() => {
        this.$refs["videoForm"].clearValidate();
      });
    },
    handleUpdateVideo(scope) {
      this.video = Object.assign({}, scope.row); // copy obj
      this.dialogType2 = "update";
      this.dialogVisible2 = true;
      this.$nextTick(() => {
        this.$refs["videoForm"].clearValidate();
      });
    },
    handleDeleteVideo(scope) {
      this.$confirm("确认删除该视频吗?将丢失数据!", "警告", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "error",
      })
        .then(async () => {
          await deleteCourse(scope.row.id);
          this.getCourseList();
          this.$message.success("成功删除");
        })
        .catch((err) => {
          // console.error(err);
        });
    },
    async confirmVideo(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          const isEdit = this.dialogType2 === "update";
          if (isEdit) {
            updateVideo(this.video.id, this.video).then(() => {
              this.getVideoList();
              this.dialogVisible2 = false;
              this.$message.success("成功");
            });
          } else {
            createVideo(this.video).then((res) => {
              this.getVideoList();
              this.dialogVisible2 = false;
              this.$message.success("成功");
            });
          }
        } else {
          return false;
        }
      });
    },
  },
};
</script>