<template>
  <div class="photo" :class="[isHide ? 'home-active' : '']" :style="{height: height + 'px'}" @click="isHide = true">
    <div class="photo-top" data-html2canvas-ignore>
      <image src="./images/close.png" @click="back" />
      <div class="photo-top__middle" @click="isShowAlbum = true">
        <span>保存至：{{ albumName || '默认相册' }}</span>
        <image src="./images/to-right.png" />
      </div>
      <span @click.stop="save">保存</span>
    </div>
    <div ref="waterMarker" class="waterMarker-wrapper" :style="{height: canvasHeight + 'px'}">
      <image class="waterMarker-img" :src="img" mode="widthFix" @load="onImgLoad" />
      <div
        class="watermark"
        v-if="currIndex > -1 && currWatermarkConfig.length"
        :style="{left: x + 'px', top: y + 'px' }"
        @touchstart="onTouchstart"
        @touchmove="onTouchmove">
        <component :is="'Watermark' + (currIndex + 1)" :config="currWatermarkConfig"></component>
      </div>
    </div>
    <div class="photo-bottom" data-html2canvas-ignore>
      <div class="photo-bottom__top">
        <image src="./images/clear.png" @click.stop="isHide = true, currIndex = -1" />
        <h2>水印</h2>
        <span @click.stop="isHide = true">确定</span>
      </div>
      <div class="waterlist">
        <div
          class="water-item"
          :class="[currIndex === index ? 'active' : '']"
          v-for="(item, index) in watermarkList"
          :key="item.id"
          @click.stop="currIndex = index">
          <image :src="item.thum" />
          <div class="water-item__bottom">{{ item.name }}</div>
        </div>
      </div>
    </div>
    <div class="photo-tabbar"  data-html2canvas-ignore>
      <div class="item" @click.stop="back">
        <image src="./images/fanhui.png" />
        <div>返回</div>
      </div>
      <div class="item" @click.stop="isHide = false">
        <image src="./images/shuiyin.png" />
        <div>水印</div>
      </div>
      <div class="item" @click.stop="save">
        <image src="./images/shangchuan.png" />
        <div>上传</div>
      </div>
    </div>
    <u-select v-model="isShowAlbum" :default-value="defaultValue" :list="albumList" @confirm="onConfirm"></u-select>
  </div>
</template>

