<template>
  <div>
    <el-dialog
      title="上传图片"
      append-to-body
      :modal-append-to-body="true"
      :visible.sync="uploadModal"
      :width="isIframe ? '100%' : '800px'"
      :fullscreen="isIframe"
      @close="closed"
      top="5vh"
    >
      <div class="main" v-loading="loading">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="上传方式：" prop="type">
            <el-radio-group v-model="ruleForm.type" @change="radioChange(ruleForm.type)">
              <el-radio :label="0">本地上传</el-radio>
              <el-radio :label="1">网络上传</el-radio>
              <el-radio :label="2">扫码上传</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="上传至分组：" prop="region" v-show="ruleForm.type == 0 || ruleForm.type == 1">
            <el-cascader
              class="form-width"
              v-model="ruleForm.region"
              :props="props"
              :options="categoryList"
              @change="handleChange"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="网络图片：" prop="region" v-if="ruleForm.type == 1">
            <el-input class="form-width" v-model="webImgUrl" placeholder="请填写网络图片地址"></el-input>
            <span class="tq-text" @click="getImg">提取照片</span>
          </el-form-item>
          <el-form-item label="上传图片：" prop="region" v-if="ruleForm.type == 0">
            <div class="acea-row">
              <div class="uploadCont">
                <el-upload
                  ref="upload"
                  :action="fileUrl"
                  list-type="picture-card"
                  :on-change="fileChange"
                  :file-list="ruleForm.imgList"
                  :auto-upload="false"
                  :data="uploadData"
                  :headers="myHeaders"
                  :before-upload="beforeUpload"
                  :multiple="true"
                  :limit="limit"
                >
                  <i slot="default" class="el-icon-plus"></i>
                  <div
                    slot="file"
                    slot-scope="{ file }"
                    draggable="false"
                    @dragstart="handleDragStart($event, file)"
                    @dragover="handleDragOver($event, file)"
                    @dragenter="handleDragEnter($event, file)"
                    @dragend="handleDragEnd($event, file)"
                  >
                    <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                    <i class="el-icon-error btndel" @click="handleWebRemove(file)" />
                  </div>
                </el-upload>
                <div class="tips">一次最多上传50张，建议上传图片最大宽度750px，不超过5MB；单次最多一次上传20张，仅支持jpeg、png格式，可拖拽调整上传顺序</div>
              </div>
            </div>
          </el-form-item>
          <template v-if="ruleForm.type == 1">
            <div class="img-box pl100">
              <div
                v-for="(item, index) in ruleForm.imgList"
                :key="index"
                class="pictrue"
                draggable="false"
                @dragstart="handleDragStart($event, item)"
                @dragover.prevent="handleDragOver($event, item)"
                @dragenter="handleDragEnter($event, item)"
                @dragend="handleDragEnd($event, item)"
              >
                <img :src="item.url" />
                <i class="el-icon-error btndel" @click="handleRemove(index)" />
              </div>
            </div>
          </template>
          <div class="code-image" v-if="ruleForm.type == 2">
            <div class="left">
              <el-form-item label="上传至分组：" prop="region">
                <el-cascader
                  class="form-width"
                  v-model="ruleForm.region"
                  :props="props"
                  :options="categoryList"
                  @change="handleChange"
                ></el-cascader>
              </el-form-item>
              <el-form-item label="二维码：" prop="region">
                <div class="code" ref="qrCodeUrl"></div>
                <div class="trip">扫描二维码，快速上传手机图片</div>
                <div class="trip-small">建议使用手机浏览器</div>
              </el-form-item>
            </div>
            <div class="right">
              <el-button size="small" @click="scanUploadGet">刷新图库</el-button>
              <div class="tip">刷新图库按钮，可显示移动端上传成功的图片</div>
              <div class="img-box">
                <div
                  v-for="(item, index) in ruleForm.imgList"
                  :key="index"
                  class="pictrue"
                  draggable="false"
                  @dragstart="handleDragStart($event, item)"
                  @dragover.prevent="handleDragOver($event, item)"
                  @dragenter="handleDragEnter($event, item)"
                  @dragend="handleDragEnd($event, item)"
                >
                  <img :src="item.attachment_src" />
                  <!-- <i class="el-icon-error btndel" @click="handleWebRemove(item)" /> -->
                </div>
              </div>
            </div>
          </div>
        </el-form>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="clear">取 消</el-button>
        <el-button type="primary" @click="submitUpload">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>

import { getToken } from "@/utils/auth";
import { fileUpload, scanUploadQrcode, scanUploadGet, onlineUpload, scanUploadSave } from '@/api/setting';
import QRCode from 'qrcodejs2';
import compressImg from '@/utils/compressImg.js';
import SettingMer from "@/libs/settingMer";

