<template>
  <div style="background:#fff;" class="mainPage" id="main">
    <div>
      <div v-if="isLoading || windowLoad" class="loading">
        <img :src="loading" alt>
        <span>{{msg}}</span>
      </div>
      <div class="cutBox" v-for="(item,index) in banner" :key="index">
        <div class="cutDom" v-if="index === mainIndex-1">
          <img :src="item.bgImg" class="cover">
          <div :style="item.styleCut" v-show="!item.CustomerImg && item.defaultBg" class="cla">
            <img :src="item.defaultBg">
          </div>
          <div :style="item.styleCut" v-if="item.CustomerImg" class="cla">
            <img :src="item.CustomerImg">
          </div>
          <img class="text-h" v-if="item.ImgName === '10月'" :src="textH">
          <img class="text-l" v-if="item.ImgName === '4月' || item.ImgName === '7月'" :src="textL">
        </div>
      </div>
      <div class="topBanner">
        <swiper :options="swiperOption" ref="mySwiper">
          <swiper-slide class="swiper-slide" v-for="(item,index) in banner" :key="index">
            <div
              class="item"
              v-if="index === mainIndex-1 || index === mainIndex ||  index === mainIndex-2"
            >
              <div>
                <img :src="item.bgImg" class="cover">
                <img
                  :style="item.style"
                  v-if="!item.CustomerImg && item.defaultBg"
                  :src="item.defaultBg"
                >
                <img :src="item.CustomerImg" :style="item.style" v-if="item.CustomerImg">
                <img class="text-h" v-if="item.ImgName === '10月'" :src="textH">
                <img
                  class="text-l"
                  v-if="item.ImgName === '4月' || item.ImgName === '7月'"
                  :src="textL"
                >
                <div class="reload-img">
                  <van-uploader :after-read="onRead" v-show="mainIndex !== 1">
                    <img :src="reloadImg">
                  </van-uploader>
                </div>
              </div>
            </div>
          </swiper-slide>
        </swiper>
        <div class="swiper-button-next">
          <i class="iconfont icon-you"></i>
        </div>
        <div class="swiper-button-prev">
          <i class="iconfont icon-left"></i>
        </div>
        <div class="swiper-pagination"></div>
      </div>
      <div class="meassage" v-if="mainIndex !== 1">备注：为了美观效果请上传{{size}}尺寸照片，未按尺寸会默认裁剪</div>
      <div class="meassage" v-else>左右滑动可上传自定义图片</div>
      <div class="operation">
        <div>
          <van-uploader :after-read="onRead" v-show="mainIndex !== 1">
            <img :src="uploadImg">
            <p>自定义图片</p>
          </van-uploader>
        </div>
        <div>
          <img :src="reSet" v-show="mainIndex !== 1" @click="changeOld">
          <p v-show="mainIndex !== 1">恢复默认</p>
        </div>
      </div>
      <div class="email">
        <span>邮箱</span>
        <input
          class="input"
          type="text"
          @blur="emailBlur"
          placeholder="接收电子版"
          v-model="email"
          style="border-radius:5px;background:rgba(245, 246, 250, 1);"
        >
      </div>
      <div class="btn">
        <div @click="pre">预览</div>
        <div @click="showPop=true">确定</div>
      </div>
      <div v-show="showPop" class="pop-box">
        <div class="pop-content">
          <div>确认定制此台历？</div>
          <div>
            <div @click="submit">确定</div>
            <div @click="showPop=false">取消</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import html2canvas from 'html2canvas'
import canvas2image from '@/util/canvas2image.js'
import { swiper, swiperSlide } from 'vue-awesome-swiper'
import 'swiper/dist/css/swiper.css'
import { createNamespacedHelpers } from 'vuex'
const { mapState: mapMakingState, mapActions: mapMakingActions } = createNamespacedHelpers('making')
import textH from '@/common/icon/text-h.png'
import textL from '@/common/icon/text-l.png'
import uploadImg from '@/common/icon/uploadImg.png'
import reloadImg from '@/common/icon/reloadImg.png'
import reSet from '@/common/icon/reSet.png'
import loading from '@/common/icon/loading-red.gif'

