<template>
  <!-- 上传试玩素材弹窗 -->
  <div>
    <el-dialog
      :visible.sync="showUploadDialog"
      title="上传试玩素材"
      top="2vh"
      @close="closeStateDialog"
      center
    >
      <el-form>
        <!-- 应用选择 -->
        <el-form-item label="应用">
          <el-select
            v-model="condition.pkg"
            @change="handleSelectChange"
            filterable
          >
            <el-option
              v-for="(item, index) in appList"
              :key="index"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <!-- 添加素材 -->
        <el-form-item label="添加素材">
          <el-row class="add-material">
            <el-upload
              multiple
              action
              ref="upload"
              auto-upload
              show-file-list
              :http-request="uploadMulFile"
              :on-remove="handleRemove"
              :limit="100"
            >
              <el-button size="small" type="primary">本地选择</el-button>
            </el-upload>
          </el-row>
        </el-form-item>
      </el-form>
      <span class="footer-btn">
        <el-button @click="showUploadDialog = false">取消</el-button>
        <el-button type="primary" @click="handleEnterUpload">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { uploadSaveMaterial } from "@/api/report";

import ossClient from "@/utils/ossClient";
import md5 from "md5";
export default {
  props: {
    condition: {
      type: Object,
      require: true,
    },
    appList: {
      type: Array,
      default: [],
    },
  },

  data() {
    return {
      showUploadDialog: false,
      uploadCondition: {
        pkg: this.condition.pkg,
        urls: "",
      },
      fileList: [],
      /* 连接oss 的参数 */
      uploadConf: {
        region: null,
        accessKeyId: null,
        accessKeySecret: null,
        bucket: null,
        // stsToken: null,
      },
    };
  },

  watch: {
    fileList(val) {
      console.log(val);
    },
  },

  created() {
    this.initOssInfo();
  },

  methods: {
    /* 进入弹窗时的初始化 */
    init() {
      this.showUploadDialog = true;
      /* 数据初始化 */
    },

    /* 关闭弹窗 */
    closeStateDialog() {
      this.showUploadDialog = false;
      this.fileList = [];
      this.$refs.upload.clearFiles();
    },

    //初始化从后端获取到 TST账户对OSS进行操作  在created初始化
    initOssInfo() {
      //获取阿里云token  这里是后台返回来的数据 暂时使用死数据
      const aliyun = {
        // "你的Region  注意 这个只要 空间名 不要 http:// 和 .aliyunoss.com !!",
        Region: "oss-cn-beijing",
        AccessKeyId: "LTAIOxFvkIPvgKrc",
        AccessKeySecret: "y5VxsiIviudY6swKWlFySFh3PRCafP",
        Bucket: "zx-material",
        //"你的SecurityToken"
        // SecurityToken: null,
      };
      const {
        Region,
        AccessKeyId,
        AccessKeySecret,
        Bucket,
        SecurityToken,
      } = aliyun;
      //初始化连接oss参数
      this.uploadConf.region = Region;
      this.uploadConf.accessKeyId = AccessKeyId;
      this.uploadConf.accessKeySecret = AccessKeySecret;
      this.uploadConf.bucket = Bucket;
      this.uploadConf.stsToken = SecurityToken;
    },

    //上传到阿里云OSS
    uploadMulFile(uploader) {
      console.log("文件信息", uploader);
      //获取到文件的信息内容
      let file = uploader.file;
      //获取文件类型 和 上传文件的日期
      let fileType = file.name.split(".").pop();

      // 判断是否满足条件
      if (fileType != "zip") {
        this.$message.error("只允许zip类型的文件，请重新选择文件！");
        this.$refs.upload.clearFiles();
        return;
      } else if (file.size > 3145728) {
        this.$message.error("上传的文件超过3M，请重新选择文件！");
        this.$refs.upload.clearFiles();
        return;
      }
      let curTime = new Date();
      //定义上传到云端的路径和文件名字
      let upFilePath =
        file.type.split("/")[0] +
        "/" +
        curTime.getFullYear() +
        "/" +
        (curTime.getMonth() + 1) +
        "/" +
        curTime.getDate() +
        "/" +
        md5(file.name) +
        "." +
        fileType;

      //分片上传配置，回显进度以及上传总进度重置，分片大小，超时设置
      let optionsFile = {
        progress: function (p) {
          uploader.onProgress({ percent: Math.floor(p * 10000) / 100 });
        },
        partSize: 1000 * 1024, //设置分片大小 小于1m 1024*1024
        timeout: 36000000, //设置超时时间 - 10小时
      };
      //实例化上传对象
      let client = ossClient(this.uploadConf);
      /* 分片上传 显示上传进度 */
      const that = this;
      //测试地址替换为 "test/" +upFilePath
      client
        .multipartUpload(upFilePath, file, optionsFile)
        .then((res) => {
          //解析url并替换前缀可访问
          let strUrl = res.res.requestUrls[0].split("?")[0];
          strUrl = strUrl.replace(
            "http://zx-material.oss-cn-beijing.aliyuncs.com",
            "https://cdn.zhangxingames.com"
          );
          that.fileList = [...that.fileList, { uid: file.uid, url: strUrl }];
          uploader.onSuccess(); //上传成功(打钩的小图标)
          client = null;
        })
        .catch((err) => {
          that.$message.warning(`上传终止，提示：${err}`);
          console.log(err);
          if (client.isCancel()) {
            uploader.onError();
          }
        });
    },

    /* 移除上传列表中的文件 */
    handleRemove(file) {
      this.$refs.upload.abort(); //取消上传
      this.fileList = this.fileList.filter((itm) => itm.uid !== file.uid);
      this.$message({ message: "成功移除" + file.name, type: "success" });
    },

    /* 确认上传 */
    handleEnterUpload() {
      // 上传需要满足的条件
      let temp = this.uploadCondition;
      if (temp.pkg == "" || this.fileList == []) {
        this.$message.error("请填写完整的参数并检查是否选择文件！");
        return;
      }

      //将上传的url拼接
      this.fileList.forEach((itm) => {
        temp.urls += itm.url + ",";
      });
      //截取多余的逗号
      temp.urls = temp.urls.substr(0, temp.urls.length - 1);
      let params = { ...temp };

      // 调用接口 上传保存素材
      uploadSaveMaterial(params)
        .then((res) => {
          // console.log(res);
          //参数重置
          this.showUploadDialog = false;
          this.fileList = [];
          this.$refs.upload.clearFiles();
          if (res.status == 200) {
            this.$message.success("恭喜您, 上传成功!");
            this.$emit("uploadSuccess");
          }
        })
        .catch((err) => {
          this.$message.error(`请求出错，错误：${err}`);
          console.log(err);
        });
    },

    handleSelectChange() {
      this.uploadCondition.pkg = this.condition.pkg;
    },
  },
};
</script>

<style scoped>
.add-material {
  width: 500px;
  height: 360px;
  overflow-y: scroll;
  border: 1px solid #cccccc;
}

.footer-btn {
  display: flex;
  justify-content: center;
}
</style>