<template>
  <div>
    <draggable
      v-model="uploadList"
      :move="dragMove"
      class="upload-images"
      @update="uploadListSort"
    >
      <div
        v-for="(item, index) in uploadList"
        :key="item"
        class="demo-upload-list"
      >
        <img :src="item" />
        <div class="demo-upload-list-cover">
          <Icon
            type="ios-eye-outline"
            size="30"
            @click.native="handleView('.upload-images', index)"
          ></Icon>
          <Icon
            type="ios-trash-outline"
            size="30"
            style="position: absolute; top: 0px;"
            @click.native="handleRemove(item)"
          ></Icon>
        </div>
      </div>
      <div
        v-if="uploadList.length < 6"
        class="demo-upload-list plus"
        @click="prepareUpload"
      >
        +
      </div>
    </draggable>

    <div>
      点击<span style="color: blue; font-size: 24px;">+</span
      >上传图片(最多上传6张图片)
    </div>

    <Modal
      v-model="uploadModalVisible"
      title="上传图片"
      mask
      footer-hide
      :mask-closable="false"
      :closable="false"
      width="660"
    >
      <div>
        <div v-if="qrValue" style="display: flex">
          <qrcode
            :value="qrValue"
            :options="{ width: 200 }"
            :style="{
              'margin-left': '-10px',
              filter: totalList.length >= 6 ? 'blur(10px)' : 'none',
            }"
          ></qrcode>
          <div style="font-size: 24px; margin-top: 10px;">
            <div>
              请使用<span style="font-weight: 900; color: #1E90FF;">微信</span
              >扫描二维码后，在微信小程序上拍照，并上传文件。<br />
              上传期间，请勿关闭二维码。
            </div>
            <div v-if="qrScanned" style="margin-top: 30px; font-size: 30px;">
              {{ uploaded ? "已上传" : "已扫描" }}
              <Icon type="md-checkmark" />
            </div>
          </div>
        </div>
        <div v-else>正在获取二维码...</div>

        <draggable
          v-model="totalList"
          class="total-images"
          @start="drag = true"
          @end="drag = false"
        >
          <div
            v-for="(item, index) in totalList"
            :key="item"
            class="demo-upload-list"
          >
            <img :src="item" />
            <div class="demo-upload-list-cover">
              <Icon
                type="ios-eye-outline"
                size="30"
                @click.native="handleView('.total-images', index)"
              ></Icon>
              <Icon
                type="ios-trash-outline"
                size="30"
                style="position: absolute; top: 0px;"
                @click.native="handleRemoveTotal(item)"
              ></Icon>
            </div>
          </div>
        </draggable>

        <div v-if="totalList.length > 6">
          * 图片上传最多只支持6张
        </div>
        <div style="display: flex; justify-content: center">
          <Button type="primary" size="large" @click="modalCloseClicked">
            确认
          </Button>
        </div>
      </div>
    </Modal>
  </div>
</template>

<script>
import VueQrcode from "@chenfengyuan/vue-qrcode";
import draggable from "vuedraggable";
import { createNamespacedHelpers } from "vuex";
const { mapState, mapMutations } = createNamespacedHelpers("examingHomeModule");
import "viewerjs/dist/viewer.css";
import Viewer from "viewerjs";