export default {
  data () {
    const self = this
    return {
      textH,
      textL,
      uploadImg,
      reSet,
      reloadImg,
      loading,
      banner: [],
      mainIndex: 1,
      isLoading: false,
      showPop: false,
      imglength: 0,
      msg: '请稍候...',
      swiperOption: {
        observer: false,
        speed: 1500,
        navigation: {
          nextEl: '.swiper-button-next',
          prevEl: '.swiper-button-prev',
        },
        pagination: {
          el: '.swiper-pagination',
          type: 'fraction',
        },
        on: {
          transitionStart: function () {
            self.mainIndex = this.activeIndex + 1
            self.$nextTick(() => {
              self.calSize()
            })
          }
        }
      }
    }
  },
  components: {
    swiper,
    swiperSlide
  },
  computed: {
    MySwiper () {
      return this.$refs.mySwiper.swiper
    },
    ...mapMakingState({
      bannerBlack: item => item.bannerBlack,
      bannerRed: item => item.bannerRed,
      Email: item => item.email
    }),
    size () {
      if (this.mainIndex === 2 || this.mainIndex === 5 || this.mainIndex === 8 || this.mainIndex === 11) {
        return '横'
      } else {
        return '竖'
      }
    },
    email: {
      get () {
        console.log(this.Email)
        return this.Email
      },
      set (val) {
        this.setEmail(val)
      }
    }
  },
  created () {
    if (this.$route.query.type == 1) {
      this.banner = this.bannerBlack
    } else {
      this.banner = this.bannerRed
    }
  },
  methods: {
    ...mapMakingActions(['setBanner', 'calendar', 'setEmail']),
    upload (url) {
      this.banner[this.mainIndex - 1].CustomerImg = url + '?x-oss-process=style/calendar-thumb'
      this.setBanner({ type: this.$route.query.type, data: JSON.parse(JSON.stringify(this.banner)) }).then(() => {
        this.calSize().then(() => {
          let cutDoms = document.getElementsByClassName('cutDom')[0]
          this.convert2canvas(cutDoms, this.mainIndex - 1).then(() => {
            this.isLoading = false
          }).catch(() => {
            this.isLoading = false
          })
        })
      })
    },
    emailBlur () {
      var currentPosition, timer;
      var speed = 1;//页面滚动距离
      timer = setInterval(function () {
        currentPosition = document.documentElement.scrollTop || document.body.scrollTop;
        currentPosition -= speed;
        window.scrollTo(0, currentPosition);//页面向上滚动
        currentPosition += speed; //speed变量
        window.scrollTo(0, currentPosition);//页面向下滚动
        clearInterval(timer);
      }, 1);
    },
    onRead (file) {
      let that = this
      this.isLoading = true
      let reg = new RegExp("[`/?%#&=:\s\+]")
      if (reg.test(file.file.name)) {
        this.$toast('图片名称中包含非法字符')
        this.isLoading = false
        return
      }
      let reader = new FileReader();
      reader.readAsDataURL(file.file);
      reader.onload = function (e) {
        let data = e.target.result;
        //加载图片获取图片真实宽度和高度
        let image = new Image();
        image.src = data;
        image.onload = function () {
          let width = image.width;
          let height = image.height;
          // if (!/.(jpg|jpeg)$/.test(image.src)) {
          //   that.isLoading = false
          //   that.$toast('只允许JPG/JPEG格式的图片')
          //   return
          // }
          if (width / height > 2.5) {
            that.isLoading = false
            that.$toast('该图片长度过长，请重新选择')
            return
          }
          // this.banner[this.mainIndex - 1].CustomerImgShow = file.content
          // this.setBanner({ type: this.$route.query.type, data: JSON.parse(JSON.stringify(this.banner)) })
          that.toolClass.upload(file).then((res) => {
            that.upload(res.result.url)
          }).catch(() => {
            that.isLoading = false
          })
        };
      };
    },
    changeOld () {
      if (!this.banner[this.mainIndex - 1].CustomerImg) {
        return
      }
      this.isLoading = true
      this.banner[this.mainIndex - 1].CustomerImg = ''
      // this.banner[this.mainIndex - 1].CustomerImgShow = ''
      this.setBanner({ type: this.$route.query.type, data: JSON.parse(JSON.stringify(this.banner)) }).then(() => {
        this.$nextTick(() => {
          this.calSize().then(() => {
            let cutDoms = document.getElementsByClassName('cutDom')[0]
            this.convert2canvas(cutDoms, this.mainIndex - 1).then(() => {
              this.isLoading = false
            }).catch(() => {
              this.isLoading = false
            })
          })
        })
      })
    },
    submit () {
      this.showPop = false
      if (!this.email) {
        this.$toast('邮箱为必填项')
        return
      } else if (this.email.indexOf('@') <= -1) {
        this.$toast('请输入正确的邮箱')
        return
      }
      let data = JSON.parse(JSON.stringify(this.banner))
      data.forEach((curr, index) => {
        delete curr['bgImg']
        delete curr['defaultBg']
        delete curr['style']
        delete curr['styleCut']
        if (!curr.CustomerImg) {
          curr.CustomerImg = curr.defaultNoUser
        } else {
          curr.CustomerImg = curr.CustomerImg.replace('?x-oss-process=style/calendar-thumb', '')
        }
        delete curr['defaultNoUser']
        delete curr['CustomerImgShow']
      });
      let submitData = {
        ModelName: this.$route.query.type == 1 ? '黑色' : '红色',
        Email: this.email,
        CaseId: '13',
        Imgs: data
      }
      this.calendar({ Calendar: JSON.stringify(submitData) }).then(() => {
        this.$toast('活动参与成功')
        this.$router.replace({ name: 'userCenter' })
      })
    },
    pre () {
      this.$router.push({ name: 'preview', query: { type: this.$route.query.type } })
    },
    convert2canvas (dom, i) {
      return new Promise((resolve, reject) => {
        const that = this
        var shareContent = dom;
        var width = shareContent.offsetWidth; //获取dom 宽度
        var height = shareContent.offsetHeight; //获取dom 高度
        var canvas = document.createElement("canvas"); //创建一个canvas节点
        var scale = 1; //定义任意放大倍数 支持小数
        canvas.width = width * scale; //定义canvas 宽度 * 缩放
        canvas.height = height * scale; //定义canvas高度 *缩放
        canvas.getContext("2d").scale(scale, scale); //获取context,设置scale 
        var opts = {
          scale: scale, // 添加的scale 参数
          canvas: canvas, //自定义 canvas
          // logging: true, //日志开关，便于查看html2canvas的内部执行流程
          width: width, //dom 原始宽度
          height: height,
          useCORS: true // 【重要】开启跨域配置
        };

        html2canvas(shareContent, opts).then(function (canvas) {
          var context = canvas.getContext('2d');
          // 【重要】关闭抗锯齿
          context.mozImageSmoothingEnabled = false;
          context.webkitImageSmoothingEnabled = false;
          context.msImageSmoothingEnabled = false;
          context.imageSmoothingEnabled = false;
          // 【重要】默认转化的格式为png,也可设置为其他格式
          // var img = canvas2image.convertToJPEG(canvas, canvas.width, canvas.height);
          // var blobs = that.urltoblob(img.src);
          // var namestr = `${that.banner[i].ImgName}.jpg`;
          // var file = {
          //   content: img.src,
          //   file: that.blobToFile(blobs, namestr)
          // }
          // that.toolClass.upload(file).then((res) => {
          //   that.banner[i].CalendarImg = res.result.url
          //   that.setBanner({ type: that.$route.query.type, data: JSON.parse(JSON.stringify(that.banner)) })
          //   resolve()
          // }).catch(() => {
          //   reject()
          // })
          let file = {
            namestr: `${that.banner[i].ImgName}.jpg`,
            base64str: encodeURIComponent(canvas.toDataURL('image/jpeg', 0.8))
          }
          that.toolClass.uploadBase64(file).then((res) => {
            that.banner[i].CalendarImg = res.result.url
            that.setBanner({ type: that.$route.query.type, data: JSON.parse(JSON.stringify(that.banner)) })
            resolve()
          }).catch(() => {
            reject()
          })
        }).catch((err) => {
          console.log(err)
          that.isLoading = false
        })
      })
    },
    urltoblob (dataURL) {
      var BASE64_MARKER = ';base64,';
      if (dataURL.indexOf(BASE64_MARKER) == -1) {
        var parts = dataURL.split(',');
        var contentType = parts[0].split(':')[1];
        var raw = decodeURIComponent(parts[1]);
        return new Blob([raw], { type: contentType });
      }
      var parts = dataURL.split(BASE64_MARKER);
      var contentType = parts[0].split(':')[1];
      var raw = window.atob(parts[1]);
      var rawLength = raw.length;
      var uInt8Array = new Uint8Array(rawLength);
      for (var i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
      }
      return new Blob([uInt8Array], { type: contentType });
    },
    blobToFile (theBlob, fileName) {
      theBlob.lastModifiedDate = new Date();
      theBlob.name = fileName;
      return theBlob;
    },
    calSize () {
      return new Promise((resolve) => {
        let rotate = this.size
        let dom = document.getElementsByClassName('cla')
        if (dom.length < 2) {
          resolve()
          return
        }
        dom = dom[1]
        let parentW = dom.offsetWidth
        let parentH = dom.offsetHeight
        dom.children[0].onload = function () {
          let imgW = dom.children[0].naturalWidth
          let imgH = dom.children[0].naturalHeight
          if (rotate === '横') {
            if (imgW <= imgH) {
              dom.children[0].style = 'width:100%;'
              let Offset = -((dom.children[0].height - parentH) / 2)
              dom.children[0].style = `width:100%;position:relative;top:${Offset}px;left:0`
              resolve()
            } else {
              dom.children[0].style = 'height:100%;'
              let Offset = -((dom.children[0].width - parentW) / 2)
              dom.children[0].style = `height:100%;position:relative;left:${Offset}px;top:0`
              resolve()
            }
          } else {
            if (imgW >= imgH) {
              dom.children[0].style = 'height:100%;'
              let Offset = -((dom.children[0].width - parentW) / 2)
              dom.children[0].style = `height:100%;position:relative;left:${Offset}px;top:0`
              resolve()
            } else {
              dom.children[0].style = 'width:100%;'
              let Offset = -((dom.children[0].height - parentH) / 2)
              dom.children[0].style = `width:100%;position:relative;top:${Offset}px;left:0`
              resolve()
            }
          }
        }
      })
    }
  }
}
</script>

