<template>
  <div class="coursehour-total-wrapper">
    <div class="tools-wrapper">
      <el-button type="primary" @click="addClass">新增课时</el-button>
      <el-button type="warning" :disabled="isEditable" @click="editClass"
        >编辑课时</el-button
      >
      <el-button type="danger" :disabled="isDeleteable" @click="deleteClass"
        >删除课时</el-button
      >
    </div>
    <div class="table-wrapper">
      <el-table :data="tableData" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="title" label="课时名称" />
        <el-table-column prop="time" label="课时时长" />
      </el-table>
    </div>
    <el-dialog title="新增课时" :visible.sync="addDialogFormVisible">
      <el-form
        v-if="addDialogFormVisible"
        ref="addform"
        :model="formInfo"
        label-width="120px"
        :rules="rules"
      >
        <el-form-item label="课时名称" prop="title">
          <el-input v-model="formInfo.title" />
        </el-form-item>
        <el-form-item label="导入视频文件" prop="fileUrl">
          <div class="import-file-total-wrapper">
            <div class="import-file-wrapper">
              <label style="width: 100%;height: 100%;">
                导入文件
                <input
                  ref="importfile"
                  type="file"
                  hidden
                  @change="importFile"
                />
              </label>
            </div>
          </div>
          <div class="import-file-elprogress-wrapper">
            <el-progress :percentage="importfilePercentage" />
          </div>
          <div v-if="formInfo.fileUrl">{{ formInfo.fileUrl.name }}</div>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="submitFileName">提交</el-button>
      </div>
    </el-dialog>
    <el-dialog title="修改课时" :visible.sync="editDialogFormVisible">
      <el-form
        ref="editform"
        :model="editFormInfo"
        label-width="120px"
        :rules="editrules"
      >
        <el-form-item label="课时名称" prop="title">
          <el-input v-model="editFormInfo.title" />
        </el-form-item>
        <el-form-item label="导入视频文件" prop="fileUrl">
          <div class="import-file-total-wrapper">
            <div class="import-file-wrapper">
              <label style="width: 100%;height: 100%;">
                导入文件
                <input
                  ref="editImportfile"
                  type="file"
                  hidden
                  @change="editImportFile"
                />
              </label>
            </div>
          </div>

          <div v-if="!editFormInfo.fileUrl && editFormInfo.lessonFilePath">
            {{ editFormInfo.lessonFilePath }}
          </div>
          <div v-if="editFormInfo.fileUrl && editFormInfo.lessonFilePath">
            {{ editFormInfo.fileUrl.name }}
          </div>
          <div class="import-file-elprogress-wrapper">
            <el-progress :percentage="editImportantPercentage" />
          </div>
          <!-- <div v-else-if="(editFormInfo.fileUrl instanceof String)">{{ editFormInfo.fileUrl }}</div> -->
          <!-- <div v-if="editFileName">{{ editFileName }}</div> -->
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="success" @click="editSubmitClass">提交</el-button>
      </div>
    </el-dialog>
    <video
      :src="curAddFilePath"
      style="display:none"
      @loadeddata="addvideoLoadData"
    />
    <video
      :src="curUpdateFilePath"
      style="display: none"
      @loadeddata="editvideoLoadData"
    />
  </div>
</template>