export default {
  name: '',
  props: {
    categoryList: {
      default: () => {
        return [];
      },
    },
    categoryId: {
      default: '',
    },
    isPage: {
      default: false,
    },
    isIframe: {
      default: false,
    },
  },
  watch: {
    uploadModal: {
      handler(newVal) {
        // if (newVal) this.ruleForm.region = this.categoryId;
      },
      immediate: true,
    },
  },
  data() {
    return {
      webImgUrl: '',
      uploadModal: false,
      fileUrl: SettingMer.https  + `/upload/image/0/file`,
      myHeaders: {
        "X-Token": getToken()
      },
      uploadData: {},
      props: { checkStrictly: true, emitPath: false, label: 'attachment_category_name', value: 'attachment_category_id' },
      disabled: false,
      ruleForm: {
        type: 0,
        region: 0,
        imgList: [],
      },
      rules: { type: [{ required: true, message: '请选择活动资源', trigger: 'change' }] },
      qrcode: '',
      scanToken: '',
      limit: 50,
      loading: false,
      time: undefined,
    };
  },
  created() {},
  mounted() {},
  beforeDestroy() {
    clearInterval(this.time);
    this.time = undefined;
  },
  methods: {
    radioChange(type) {
      this.ruleForm.type = type;
      this.ruleForm.imgList = [];
      clearInterval(this.time);
      this.time = undefined;
      if (type == 2) {
        this.scanUploadQrcode();
        this.time = setInterval((e) => {
          this.scanUploadGet();
        }, 2000);
      }
    },
    scanUploadQrcode() {
      scanUploadQrcode(this.ruleForm.region).then((res) => {
        this.creatQrCode(res.data.url);
        this.scanToken = res.data.url;
      });
    },
    scanUploadGet() {
      let token = this.scanToken.split('token=')[1];
      scanUploadGet(token).then((res) => {
        this.ruleForm.imgList = res.data;
      });
    },
    getImg() {
      if (!this.webImgUrl) {
        this.$message.error('请先输入图片地址');
        return;
      }
      this.ruleForm.imgList.push({
        url: this.webImgUrl,
      });
    },
    async submitUpload() {
      if(this.ruleForm.imgList <= 0){
        return this.$message.error('请上传图片');
      }
      if (this.ruleForm.type == 0) {
        this.uploadData = {
          pid: this.ruleForm.region,
        };
        if (this.ruleForm.imgList.length) {
          if (this.loading) return;
          this.loading = true;
          for (let i = 0; i < this.ruleForm.imgList.length; i++) {
            const file = this.ruleForm.imgList[i].raw;
            await this.uploadItem(file);
            if (i == this.ruleForm.imgList.length - 1) {
              this.$message.success('上传成功');
              this.$emit('uploadSuccess');
              this.uploadModal = false;
              this.loading = false;
              this.initData();
            }
          }
        }
      } else if (this.ruleForm.type == 1) {
        let urls = this.ruleForm.imgList.map((e) => {
          return e.url;
        });
        if (urls.length) {
          if (this.loading) return;
          this.loading = true;
          onlineUpload({ id: this.ruleForm.region, images: urls })
            .then((res) => {
              this.$message.success('上传成功');
              this.$emit('uploadSuccess');
              this.uploadModal = false;
              this.loading = false;
              this.initData();
            })
            .catch((err) => {
              this.loading = false;
              this.$message.error(err.message);
            });
        }
      } else if (this.ruleForm.type == 2) {
        let token = this.scanToken.split('token=')[1];
        let attId = this.ruleForm.imgList.map((e) => {
          return e.attachment_id;
        });
        scanUploadSave(token,{ pid: this.ruleForm.region, ids: attId }).then((res) => {
          this.$message.success(res.message);
          this.$emit('uploadSuccess');
          this.uploadModal = false;
          this.initData();
        });
      }
    },
    uploadItem(file) {
      return new Promise((resolve, reject) => {
        const formData = new FormData();
        formData.append('file', file);
        fileUpload(this.ruleForm.region,formData)
          .then((res) => {
            if (res.status == 200) {
              resolve();
            } else {
              this.loading = false;
              this.$message({
                message: '上传失败',
                type: 'error',
                duration: 1000,
              });
            }
          })
          .catch((err) => {
            this.loading = false;
            this.$message.error(err.message);
          });
      });
    },
    beforeUpload(file) {},
    creatQrCode(url) {
      this.$refs.qrCodeUrl.innerHTML = '';
      var qrcode = new QRCode(this.$refs.qrCodeUrl, {
        text: url, // 需要转换为二维码的内容
        width: 160,
        height: 160,
        colorDark: '#000000',
        colorLight: '#ffffff',
        correctLevel: QRCode.CorrectLevel.H,
      });
    },
    handleWebRemove(file) {
      console.log(file);
      let index = this.ruleForm.imgList.findIndex((e) => {
        return e.url == file.url;
      });
      this.ruleForm.imgList.splice(index, 1);
    },
    handleRemove(index) {
      this.ruleForm.imgList.splice(index, 1);
    },
    async fileChange(file, fileList) {
      if(['image/jpeg','image/png','image/jpg'].indexOf(file.raw.type) == -1){
       return this.$message.error('请上传正确的文件格式！');
      }else{
        if (file.size >= 2097152) {
          await this.comImg(file.raw).then((res) => {
            fileList.map((e) => {
              // if (e.uid === file.uid) {
              //   e.raw = res;
              // }
            });
            this.ruleForm.imgList = fileList;
          });
        } else {
          this.ruleForm.imgList = fileList;
        }
      }
    },
    comImg(file) {
      return new Promise((resolve, reject) => {
        compressImg(file).then((res) => {
          resolve(res);
        });
      });
    },
    handleChange(e) {
      this.fileUrl = SettingMer.https  + `/upload/image/${this.ruleForm.region}/file`
      if (this.ruleForm.type == 2) this.scanUploadQrcode();
    },
    // 移动
    handleDragStart(e, item) {
      this.dragging = item;
    },
    handleDragEnd(e, item) {
      this.dragging = null;
    },
    handleDragOver(e) {
      e.dataTransfer.dropEffect = 'move';
    },
    handleDragEnter(e, item) {
      e.dataTransfer.effectAllowed = 'move';
      if (item === this.dragging) {
        return;
      }
      const newItems = [...this.ruleForm.imgList];
      const src = newItems.indexOf(this.dragging);
      const dst = newItems.indexOf(item);
      newItems.splice(dst, 0, ...newItems.splice(src, 1));
      this.ruleForm.imgList = newItems;
    },
    closed() {
      this.initData();
    },
    clear() {
      this.uploadModal = false;
      this.initData();
    },
    initData() {
      this.ruleForm.type = 0;
      this.ruleForm.region = 0;
      this.scanToken = '';
      this.webImgUrl = '';
      this.ruleForm.imgList = [];
      clearInterval(this.time);
      this.time = undefined;
    },
  },
};
</script>
<style lang="scss" scoped>
/deep/ .el-dialog__title{
  font-size: 16px;
}
.main{
  min-height: 400px
}
.pictrue {
  width: 64px;
  height: 64px;
  border: 1px dotted rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  margin-right: 10px;
  position: relative;
  cursor: pointer;
  img {
    border-radius: 4px;
    width: 100%;
    height: 100%;
  }
}
.btndel {
  position: absolute;
  z-index: 1;
  font-size: 18px;
  right: -5px;
  top: -5px;
  color: #999;
}
.form-width{
  width: 280px;
}
.tq-text{
  margin-left: 14px;
  font-size: 12px;
  font-weight: 400;
  color: #1890FF;
  cursor: pointer;
}
/deep/ .el-upload--picture-card, /deep/ .el-upload-list--picture-card .el-upload-list__item{
  width: 64px;
  height: 64px;
  line-height: 72px;
  overflow: inherit;
  border: 1px dotted rgba(0, 0, 0, 0.1);
}
/deep/ .el-upload--picture-card, /deep/ .el-upload-list--picture-card .el-upload-list__item img{
  width: 64px;
  height: 64px;
  border-radius: 4px;
  object-fit: cover;

}
.pl100{
  padding-left: 100px;
}
.img-box{
  display: flex;
  flex-wrap: wrap;
}
.tips{
  font-size: 12px;
  color: #BBBBBB;
}
.code-image{
  display: flex;
  margin-top: 12px;
  .left{
    display: flex;
    flex-direction: column;
    margin-right: 20px;
    align-items: center;
    .code{
      border: 1px solid #DDDDDD;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 200px;
      height: 200px;
      border-radius: 4px;
      .code-img{
        width: 160px;
        height: 160px;
      }
    }
    .form-width{
      width: 200px;
    }
    .code{
      margin-bottom: 14px;
    }
    .trip{
      color: #333333;
      text-align: center;
      line-height: 18px;
    }
    .trip-small{
      font-size: 12px;
      font-weight: 400;
      color: #BBBBBB;
      text-align: center;
      line-height: 16px;
    }
  }
  .right{
    margin-top: 62px;
    .tip{
      font-size: 12px;
      font-weight: 400;
      color: #BBBBBB;
      margin: 10px 0;
    }

  }
}
</style>