<style lang="scss">
.swiper-pagination-current {
  color: #fc6243;
}
</style>


<style lang="scss" scoped>
.input {
  border-radius: 5px;
  background: rgb(245, 246, 250);
  width: 100%;
  height: 0.4rem;
  padding-left: 0.1rem;
}
.mainPage {
  position: fixed;
  overflow-y: scroll;
}
.cla {
  overflow: hidden;
  z-index: 10;
}
.loading {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;
  display: flex;
  flex-flow: column nowrap;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  background: rgba(0, 0, 0, 0.6);
  img {
    width: 0.5rem;
    height: 0.5rem;
  }
  span {
    font-size: 0.14rem;
    color: #fff;
  }
}
.meassage {
  color: red;
  padding: 0.1rem;
  text-align: center;
  font-size: 0.12rem;
}
.pop-box {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;
  display: flex;
  flex-flow: column nowrap;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  background: rgba(0, 0, 0, 0.6);
  .pop-content {
    width: 2.6rem;
    height: 1.7rem;
    background: rgba(255, 255, 255, 1);
    box-shadow: 0px 2px 4px 0px rgba(194, 194, 194, 0.5);
    border-radius: 4px;
    > div {
      padding-top: 0.5rem;
      font-size: 0.16rem;
      display: flex;
      justify-content: center;
      align-items: center;
      div {
        margin: 0 0.12rem;
        padding: 0.08rem 0.3rem;
        border-radius: 4px;
        border: 1px solid;
      }
    }
  }
}
.cutBox {
  z-index: -1;
  position: absolute;
  top: -10rem;
  left: -10rem;
  > div {
    position: relative;
    width: 13cm;
    height: 21cm;
    .cover {
      width: 100%;
      height: 100%;
    }
    .text-h {
      width: 9cm;
      position: absolute;
      top: 8.8cm;
      left: 1cm;
      z-index: 3;
    }
    .text-l {
      width: 0.85cm;
      position: absolute;
      top: 2.8cm;
      left: 1cm;
      z-index: 3;
    }
  }
}
.topBanner {
  width: 100%;
  height: 3.3rem;
  background: #e9e9e9;
  position: relative;
  overflow: hidden;
  &::before {
    content: '';
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 1.65rem;
    box-sizing: border-box;
    border-bottom: 1px dashed #d1d1d1;
    transform-origin: bottom center;
    transform: rotateZ(41deg) scale(1.414);
  }
  &::after {
    content: '';
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 1.65rem;
    box-sizing: border-box;
    border-bottom: 1px dashed #d1d1d1;
    transform-origin: bottom center;
    transform: rotateZ(-41deg) scale(1.414);
  }
  .swiper-container {
    width: 100%;
    height: 100%;
  }
  .swiper-button-next,
  .swiper-button-prev {
    background-image: url();
    outline: 0px;
    text-align: center;
    line-height: 0.44rem;
  }
  .swiper-cover {
    z-index: 2;
    position: absolute;
    bottom: 0.1rem;
    left: 50%;
    transform: translateX(-50%);
    font-size: 0.12rem;
    color: #fc6243;
  }
  .item {
    position: relative;
    height: 100%;
    > div {
      position: absolute;
      width: 1.7rem;
      height: 2.7rem;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      .cover {
        width: 100%;
        height: 100%;
      }
      .text-h {
        width: 1.2rem;
        position: absolute;
        top: 1.12rem;
        left: 0.2rem;
        z-index: 3;
      }
      .text-l {
        width: 0.1rem;
        position: absolute;
        top: 0.4rem;
        left: 0.16rem;
        z-index: 3;
      }
      .reload-img {
        width: 0.2rem;
        height: 0.2rem;
        position: absolute;
        top: 0.02rem;
        right: 0.02rem;
        z-index: 3;
        img {
          width: 100%;
          height: 100%;
        }
      }
    }
  }
}
.operation {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0.15rem 0.2rem 0.3rem;
  > div {
    text-align: center;
    height: 0.68rem;
    margin: 0 0.4rem;
    img {
      width: 0.68rem;
      height: 0.68rem;
    }
    p {
      color: #8a8a8a;
      padding-top: 0.05rem;
    }
  }
}
.email {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0 0.25rem;
  box-sizing: border-box;
  span {
    width: 0.5rem;
  }
}
.btn {
  margin-top: 0.1rem;
  width: 100%;
  box-sizing: border-box;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0 0.2rem;
  div {
    flex: 1;
    margin: 0.1rem;
    border-radius: 20px;
    height: 0.4rem;
    text-align: center;
    line-height: 0.4rem;
    background-color: #fc6243;
    color: #fff;
  }
  div:nth-of-type(1) {
    background: #9db0ce;
  }
}
</style>
