<template>
  <el-dialog
    :title="title"
    :visible.sync="modal"
    :close-on-click-modal="false"
    width="960px"
    @close="
      res => {
        $emit('cancel');
      }
    "
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="场景" prop="kindergartenId">
        <SceneSelect v-model="form.kindergartenId" :clearable="false" />
      </el-form-item>
      <el-form-item label="活动">
        <ActivitySelect
          v-model="form.activityId"
          :kindergartenId="form.kindergartenId"
          :firstLoad="false"
          :disabled="form.kindergartenId === null"
        />
      </el-form-item>

      <el-form-item label="图片">
        <el-row>
          <el-upload
            action
            :http-request="upload"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :on-change="handleChange"
            :before-upload="beforeUpload"
            :before-remove="beforeRemove"
            multiple
            drag
            accept="image/*"
            :file-list="fileList"
            :limit="limit"
            :on-exceed="handleExceed"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将照片拖到此处，或<em>点击上传</em>
            </div>
            <div slot="tip" class="el-upload__tip">
              <el-row>注意事项：</el-row>
              <el-row>1. 上传照片大小要在1MB ~ 100MB之间哦!</el-row><!-- todo -->
            </div>
          </el-upload>
        </el-row>

        <el-row style="text-align: right;">
          <el-button class="mt-40" size="small" type="primary" @click="close">确认</el-button>
        </el-row>
      </el-form-item>

      <el-progress
        v-show="showProgress"
        :text-inside="true"
        :stroke-width="15"
        :percentage="progress"
      ></el-progress>
    </el-form>
  </el-dialog>
</template>

<script>
import { client, getFileNameUUID } from '@/utils/ali-oss'; // 前面的ali-js文件内的两个封装函数
import { saveItem } from '@/api/photoWarehouse';

export default {
  name: 'Upload',
  props: {
    limit: {
      type: Number,
      default: 100
    }
  },
  data() {
    return {
      title: '批量上传照片',
      modal: true,

      form: {
        kindergartenId: '',
        activityId: ''
      },
      rules: {
        kindergartenId: [
          { required: true, message: '请选择场景', trigger: 'blur' }
        ]
      },

      fileList: [], // 文件列
      showProgress: false, // 进度条的显示
      dataObj: {
        region: 'oss-cn-guangzhou',
        accessKeyId: 'LTAI5t8FMLXGzU4pTi9GXWb6',
        accessKeySecret: 'Hz6WOXIVNfpdMphYtf3laHbVoasGlT',
        bucket: 'yxl-kindergarten'
      }, // 存签名信息 todo
      progress: 0 // 进度条数据
    };
  },
  methods: {
    // 点击文件列表中已上传的文件时的钩子
    handlePreview(file) {},
    // 文件列表移除文件时的钩子
    handleRemove(file, fileList) {
      if (file && file.status==="success") {}
    },
    // 文件上传成功时的钩子
    handleSuccess(response, file, fileList) {
      this.fileList = fileList;
      // if (response.name) {
      //   this.saveData(response.name);
      // }
    },
    handleChange(file, fileList) {
    },
    // 文件上传前的校验
    beforeUpload(file) {
      const isLt100M = file.size / 1024 / 1024 > 1 && file.size / 1024 / 1024 < 100;
      if (!isLt100M) {
        this.$message.error("上传照片大小要在1MB ~ 100MB之间哦!");
        return false;
      }
      const isLt30 = file.name.length < 30;
      if (!isLt30) {
        this.$message.error('上传照片名称长度必须要小于30个文字哦!');
        return false;
      }
    },
    // 删除文件之前的钩子
    beforeRemove(file, fileList) {
      if (file && file.status==="success") {
        return this.$confirm(`确定移除 ${file.name}？`);
      }
    },
    // 文件超出个数限制时的钩子
    handleExceed(files, fileList) {
      this.$message.warning(`每次只能上传 ${this.limit} 张照片`);
    },
    // http-request属性来覆盖默认的上传行为（即action="url"），自定义上传的实现
    upload(file) {
      const _that = this;
      this.$refs.form.validate(async valid => {
        if (!valid) {
          return false;
        }

        async function multipartUpload() {
          let temporary = file.file.name.lastIndexOf('.');
          let fileNameLength = file.file.name.length;
          let fileFormat = file.file.name.substring(
            temporary + 1,
            fileNameLength
          );
          let fileName = getFileNameUUID() + '.' + fileFormat;

          // https://github.com/ali-sdk/ali-oss#multipartuploadname-file-options
          client(_that.dataObj)
            .multipartUpload(`tmp/${fileName}`, file.file, {
              parallel: 4, // 同时处理分片
              partSize: 2 * 1024 * 1024, // 每个分片大小
              progress: function(p) { // p进度条的值
                // todo 每个文件一个进度条？？？如何限定的业务参数（幼儿园id、活动id）
                console.log(p);
                _that.showProgress = true;
                _that.progress = Math.floor(p * 100);
              }
            })
            .then(result => { // 上传成功返回值，可针对项目需求写其他逻辑
              _that.saveData(result, file.file.name, file.file.size);
            })
            .catch(err => {
              console.log('err:', err);
            });
        }

        multipartUpload();
      })
    },
    async saveData(obj, name, size) {
      const params = {
        kindergartenId: this.form.kindergartenId,
        activityId: this.form.activityId,
        fileRequest: {
          originalFilename: name,
          size: size,
          path: obj.name
        }
      };
      const { success, msg } = await saveItem(params);
      if (success) {
      }
    },
    close () {
      this.modal = false;
      this.$g_emit('photo_reload');
    }
  }
};
</script>

<style lang="scss" scoped></style>

<style>
  .el-upload {
    width: 100%;
  }
  .el-upload-dragger {
    width: 100%;
  }
</style>