export default {
  name: "UploadPhotos",
  components: {
    qrcode: VueQrcode,
    draggable,
  },
  // props: ["defaultList", "qrValue"],
  props: {
    examQuestion: {
      type: Object,
      default() {
        return {};
      },
    },
    defaultList: {
      type: Array,
      default() {
        return [];
      },
    },
    qrValue: { type: String, default: "" },
  },
  data() {
    return {
      visible: false,
      uploadModalVisible: false,
      rotate: 0,
      // defaultList2: [...this.defaultList],
      uploadList: [],
      totalList: [],
      uploadUrl: "",
      headers: {},
      format: ["jpg", "jpeg", "png"],
      qrScanned: false,
      uploaded: false,
      drag: false,
    };
  },
  computed: {
    ...mapState(["questionQrCodeScanned", "pictureAnswer"]),
  },
  watch: {
    defaultList: {
      handler: function update() {
        this.uploadList = this.defaultList;
      },
      deep: true,
    },
    questionQrCodeScanned(value) {
      // console.log(this.examQuestion.studentAnswer);
      // console.log("watch", value);
      if (value.order === this.examQuestion.order) {
        this.qrScanned = true;
      }
    },
    pictureAnswer(value) {
      // console.log(this.examQuestion.studentAnswer);
      console.log("watch", value);
      this.uploaded = true;
      if (value.order === this.examQuestion.order) {
        this.totalList.push(...[...new Set(value.fileUrl.split(","))]);
      }
    },
    uploadModalVisible(val) {
      this.updateUploadModalVisible(val);
    },
  },
  mounted() {
    this.uploadList = this.defaultList;
    // this.uploadList.push(
    //   ...[
    //     "https://o5wwk8baw.qnssl.com/a42bdcc1178e62b4694c830f028db5c0/avatar",
    //     "https://o5wwk8baw.qnssl.com/bc7521e033abdd1e92222d733590f104/avatar",
    //   ]
    // );
  },
  methods: {
    ...mapMutations(["updateUploadModalVisible"]),
    handleView(imagesClass, index) {
      const viewer = new Viewer(document.querySelector(imagesClass), {
        container: "#app",
        zIndex: 99999,
        title: false,
        toolbar: {
          zoomIn: 1,
          zoomOut: 1,
          oneToOne: 1,
          reset: 1,
          prev: 1,
          play: {
            show: 0,
            size: "large",
          },
          next: 1,
          rotateLeft: 1,
          rotateRight: 1,
          flipHorizontal: 1,
          flipVertical: 1,
        },
        ready() {
          // viewer.zoomTo(1);
          viewer.view(index);
          // console.log("once");
        },
        hidden() {
          viewer.destroy();
        },
      });
      viewer.show();
    },
    handleRemove(file) {
      // const fileList = this.$refs.upload.fileList;
      this.$emit("on-photo-removed", file);
      // this.$refs.upload.fileList.splice(fileList.indexOf(file), 1);
    },
    handleRemoveTotal(file) {
      // const fileList = this.$refs.upload.fileList;
      // this.$emit("on-photo-removed", file);
      this.totalList.splice(this.totalList.indexOf(file), 1);
    },
    // handleSuccess(res, file) {
    //   // file.url = this.resultUrl;
    //   this.$emit("on-photo-added", this.resultUrl);
    // },
    prepareUpload() {
      this.uploadModalVisible = true;
      this.qrScanned = false;
      this.uploaded = false;
      this.totalList = [...this.uploadList];
    },
    modalCloseClicked() {
      // 在二维码被扫描，文件没得到之前，提示是否关闭。
      if (this.qrScanned && !this.uploaded) {
        this.$Modal.confirm({
          title: "确认关闭？",
          content:
            "检测到二维码被扫描，但是图片未上传。关闭此窗口后，将不再接受小程序图片上传。",
          okText: "确定关闭",
          cancelText: "取消关闭",
          onOk: () => {
            this.uploadModalVisible = false;
            // this.$emit("on-photos-reseted", this.totalList);
          },
          onCancel: () => {
            return;
          },
        });
        return;
      } else if (this.totalList.length > 6) {
        // 检查是否超过6张
        this.$Modal.warning({
          title: "图片数量超出限制",
          content: "请删除多余的图片，图片总数不应该超过6张",
        });
        return;
      }
      this.uploadModalVisible = false;
      this.$emit("on-photos-reseted", this.totalList);
    },
    uploadListSort() {
      this.$emit("on-photos-reseted", this.uploadList);
    },
    // dragStart() {
    //   console.log("drag start");
    //   return false;
    // },
    dragMove(e) {
      console.log(e);
      return !e.dragged.className.includes("plus");
    },
  },
};
</script>
<style scoped>
.demo-upload-list {
  display: inline-block;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 4px;

  cursor: move;
}
.demo-upload-list img {
  width: 100%;
  height: 100%;
}
.plus {
  font-size: 48px;
}
.plus:hover {
  cursor: pointer;
  color: blueviolet;
}
.demo-upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
}
.demo-upload-list:hover .demo-upload-list-cover {
  display: block;
}
.demo-upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
</style>