<script>
import {
  onlineTraining,
  createLesson,
  updateLesson,
  findLesson
} from "@/api/course.js";
export default {
  data() {
    return {
      tableData: [
        {
          title: "2021年全员必看的安全生产警示片",
          time: "01:06:25"
        },
        {
          title: "年度最走心的安全生产微电影《安全是什么》",
          time: "07:51"
        },
        {
          title: "新-安全生产法",
          time: "0"
        },
        {
          title: "应急管理部政策法规司新安全生产法修改权威解读",
          time: "02:31:12"
        }
      ],
      multipleSelection: [],
      addDialogFormVisible: false,
      formInfo: {
        title: "",
        fileUrl: "",
        lessonDuration: ""
      },
      formLabelWidth: "120px",
      fileName: "",
      importfilePercentage: 0,
      rules: {
        title: [
          {
            required: true,
            message: "请输入课时名称",
            trigger: "blur"
          }
        ],
        fileUrl: [
          {
            required: true,
            message: "请选择课时文件",
            trigger: "change"
          }
        ]
      },
      isLoadingAdd: false,
      isLoadingEdit: false,
      curAddFilePath: "",
      curUpdateFilePath: "",
      editDialogFormVisible: false,
      editFormInfo: {
        title: "",
        fileUrl: ""
      },
      editrules: {
        title: [
          {
            required: true,
            message: "请输入课时名称",
            trigger: "blur"
          }
        ]
      },
      editFileName: "",
      editImportantPercentage: 0,
      isEditable: true,
      isDeleteable: true,
      curFilePath: ""
    };
  },
  mounted() {
    // alert(this.$route.params.name)
    this.initTableData();
  },
  methods: {
    async initTableData() {
      const params = {
        pid: this.$route.params.name
      };
      await findLesson(params).then(res => {
        this.tableData = [
          ...res.map(item => {
            return {
              title: item.lessonTitle,
              time: item.lessonDuration,
              ...item
            };
          })
        ];
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      this.isEditable = true;
      this.isDeleteable = true;
      if (this.multipleSelection.length === 1) {
        this.isEditable = false;
      }
      if (this.multipleSelection.length > 0) {
        this.isDeleteable = false;
      }
    },
    addClass() {
      // 新增课程
      this.addDialogFormVisible = true;
      this.formInfo.title = "";
      this.formInfo.fileUrl = null;
      this.formInfo.lessonDuration = "00:00:00";
      this.importfilePercentage = 0;
    },
    editClass() {
      // 赋值当前
      this.editFormInfo = {
        fileUrl: "",
        title: this.multipleSelection[0].lessonTitle,
        ...this.multipleSelection[0]
      };
      this.editDialogFormVisible = true;
    },
    deleteClass() {
      this.$confirm("此操作将永久删除所选课时", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          onlineTraining(this.multipleSelection.map(item => item.id))
            .then(res => {
              this.initTableData();
              this.$message({
                type: "success",
                message: "删除成功"
              });
            })
            .catch(() => {
              this.$message.error("删除失败");
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    importFile() {
      if (this.$refs.importfile.files.length > 0) {
        this.formInfo.fileUrl = this.$refs.importfile.files[0];
        if (this.formInfo.fileUrl.name.endsWith(".mp4")) {
          this.isLoadingAdd = false;
          this.curAddFilePath = window.URL.createObjectURL(
            this.formInfo.fileUrl
          );
        } else if (this.formInfo.fileUrl.name.endsWith(".pdf")) {
          this.isLoadingAdd = true;
          this.formInfo.lessonDuration = "00:00:00";
        }
      } else {
        this.formInfo.fileUrl = null;
      }
    },
    submitFileName() {
      // 判断valid
      this.$refs.addform.validate(valid => {
        if (valid) {
          // ..
          if (
            !(
              this.formInfo.fileUrl.name.endsWith(".mp4") ||
              this.formInfo.fileUrl.name.endsWith(".pdf")
            )
          ) {
            this.$message.error("支持mp4、pdf等文件格式");
            return;
          }
          if (this.isLoadingAdd === true) {
            const formData = new FormData();
            const data = {
              pid: this.$route.params.name,
              lessonTitle: this.formInfo.title,
              lessonFile: this.formInfo.fileUrl,
              lessonDuration: this.formInfo.lessonDuration
            };
            for (const key in data) {
              formData.append(key, data[key]);
            }
            const updateFunc = progressEvent => {
              console.log(
                progressEvent,
                "progressEvent progressEvent updateFunc updateFunc updateFunc"
              );
              this.importfilePercentage = parseInt(
                "" + (progressEvent.loaded / progressEvent.total) * 100
              );
              console.log(
                this.importfilePercentage,
                "this.importfilePercentage this.importfilePercentage this.importfilePercentage"
              );
            };
            createLesson(formData, updateFunc)
              .then(res => {
                console.log(res, "createLesson createLesson createLesson");
                this.$message({
                  type: "success",
                  message: "添加成功"
                });
                this.initTableData();
                this.addDialogFormVisible = false;
              })
              .catch(() => {
                this.$message.error("添加失败");
              });
          } else {
            this.$message.error("视频获取失败");
          }
        } else {
          // ..
        }
      });
    },
    editImportFile() {
      if (this.$refs.editImportfile.files.length > 0) {
        console.log(
          this.$refs.editImportfile.files,
          "this.$refs.editImportfile.files"
        );
        this.editFormInfo.fileUrl = this.$refs.editImportfile.files[0];
        if (this.editFormInfo.fileUrl.name.endsWith(".mp4")) {
          this.isLoadingEdit = false;
          this.curUpdateFilePath = window.URL.createObjectURL(
            this.editFormInfo.fileUrl
          );
        } else if (this.editFormInfo.fileUrl.name.endsWith(".pdf")) {
          this.isLoadingEdit = true;
        }
      } else {
        this.editFormInfo.fileUrl = null;
      }
    },
    editSubmitClass() {
      this.$refs.editform.validate(valid => {
        if (valid) {
          // ..
          if (this.editFormInfo.fileUrl) {
            if (
              !(
                this.editFormInfo.fileUrl.name.endsWith(".mp4") ||
                this.editFormInfo.fileUrl.name.endsWith(".pdf")
              )
            ) {
              this.$message.error("支持mp4、pdf等文件格式");
              return;
            }
            if (this.isLoadingEdit === true) {
              const formData = new FormData();
              const data = {
                pid: this.$route.params.name,
                lessonTitle: this.editFormInfo.title,
                lessonFile: this.editFormInfo.fileUrl,
                lessonDuration: this.editFormInfo.lessonDuration,
                id: this.editFormInfo.id
              };
              for (const key in data) {
                formData.append(key, data[key]);
              }
              const updateFunc = progressEvent => {
                this.editImportantPercentage = parseInt(
                  "" + (progressEvent.loaded / progressEvent.total) * 100
                );
                console.log(
                  this.editImportantPercentage,
                  progressEvent,
                  "progressEvent"
                );
              };
              updateLesson(formData, updateFunc)
                .then(res => {
                  console.log(res, "createLesson createLesson createLesson");
                  this.$message({
                    type: "success",
                    message: "修改成功"
                  });
                  this.initTableData();
                  this.editDialogFormVisible = false;
                })
                .catch(() => {
                  this.$message.error("修改失败");
                });
            }
          } else {
            const formData = new FormData();
            const data = {
              pid: this.$route.params.name,
              lessonTitle: this.editFormInfo.title,
              lessonDuration: this.editFormInfo.lessonDuration,
              id: this.editFormInfo.id
            };
            for (const key in data) {
              formData.append(key, data[key]);
            }
            const updateFunc = progressEvent => {
              this.editImportantPercentage = parseInt(
                "" + (progressEvent.loaded / progressEvent.total) * 100
              );
              console.log(
                this.editImportantPercentage,
                progressEvent,
                "progressEvent"
              );
            };
            updateLesson(formData, updateFunc)
              .then(res => {
                this.$message({
                  type: "success",
                  message: "修改成功"
                });
                this.initTableData();
                this.editDialogFormVisible = false;
              })
              .catch(() => {
                this.$message.error("修改失败");
              });
          }
        } else {
          // ..
        }
      });
    },
    addvideoLoadData(event) {
      const seconds = parseInt("" + event.target.duration);
      let hour = parseInt("" + seconds / 3600);
      let minute = parseInt("" + (seconds - hour * 3600) / 60);
      let second = parseInt("" + (seconds - 3600 * hour - 60 * minute));
      if (hour < 10) {
        hour = "0" + hour;
      }
      if (minute < 10) {
        minute = "0" + minute;
      }
      if (second < 10) {
        second = "0" + second;
      }
      this.formInfo.lessonDuration = hour + ":" + minute + ":" + second;
      this.isLoadingAdd = true;
    },
    editvideoLoadData(event) {
      const seconds = parseInt("" + event.target.duration);
      let hour = parseInt("" + seconds / 3600);
      let minute = parseInt("" + (seconds - hour * 3600) / 60);
      let second = parseInt("" + (seconds - 3600 * hour - 60 * minute));
      if (hour < 10) {
        hour = "0" + hour;
      }
      if (minute < 10) {
        minute = "0" + minute;
      }
      if (second < 10) {
        second = "0" + second;
      }
      this.editFormInfo.lessonDuration = hour + ":" + minute + ":" + second;
      this.isLoadingEdit = true;
    }
  }
};
</script>

<style lang="scss" scoped>
.coursehour-total-wrapper {
  width: 80%;
  padding: 30px;
  border-radius: 30px;
  box-shadow: 0 0 9px 1px #eee;
  margin: 30px auto;
  .tools-wrapper {
    padding: 20px;
    border-radius: 20px;
    margin: 20px auto;
    box-shadow: 0 0 9px 1px #eee;
    width: 80%;
  }
  .table-wrapper {
    width: 80%;
    padding: 20px;
    border-radius: 20px;
    margin: 20px auto;
    box-shadow: 0 0 9px 1px #eee;
  }
}
.import-file-total-wrapper {
  display: flex;
  width: 100%;
  align-items: center;
}
.import-file-wrapper {
  /* width: 200px; */
  flex-basis: 50%;
  height: 100px;
  text-align: center;
  line-height: 100px;
  color: white;
  font-size: 20px;
  background: #a1a1a1;
}
.import-file-elprogress-wrapper {
  flex-grow: 1;
}
</style>