<script>
  import html2canvas from 'html2canvas'
  import Watermark1 from './components/watermark/Watermark1'
  import Watermark2 from './components/watermark/Watermark2'
  import Watermark3 from './components/watermark/Watermark3'
  import Watermark4 from './components/watermark/Watermark4'
  import Watermark5 from './components/watermark/Watermark5'
  import Watermark6 from './components/watermark/Watermark6'
  import Watermark7 from './components/watermark/Watermark7'
  import Watermark8 from './components/watermark/Watermark8'
  import { mapActions } from 'vuex'

  export default {
    name: 'Watermark',

    appName: '水印相机',

    components: {
      Watermark1,
      Watermark2,
      Watermark3,
      Watermark4,
      Watermark5,
      Watermark6,
      Watermark7,
      Watermark8
    },

    data () {
      return {
        img: '',
        currIndex: 0,
        isHide: false,
        height: '100%',
        waterSrc: '',
        albumId: '1',
        albumName: '',
        watermarkList: [],
        isShowAlbum: false,
        albumList: [],
        address: {},
        x: 32,
        y: 200,
        startX: 0,
        startY: 0,
        canvasHeight: 0
      }
    },

    computed: {
      defaultValue () {
        if (!this.albumList.length) {
          return [0]
        }

        return [this.albumList.map(v => v.value).indexOf(this.albumId)]
      },

      currWatermarkConfig () {
        if (this.currIndex < 0 || !this.watermarkList.length) return []

        return this.watermarkList[this.currIndex].itemList
      }
    },

    onLoad (query) {
      if (query.albumId) {
        this.albumId = query.albumId
      }

      this.img = query.url
      this.height = uni.getSystemInfoSync().windowHeight

      this.getLocation()

      this.$nextTick(() => {
        this.getWatermarkList()
      })
    },

    methods: {
      ...mapActions(['injectJWeixin']),

      onImgLoad () {
        const img = document.querySelector('.waterMarker-img')

        this.canvasHeight = img.clientHeight
      },

      onTouchstart (e) {
        const isMobile = e.type !== 'mousemove'
        const watermark = document.querySelector('.watermark')
        if (isMobile) {
          this.startX = e.touches[0].clientX - Number((watermark.style.left).replace('px', ''))
          this.startY = e.touches[0].clientY - Number((watermark.style.top).replace('px', ''))
        } else {
          this.startX = e.clientX - Number((watermark.style.left).replace('px', ''))
          this.startY = e.clientY -Number((watermark.style.top).replace('px', ''))
        }
      },

      onTouchmove (e) {
        const isMobile = e.type !== 'mousemove'
        if (isMobile) {
          this.x = e.touches[0].clientX - this.startX
          this.y = e.touches[0].clientY - this.startY
        } else {
          this.x = e.clientX - this.startX
          this.y = e.clientY - this.startY
        }
      },

      save () {
        this.isHide = true
        this.$loading()
        this.$nextTick(() => {
          html2canvas(this.$refs.waterMarker, {
            allowTaint: true,
            useCORS: true
          }).then((canvas) => {
            let dataURL = canvas.toDataURL('image/png')
            const file = this.dataURLtoFile(dataURL, 'photo.png')
            let formData = new FormData()
            formData.append('file', file)
            this.$http.post('/admin/file/add2?type=image', formData).then(res => {
              if (res.code === 0) {
                let info = {}
                if (this.currIndex > -1) {
                  info = this.watermarkList[this.currIndex]
                }
                this.$http.post('/api/appalbumphoto/addOrUpdate', {
                  albumId: this.albumId,
                  photoUrl: res.data.url,
                  fileId: res.data.id,
                  watermarkType: this.currIndex > -1 ? info.watermarkType : '',
                  templateId: this.currIndex > -1 ? info.id : ''
                }).then(res => {
                  if (res.code === 0) {
                    uni.$emit('update')
                    this.$u.toast('新增成功')

                    setTimeout(() => {
                      this.back()
                    }, 500)
                  }
                })
              }
            })
          }).catch(e => {
            console.log(e)
          })
        })
      },

      getWeather (code) {
        this.$http.post(`/api/bdweather/wdata?districtId=${code}`).then(res => {
          console.log(res)
          if (res.code === 0) {
            const data = res.data.result.now

            uni.setStorageSync('address', {
              ...uni.getStorageSync('address'),
              weather: data.text || ''
            })

            this.address = {
              ...uni.getStorageSync('address'),
              weather: data.text || ''
            }
          }
        })
      },

      getLocation () {
        this.injectJWeixin(['getLocation']).then(res => {
          wx.getLocation({
            type: 'wgs84',
            success: res => {
              var lat = res.latitude
              var lng = res.longitude
              this.$http.post('/api/appdvcpconfig/apiForward', `https://apis.map.qq.com/ws/geocoder/v1/?location=${lat},${lng}&key=3RZBZ-LZUCF-CT6J5-NWKZH-FCWOQ-UUFKY&get_poi=1`).then(res => {
                if (res.code === 0) {
                  const data = res.data.result
                  uni.setStorageSync('address', {
                    lat,
                    lng,
                    address: data.address,
                    cityCode: `${data.ad_info.adcode}`
                  })

                  this.getWeather(`${data.ad_info.adcode}`)
                }
              })
            },
            error: res => {
              console.log(res)
            }
          })
        })
      },

      dataURLtoFile (dataurl, filename) {
        let arr = dataurl.split(',')
        let mime = arr[0].match(/:(.*?);/)[1]
        let bstr = atob(arr[1])
        let n = bstr.length
        let u8arr = new Uint8Array(n)
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n)
        }
        return new File([u8arr], filename, { type: mime })
      },

      onConfirm (e) {
        this.albumId = e[0].value
        this.albumName = e[0].label
      },

      getWatermarkList () {
        this.$http.post(`/api/appalbumtemplate/list?size=100&templateType=0`).then(res => {
          if (res.code === 0) {
            this.watermarkList = res.data.records
          }
        })

        this.$http.post('/api/appalbum/list', null, {
          params: {
            size: 1000
          }
        }).then(res => {
          if (res.code === 0) {
            this.albumList = res.data.records.map(v => {
              return {
                label: v.albumName,
                value: v.id
              }
            })

            this.albumName = this.albumList.filter(v => v.value === this.albumId)[0].label
          }
        })
      },

      back () {
        uni.navigateBack({
          delta: 1
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .photo {
    display: flex;
    position: relative;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100vh;
    background: #333;
    overflow: hidden;

    .newImg {
      position: fixed;
      left: 0;
      top: 0;
      z-index: 11111;
      width: 100%;
      height: 100%;
    }

    .waterMarker-wrapper {
      width: 100%;
      max-height: 100vh;
      overflow: hidden;

      .waterMarker-img {
        width: 100%;
        max-height: 100vh;
      }

      .watermark {
        position: absolute;
        left: 32px;
        z-index: 11;
        color: #FFFFFF;
        font-size: 28px;
      }
    }

    * {
      box-sizing: border-box;
    }

    .photo-tabbar {
      display: flex;
      position: fixed;
      align-items: center;
      bottom: 0;
      left: 0;
      z-index: 10;
      width: 100%;
      height: 160px;
      background: #1E1E21;

      .item {
        flex: 1;
        text-align: center;

        image {
          width: 56px;
          height: 56px;
          margin-bottom: 6px;
        }

        div {
          font-size: 28px;
          color: #fff;
        }
      }
    }

    .photo-bottom {
      position: fixed;
      bottom: 0;
      left: 0;
      z-index: 111;
      width: 100%;
      height: 474px;
      background: #FFFFFF;
      border-radius: 32px 32px 0px 0px;
      transition: all ease 0.3s;

      .waterlist {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
        align-items: center;
        height: calc(100% - 96px);
        padding: 18px 16px;
        overflow-y: auto;

        .water-item {
          display: flex;
          position: relative;
          align-items: center;
          justify-content: center;
          width: 352px;
          height: 240px;
          margin-bottom: 16px;
          background: #2A3540;
          border-radius: 8px;
          overflow: hidden;

          &.active {
            border: 6px solid #408EF6;
          }

          image {
            width: 236px;
            height: 200px;
          }

          .water-item__bottom {
            position: absolute;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 56px;
            line-height: 56px;
            color: #fff;
            text-align: center;
            font-size: 28px;
            background: rgba(0, 0, 0, 0.7);
          }
        }
      }

      .photo-bottom__top {
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 96px;
        padding: 0 32px;

        image {
          width: 40px;
          height: 40px;
        }

        h2 {
          font-size: 28px;
          color: #333;
        }

        span {
          font-size: 32px;
          color: #222;
          font-weight: 600;
        }
      }
    }

    .photo-top {
      display: flex;
      position: fixed;
      align-items: center;
      justify-content: space-between;
      top: 0;
      left: 0;
      z-index: 11;
      width: 100%;
      height: 128px;
      padding: 0 32px;
      background: rgba(0, 0, 0, 0.5);

      & > image {
        width: 28px;
        height: 28px;
      }

      & > span {
        color: #cbcbcb;
        font-size: 32px;
      }

      .photo-top__middle {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 400px;
        height: 72px;
        line-height: 1;
        background: #0B111F;
        border-radius: 40px;
        font-size: 28px;
        color: #cbcbcb;

        span {
          max-width: 70%;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        image {
          width: 32px;
          height: 32px;
          margin-left: 16px;
        }
      }
    }

    &.home-active {
      .photo-bottom {
        transform: translateY(100%);
      }

      .watermark {
        // bottom: 38px;
      }
    }
  }
</style>
