<template>
  <div>
    <el-dialog
      :center="true"
      :visible.sync="show"
      :close-on-click-modal="false"
      :modal="true"
      width="auto"
      height="auto"
      :append-to-body="true"
      class="uploadFileToCreateClassDialog"
    >
      <div class="box">
        <div class="b_head">
          <span>文件上传与配置</span>
          <img
            src="../../../../assets/icon/classroomObservation/close.svg"
            @click="close()"
          />
        </div>
        <div class="b_main">
          <div class="b_m_left">
            <div class="b_m_l_fileList" v-if="fileList.length > 0">
              <div class="fl_item" v-for="item in fileList" :key="item.index">
                <div class="fl_i_left">
                  <img
                   v-if="item.type =='text/plain'"
                    src="../../../../assets/icon/classroomObservation/textFile_icon.svg"
                  />

                  <img
                   v-if="item.type =='audio/wav'"
                    src="../../../../assets/icon/classroomObservation/audio_file.svg"
                  />

                  <img
                   v-if="item.type =='video/mp4'"
                    src="../../../../assets/icon/classroomObservation/videoFile_icon.svg"
                  />
                </div>
                <div class="fl_i_center">
                  <div class="fl_i_c_top">
                    <span>{{ item.name }}</span>
                    <div>
                      <span v-if="item.status === 'wait'">等待上传</span>
                      <span
                        class="uploadingText"
                        v-else-if="item.status === 'uploading'"
                        >{{ item.progress.percent }}%</span
                      >
                      <span
                        class="successText"
                        v-else-if="item.status === 'success'"
                        >上传成功
                      </span>
                    </div>
                  </div>
                  <div class="fl_i_c_bottom">
                    <div class="f_i_c_progress">
                      <div
                        class="f_i_c_p_value"
                        :class="{
                          successProgress: item.status === 'success',
                          uploadingProgress: item.status === 'uploading'
                        }"
                        :style="`width:${item.progress.percent}%`"
                      ></div>
                    </div>
                  </div>
                </div>
                <div class="fl_i_right">
                  <img
                    @click="delUploadFile(item)"
                    src="../../../../assets/icon/classroomObservation/del.svg"
                  />
                </div>
              </div>
            </div>
            <div class="b_m_l_noFile" v-else @click="addFile()">
              <img
                src="../../../../assets/icon/classroomObservation/file_processing.svg"
              />
              <span>文件格式支持：mp4、wav、txt 文件</span>
            </div>
          </div>
          <div class="b_m_right">
            <span>配置</span>
            <div>
              <span>自动编码</span>
              <el-switch
                v-model="automaticCoding"
                active-color="#13ce66"
                inactive-color="#ff4949"
              >
              </el-switch>
            </div>
            <div>
              <span>分析模板</span>
              <el-cascader
                size="small"
                v-model="analysisTemplate"
                :options="options"
              ></el-cascader>
            </div>
          </div>
        </div>
        <div class="b_bottom">
          <el-button size="small" @click="close()">取消</el-button>
          <el-button size="small" type="primary" @click="submit"
            >确定添加</el-button
          >
        </div>
        <uploadFile
          v-for="(item, index) in fileList"
          v-if="item.status == 'uploading'"
          :ref="`uploadFileRef_${item.index}`"
          :key="item.index"
          :index="item.index"
          @progressUpdate="progressUpdate"
          @success="uploadSuccess"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import uploadFile from "../newComponents/uploadFile.vue";
