<template>
  <!-- 图片裁切部分 -->
  <div class="picture-cutting">
    <h1>上传手机banner图</h1>
    <div class="picture-cutting__center">
      <div class="picture-cutting__left">
        <p class="title">封面预览</p>
        <div class="picture-cutting__imgbox">
          <div class="stance"></div>

          <div class="mask">
            <img
              :src="previews.url"
              v-if="previews.url"
              :style="previews.img"
            />
          </div>
        </div>
        <p class="tip-title">建议尺寸700x280</p>
        <p class="tip">只支持JPG/PNG,大小不超过5M</p>
        <p class="tip">（最多上传四张）</p>
      </div>
      <div class="picture-cutting__right">
        <p class="title">裁切封面</p>
        <div class="cutting-box">
          <VueCropper
            ref="cropper"
            :img="option.img"
            :outputSize="option.size"
            :outputType="option.outputType"
            :info="true"
            :full="option.full"
            :canMove="option.canMove"
            :canMoveBox="option.canMoveBox"
            :original="option.original"
            :autoCrop="option.autoCrop"
            :autoCropWidth="option.autoCropWidth"
            :autoCropHeight="option.autoCropHeight"
            :fixedBox="option.fixedBox"
            :centerBox="option.centerBox"
            @realTime="realTime"
            @imgLoad="imgLoad"
          ></VueCropper>
        </div>
        <div class="operate-box">
          <div class="right-box" v-if="previews.url">
            <div @click="changeScale(-1)">
              <i class="iconfont iconsuoxiao"></i>
            </div>
            <div @click="changeScale(1)">
              <i class="iconfont iconfangda"></i>
            </div>
            <!-- <div @click="rotateRight">
              <i class="iconfont iconxuanzhuan"></i>
            </div>-->
            <div @click="cuttingFinished">确定</div>
          </div>
        </div>
        <ul class="pcupload-box">
          <li class="pcupload-box__up" @click.stop="check">
            <div>
              <i class="iconfont iconshangchuan"></i>
            </div>
            <p>上传图片</p>
            <input
              ref="inputDom"
              :type="typeFile"
              accept="image/jpeg, image/png"
              @click.stop
              @change.stop="fileChange"
              hidden
            />
          </li>
          <!-- 已有 -->
          <li v-for="(item, index) in ExistingImg" :key="`img` + index">
            <img :src="item.url" />
            <div class="d-box" @click="DeleteExistingImg(index)">
              <i class="iconfont iconshanchu1"></i>
            </div>
          </li>
          <!-- 本地 -->
          <li v-for="(item, index) in localImg" :key="index">
            <img :src="item.img" />
            <div class="d-box" @click="DeleteLocalImg(index)">
              <i class="iconfont iconshanchu1"></i>
            </div>
          </li>
        </ul>
      </div>
    </div>
    <div class="btn-box">
      <div class="btn" @click="imgCancel">取消</div>
      <div class="btn" @click="imgConfirm">确定</div>
    </div>
  </div>
