<template>
  <el-dialog
    :title="title"
    width="500px"
    :visible.sync="dialogVisible"
    @close="diaClose"
    :close-on-click-modal="true"
  >
   
    <el-form
      :element-loading-text="loadingText"
      element-loading-spinner="el-icon-loading"
      ref="form"
      :model="form"
      :rules="rules"
      label-width="120px"
      label-position="left"
    >
    <div class="progress" v-if="loading">
      <el-progress type="circle" :percentage="progress"></el-progress>
    </div>
      <el-form-item label="平台">
        <el-select
          v-model="form.source"
          placeholder="请选择平台"
          style="width: 100%"
        >
          <el-option
            :label="item.label"
            :value="item.value"
            v-for="item in sources"
            :key="item.value"
          />
        </el-select>
        <div class="tips"></div>
      </el-form-item>
      <el-form-item label="版本号" prop="version">
        <el-input v-model="form.version"></el-input>
      </el-form-item>
      <el-form-item label="是否强制更新" prop="isUp">
        <el-radio-group v-model="form.isUp">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="更新提示内容" prop="message">
        <el-input
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 6 }"
          v-model="form.message"
        ></el-input>
      </el-form-item>

      <el-form-item label="版本文件">
        <uploadFile
          ref="uploadFile"
          @success="changeHasUpload"
          :limit="1"
          @remove="uploadRemove"
        />
        <div class="tips"></div>
      </el-form-item>

      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmitHandle">确 定</el-button>
      </div>
    </el-form>
  </el-dialog>
</template>
  
  <script>
import uploadFile from "./upload-file";
import { $uploadVersionFile, $version, $getCredentials } from "@/api/version";
import { cancelToken, clearAllToken } from "@/utils/globalCancelToken.js";
import OSS from "@/utils/oss-upload.js";
const form = {
  source: "PC",
  version: "",
  isUp: 0,
  message: "",
  url: "",
};
export default {
  components: {
    uploadFile,
  },
  data() {
    return {
      progress: 0,
      ossClient: undefined,
      loading: false,
      loadingText: "",
      sources: [
        { label: "PC", value: "PC" },
        { label: "APP", value: "APP" },
      ],
      title: "",
      dialogVisible: false,
      rules: {
        version: [
          {
            required: true,
            message: "版本号必填",
            trigger: "blur",
          },
        ],
      },
      form: { ...form },
      //文件是否已经上传过
      hasUpload: true,
    };
  },
  mounted() {
    this.getCredentials();
  },
  methods: {
    async getCredentials() {
      const res = await $getCredentials();
      this.ossClient = new OSS({ ...res, stsToken: res.securityToken });
      console.log(this.ossClient);
    },
    changeHasUpload() {
      this.hasUpload = false;
    },
    restForm() {
      console.log("restForm");
      console.log(form);
      this.form = { ...form };
      this.loadingText = "";
      this.loading = false;
      this.progress = 0;
    },
    diaClose() {
      this.$refs.uploadFile.clearFiles();
      this.restForm();
      // cancelToken();
      this.ossClient.abortUpload()
    },
    uploadSuccess(res) {
      this.form.img = res[0];
      console.log(this.form.img);
    },
    uploadRemove() {
      this.form.img = "";
    },
    // 提交
    onSubmitHandle() {
      console.log(this.form);
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            const { version } = this.form;
            let fileRes = "";
            const file = this.$refs.uploadFile.getFileList();
            console.log(file);
            if (Object.prototype.toString.call(file)=== '[object File]') {
              this.loadingText = "文件上传中，请耐心等待...";
              this.loading = true;
              // fileRes = await $uploadVersionFile(file, { name: version });
              fileRes = await this.ossClient.partUpload(
                `/version/${version}.exe`,
                file,
                (p) => {
                  this.progress = Math.floor(p * 100);
                  // 这里可以根据进度做相应的处理，例如更新UI等
                }
              );
              console.log(fileRes);
              if (!fileRes) {
                this.loading = false;
                 this.progress = 0;
                this.$notify({
                  title: "失败",
                  message: `上传阿里云失败`,
                  type: "error",
                });
                return;
              }
              if(fileRes.name=='cancel'){
                return
              }
            }

            let res = "";
            if (this.form.id) {
              //编辑
              res = await $version.update({
                ...this.form,
                url: fileRes ? fileRes : this.form.url,
              });
              this.$notify({
                title: "成功",
                message: `修改成功`,
                type: "success",
              });
            } else {
              //添加
              if (file) {
                console.log(1);
              }
              res = await $version.add({
                ...this.form,
                url: fileRes ? fileRes : this.form.url,
              });
              this.$notify({
                title: "成功",
                message: `添加成功`,
                type: "success",
              });
            }
            this.loading = false;
            this.progress = 0;
            this.close();

            this.$emit("success", res);
          } catch (error) {
            console.log(error);
          }
        }
      });
    },
    async show(obj = {}) {
      console.log(obj);
      // this.form=this.$options.data().form
      this.dialogVisible = true;
      this.title = "新增版本";

      if (obj && obj.id) {
        this.title = "编辑版本";
        this.form = {
          ...obj,
        };
        requestAnimationFrame(() => {
          if(obj.url){
            this.$refs.uploadFile.fileList = [
            {
              url: obj.url,
              name: obj.url,
              status: "finished",
            },
          ];
          }
      
        });
      }
    },
    close() {
      this.restForm();
      this.dialogVisible = false;
    },
  },
};
</script>
  
  <style scoped lang="scss">
.dialog-footer {
  display: flex;
  margin-top: 30px;
  justify-content: right;
}
.goods_info {
  background-color: #f9f9f9;
  padding: 10px;
  display: flex;
  align-items: center;

  .info {
    flex: 1;
    padding-left: 10px;
  }
}
.progress {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  top: 0;
  background-color: rgba(255, 255, 255, 0.9);
  z-index: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
  