import { v4 as uuidv4 } from "uuid";
export default {
  components: {
    uploadFile
  },
  data() {
    return {
      loading: false,
      show: false,
      automaticCoding: false,
      analysisTemplate: [],
      userId: this.$route.query["userid"],
      fileList: [],
      options: [
        { value: "0", label: "社区", children: [] },
        { value: "1", label: "我的", children: [] },
        { value: "2", label: "收藏", children: [] }
      ]
    };
  },
  methods: {
    open(data) {
      this.init();
      this.getTemplateData();
      this.loading = false;
      this.show = true;
    },
    close() {
      this.show = false;
      this.init();
    },
    init() {
      this.fileList = [];
      this.analysisTemplate = [];
      this.automaticCoding = false
      this.loading = false;
    },
    submit() {
      if(this.fileList.length<=0)return this.$message.error("请上传文件");
      if(this.analysisTemplate.length<=1)return this.$message.error("请选择分析模板");
      if(this.fileList.some(i=>i.status==='wait' || i.status==='uploading'))return this.$message.error("请等待文件上传完毕");
      this.$emit('success',{fileList:this.fileList,automaticCoding:this.automaticCoding,analysisTemplate:this.analysisTemplate});
    },
    delUploadFile(item) {
      this.$confirm("确定要删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          // 确定删除

          if (item.status === "uploading") {
            this.$refs[`uploadFileRef_${item.index}`][0].stopUpload();
            this.$refs[`uploadFileRef_${item.index}`][0].abortMultipartUpload(
              item.progress.key,
              item.progress.uploadid
            );
          }
          this.fileList = this.fileList.filter(i => i.index != item.index);
          this.$forceUpdate();
        })
        .catch(() => {
          // 取消删除
        });
    },
    progressUpdate(res) {
      console.log(res);
      this.fileList.find(i => i.index == res.index).progress.status =
        res.status;
      this.fileList.find(i => i.index == res.index).progress.percent =
        res.percent;
      this.fileList.find(i => i.index == res.index).progress.key = res.key;
      this.fileList.find(i => i.index == res.index).progress.uploadid =
        res.uploadid;
    },
    uploadSuccess(res) {
      let data = res.data;
      let _name = this.fileList.find(i => i.index == res.index).file.name;
      let size = this.fileList.find(i => i.index == res.index).file.size;
      let _type = this.fileList.find(i => i.index == res.index).type;
      console.log(data);
      this.fileList.find(i => i.index == res.index).successData = {
        name: _name,
        url: data.Location,
        type: _type,
        size: size
      };
      this.fileList.find(i => i.index == res.index).status = "success";
      let uploadingFile = this.fileList.find(file => file.status === "wait");
      if (uploadingFile) {
        this.fileList.find(file => file.status === "wait").status = "uploading";
        this.$nextTick(() => {
          this.$refs[`uploadFileRef_${uploadingFile.index}`][0].awsupload({
            file: uploadingFile.file
          });
        });
      } else {
        console.log("上传完成");
      }
    },
    addFile() {
      let input = document.createElement("input");
      input.type = "file";
      input.accept = "video/mp4, audio/wav, text/plain";
      input.multiple = true; // 支持多文件上传
      input.style.display = "none";

      input.click();

      input.addEventListener("change", e => {
        let files = e.target.files;
        for (let i = 0; i < files.length; i++) {
          if (
            ["video/mp4", "audio/wav", "text/plain"].includes(files[i].type)
          ) {
            this.fileList.push({
              file: files[i],
              index: uuidv4(),
              successData: null,
              name: files[i].name,
              type: files[i].type,
              progress: { status: "", percent: 0, key: "", uploadid: "" },
              status: "wait"
            });
          } else {
            this.$message.info("文件格式不支持，仅支持mp4、wav、txt文件。");
          }
        }
        if (!this.fileList.some(i => i.status === "uploading")) {
          let uploadingFile = this.fileList.find(
            file => file.status === "wait"
          );
          if (uploadingFile) {
            this.fileList.find(file => file.status === "wait").status =
              "uploading";
            this.$nextTick(() => {
              this.$refs[`uploadFileRef_${uploadingFile.index}`][0].awsupload({
                file: uploadingFile.file
              });
            });
          }
        }
      });
    },
    async getTemplateData() {
      const promises = this.options.map(option => {
        return new Promise((resolve, reject) => {
          const params = {
            uid: this.userId,
            txt: "",
            sub: "0",
            type1: option.value
          };

          this.ajax
            .get(this.$store.state.api + "selectClassroomTemplate", params)
            .then(res => {
              const _data = res.data[0].map(item => ({
                value: item.id,
                label: item.name
              }));
              this.options.find(
                option2 => option2.value === option.value
              ).children = _data;
              resolve();
            })
            .catch(err => {
              console.log(err);
              reject(err);
            });
        });
      });

      try {
        await Promise.all(promises);
        console.log("获取模板成功");
      } catch (error) {
        console.log("获取模板失败");
      }
    }
  }
};
</script>