</template>
<script>
import { VueCropper } from "vue-cropper";
import CommonDialog from "@/components/CommonDialog.vue";
import { GO_URLS } from "@/config/URLS";
export default {
  //   引入组件
  components: {
    VueCropper,
  },
  props: ["TemplateId", "incrementId"],
  data() {
    return {
      previews: {}, // 图片预览
      option: {
        img: "", // 被裁剪图片的地址
        outputType: "jpeg", // 裁剪生成图片的格式
        autoCrop: true, // 是否默认生成截图框
        autoCropWidth: "172", //截图框宽度
        fixedBox: false, // 固定截图框大小 不允许改变
        autoCropHeight: "70", //截图框高度
        fixedNumber: [7, 3], //固定截图框的宽高比例
        canMoveBox: true, // 截图框能否拖动
        original: false, // 上传图片按照原始比例渲染
        canMove: false,
        centerBox: true,
      },
      // 本地数据
      localImg: [],
      //   模拟数据
      banners: [],
      localData: null,
      hashes: [],
      ExistingImg: [], //回显需要
      t: null,
      typeFile: "file",
    };
  },
  created() {
    if (this.TemplateId && this.TemplateId !== 0) this.EssentialInformation();
    if (this.incrementId && this.incrementId !== 0) this.getincrement();
  },
  computed: {},
  methods: {
    // 获取增量
    async getincrement() {
      const res = await this.$ajax({
        type: "get",
        url: GO_URLS.incrementId + `/` + this.incrementId,
      });
      if (res) {
        this.localData = JSON.parse(res.data.note);

        if (this.localData.banners && this.localData.banners.length > 0) {
          for (let index = 0; index < this.localData.banners.length; index++) {
            const element = this.localData.banners[index];
            this.hashes.push(element.hash);
            if (this.hashes.length === this.localData.banners.length) {
              this.getfiles();
            }
          }
        }
      }
    },
    //右旋转
    // rotateRight() {
    //   this.$refs.cropper.rotateRight();
    // },
    //放大/缩小
    changeScale(num) {
      num = num || 1;
      this.$refs.cropper.changeScale(num);
    },
    // 取消
    imgCancel() {
      this.$emit("closeBanner");
    },
    // 查询基本信息
    async EssentialInformation() {
      const res = await this.$ajax({
        type: "get",
        params: {
          id: this.TemplateId,
        },
        url: GO_URLS.proof,
      });
      if (res) {
        this.localData = JSON.parse(res.data.note);
        if (this.localData.banners && this.localData.banners.length > 0) {
          for (let index = 0; index < this.localData.banners.length; index++) {
            const element = this.localData.banners[index];
            this.hashes.push(element.hash);
            if (this.hashes.length === this.localData.banners.length) {
              this.getfiles();
            }
          }
        }
      }
    },
    // 通过hash获取图片
    async getfiles() {
      const res = await this.$ajax({
        type: "post",
        url: GO_URLS.getFiles,
        params: {
          hashes: this.hashes,
        },
      });
      if (res) {
        this.ExistingImg = res.data.files;
      }
    },
    // 更新note数据
    async update() {
      const res = await this.$ajax({
        type: "put",
        url:
          this.TemplateId !== 0
            ? GO_URLS.update
            : GO_URLS.incrementId + `/` + this.incrementId,
        params: {
          id: this.TemplateId !== 0 ? this.TemplateId : this.incrementId,
          note: JSON.stringify(this.localData),
        },
      });
      if (res) {
        this.$message({
          showClose: true,
          message: "图片上传成功",
          type: "success",
        });
        this.$emit("closeBanner", JSON.stringify(this.banners));
      }
    },

    // 图片上传请求
    async imageUpload(formData) {
      const res = await this.$ajax({
        type: "post",
        url: GO_URLS.upload + `?file_type=png`,
        params: formData,
      });
      if (res) {
        this.banners.push({
          hash: res.data.hash,
          target: "",
        });

        if (
          this.banners.length ===
          this.localImg.length + this.ExistingImg.length
        ) {
          this.localData.banners = this.banners;
          this.update();
        }
      }
    },

    // 图片上传事件
    async imgConfirm() {
      if (this.localImg.length + this.ExistingImg.length === 0) {
        this.$message({
          message: "请先上传图片",
          type: "warning",
        });
        return;
      }

      //   判断是否有旧的图片
      if (this.ExistingImg.length !== 0) {
        for (let index = 0; index < this.ExistingImg.length; index++) {
          const element = this.ExistingImg[index];
          this.banners.push({
            hash: element.hash,
            target: "",
          });
        }
        if (this.localImg.length === 0 && this.banners.length) {
          this.localData.banners = this.banners;
          this.update();
        }
      }

      for (let index = 0; index < this.localImg.length; index++) {
        const formData = new FormData();
        const element = this.localImg[index];
        let blob = this.dataURLtoFile(element.img, "image/png");
        var fileOfBlob = new Blob([blob], { type: "image/png" });
        formData.append("file_data", fileOfBlob, new Date() + ".png");
        this.imageUpload(formData);
      }
    },
    //将base64转换为blob
    dataURLtoFile(dataURI, type) {
      let binary = atob(dataURI.split(",")[1]);
      let array = [];
      for (let i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i));
      }
      return new Blob([new Uint8Array(array)], { type: type });
    },
    // 删除本地的base64位图片
    DeleteLocalImg(index) {
      this.localImg.splice(index, 1);
    },
    // 删除已有图片
    DeleteExistingImg(index) {
      this.ExistingImg.splice(index, 1);
    },
    // 确定裁切
    cuttingFinished() {
      if (this.t) window.clearTimeout(this.t);
      this.t = setTimeout(() => {
        this.$refs.cropper.getCropData((data) => {
          this.localImg.push({ img: data });
          this.previews.url = "";
          this.option.img = " ";
          this.typeFile = "text";
        });
      }, 500);
    },
    // 触发input上传事件
    check() {
      // 获取长度，转化为可点击数，进行递减
      if (this.localImg.length + this.ExistingImg.length === 4) {
        this.$message({
          message: "最多可上传四张图片",
          type: "warning",
        });
        return;
      }
      this.typeFile = "file";
      this.$refs.inputDom.click();
    },
    // 图片-本地上传
    fileChange(e) {
      this.previews.url = "";
      this.option.img = " ";
      const file = e.target.files[0];
      if (file) this.option.img = URL.createObjectURL(file);
    },
    imgLoad(msg) {
      if (msg === "error") {
        setTimeout(() => {
          this.previews.url = "";
        }, 300);
      }
    },
    // 图片预览
    realTime(data) {
      this.previews = {
        ...data,
      };
    },
  },
};
</script>
<style scoped lang="less">
// 图片裁减--覆盖原有公共样式
.picture-cutting {
  width: 926px;
  height: 617px;
  background: rgba(255, 255, 255, 1);
  border-radius: 10px;
  h1 {
    font-weight: 400;
    font-size: 18px;
    line-height: 67px;
    text-align: center;
    margin: 0;
    padding: 0;
    font-size: 22px;
    color: #353535;
    border-bottom: 1px solid #e9e9e9;
  }
  .picture-cutting__center {
    height: 450px;
    border-bottom: 1px solid #e9e9e9;
    .picture-cutting__left {
      width: 222px;
      border-right: 1px solid #e9e9e9;
      float: left;
      height: 100%;
      .title {
        font-size: 14px;
        font-weight: 400;
        margin: 0;
        color: rgba(53, 53, 53, 1);
        line-height: 20px;
        padding-top: 16px;
        padding-left: 26px;
      }
      .tip-title {
        color: #353535;
        padding-top: 6px;
        font-size: 12px;
        text-align: center;
        line-height: 20px;
        margin: 0;
      }
      .tip {
        text-align: center;
        font-size: 10px;
        margin: 0;
        color: #797d84;
        line-height: 20px;
      }
      .picture-cutting__imgbox {
        width: 202px;
        height: 298px;
        margin: 0 auto;
        text-align: center;
        position: relative;
        .stance {
          width: 202px;
          height: 298px;
          background-image: url("../images/TemplateManage/Stance.png");
          background-size: 100% 100%;
        }
        .mask {
          max-width: 172px !important;
          max-height: 70px !important;
          position: absolute;
          top: 43px;
          overflow: hidden;
          border-radius: 5px;
          left: 15px;
          img {
            width: 100%;
            height: 100%;
          }
        }
      }
    }
    .picture-cutting__right {
      float: left;
      height: 100%;
      width: 703px;
      .title {
        margin: 0;
        font-size: 14px;
        font-weight: 400;
        color: rgba(53, 53, 53, 1);
        line-height: 20px;
        padding-top: 15px;
        padding-bottom: 8px;
        padding-left: 31px;
      }
      .cutting-box {
        width: 641px;
        height: 256px;
        margin-left: 31px;
        border: 1px solid rgba(235, 235, 235, 1);
        // border: 1px solid #000;
        /deep/.vue-cropper {
          background: url("../images/TemplateManage/12-bg@2x.png") no-repeat
            center;
          background-size: 100%;
        }
      }
      .operate-box {
        border: 1px solid rgba(235, 235, 235, 1);
        border-top: none;
        width: 641px;
        height: 40px;
        margin-left: 31px;
        line-height: 40px;
        text-align: right;
        .right-box {
          float: right;
          div {
            float: left;
            cursor: pointer;
            padding-right: 22px;
            font-size: 14px;
            color: #9b9c9c;
            &:last-child {
              color: #3f79fe;
            }
          }
        }
      }
      // 图片上传和展示部分
      .pcupload-box {
        list-style: none;
        width: 641px;
        height: 82px;
        margin: 0 auto;
        margin-top: 14px;
        padding: 0;
        li {
          float: left;
          width: 119px;
          height: 82px;
          background: rgba(255, 255, 255, 1);
          border-radius: 4px;
          border: 1px solid rgba(234, 234, 234, 1);
          margin-right: 9px;
          position: relative;
          img {
            width: 100%;
            height: 100%;
          }
          .d-box {
            position: absolute;
            right: 0;
            width: 21px;
            background: rgba(0, 0, 0, 1);
            opacity: 0.6;
            height: 21px;
            top: 0;
            cursor: pointer;
            text-align: center;
            line-height: 21px;
            i {
              color: white;
            }
          }
          &:last-child {
            margin-right: 0;
          }
        }
        .pcupload-box__up {
          cursor: pointer;
          text-align: center;
          i {
            color: #c4c4c4;
          }
          div {
            margin-top: 19px;
            color: #797d84;
          }
          p {
            padding: 0;
            margin: 0;
            font-size: 12px;
            padding-top: 8px;
            font-weight: 400;
            color: rgba(121, 125, 132, 1);
          }
        }
      }
    }
  }
  .btn-box {
    text-align: center;
    overflow: hidden;
    margin-top: 30px;
    .btn {
      display: inline-block;
      width: 120px;
      height: 40px;
      background: rgba(236, 236, 236, 1);
      border-radius: 4px;
      color: #5c6476;
      font-size: 14px;
      cursor: pointer;
      text-align: center;
      line-height: 40px;
      &:first-child {
        margin-right: 10px;
      }
      &:last-child {
        margin-left: 10px;
        background: rgba(63, 121, 254, 1);
        color: white;
      }
    }
  }
}
</style>