<style scoped>
.uploadFileToCreateClassDialog >>> .el-dialog {
  width: 900px !important;
  border-radius: 8px;
  padding: 0;
  background-color: #fff;
  overflow: hidden;
}

.uploadFileToCreateClassDialog >>> .el-dialog__body {
  width: 900px !important;
  height: auto;
  flex-shrink: 0;
  padding: 0;
  box-sizing: border-box;
  overflow: auto;
}

.uploadFileToCreateClassDialog >>> .el-dialog__header {
  display: none !important;
}

.box {
  width: 900px;
  height: 500px;
  background: #fafafa;
  border-radius: 15px;
  box-shadow: 0px 6px 30px 5px rgba(0, 0, 0, 0.05),
    0px 16px 24px 2px rgba(0, 0, 0, 0.04), 0px 8px 10px -5px rgba(0, 0, 0, 0.08);
}

.b_head {
  width: 100%;
  height: 50px;
  border-radius: 15px 15px 0 0;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-sizing: border-box;
  padding: 0 20px;
}

.b_head > span {
  font-size: 18px;
  font-weight: bold;
  color: #000;
}

.b_head > img {
  width: 20px;
  height: 20px;
  cursor: pointer;
}

.b_main {
  width: 100%;
  height: calc(100% - 50px - 70px);
  background: #fafafa;
  padding: 20px 20px 0 20px;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: space-around;
}

.b_bottom {
  width: 100%;
  height: 70px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  box-sizing: border-box;
  padding: 0 20px;
}

.b_main > div {
  border-radius: 15px;
  width: 400px;
  height: 350px;
  box-sizing: border-box;
  border: rgba(150, 155, 163, 1) 1px dashed;
}

.b_m_left {
  background-color: #fff;
}

.b_m_l_noFile {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.b_m_l_noFile > img {
  width: 140px;
  height: 140px;
}

.b_m_l_noFile > span {
  font-size: 16px;
  color: #000;
}

.b_m_right {
  box-sizing: border-box;
  padding: 20px;
}

.b_m_right > span {
  font-size: 18px;
  font-weight: bold;
  color: #000;
}

.b_m_right > div {
  margin-top: 20px;
  font-size: 16px;
  color: #000;
}

.b_m_l_fileList {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: auto;
  box-sizing: border-box;
  padding: 5px 10px;
}

.fl_item {
  width: 100%;
  height: 60px;
  margin: 5px 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.fl_i_left {
  width: 50px;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.fl_i_left > img {
  width: 80%;
  height: 80%;
}

.fl_i_center {
  width: calc(100% - 90px);
  height: 100%;
}

.fl_i_right {
  width: 40px;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.fl_i_right > img {
  width: 25px;
  height: 25px;
  cursor: pointer;
}

.fl_i_c_top {
  width: 100%;
  display: flex;
  align-items: center;
  height: 50%;
  justify-content: space-between;
}

.fl_i_c_top > span {
  max-width: calc(100% - 100px);
  display: block;
  align-items: center;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.fl_i_c_top > div {
  width: 100px;
  display: flex;
  justify-content: flex-end;
  font-size: 14px;
}
.fl_i_c_bottom {
  width: 100%;
  height: 50%;
  display: flex;
  align-items: center;
}

.f_i_c_progress {
  width: 100%;
  height: 6px;
  background-color: rgba(217, 217, 217, 1);
  border-radius: 5px;
  overflow: hidden;
}

.f_i_c_p_value {
  height: 100%;
}

.successText {
  color: rgba(188, 230, 133, 1);
}

.successProgress {
  background-color: rgba(188, 230, 133, 1);
}

.uploadingText {
  color: rgba(54, 129, 252, 1);
}

.uploadingProgress {
  background-color: rgba(54, 129, 252, 1);
}
</style>
