<template>
  <div class="photo" ref="waterMarker" :class="[isHide ? 'home-active' : '']" :style="{height: height + 'px'}">
    <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="save">保存</span>
    </div>
    <image :src="img" mode="aspectFit" />
    <div class="watermark" v-if="currIndex > -1 && currWatermarkConfig.length">
      <component :is="'Watermark' + (currIndex + 1)" :config="currWatermarkConfig"></component>
    </div>
    <div class="photo-bottom" data-html2canvas-ignore>
      <div class="photo-bottom__top">
        <image src="./images/clear.png" @click="isHide = true, currIndex = -1" />
        <h2>水印</h2>
        <span>确定</span>
      </div>
      <div class="waterlist">
        <div
          class="water-item"
          :class="[currIndex === index ? 'active' : '']"
          v-for="(item, index) in watermarkList"
          :key="item.id"
          @click="currIndex = index">
          <image :src="item.thum" mode="aspectFill" />
          <div class="water-item__bottom">{{ item.name }}</div>
        </div>
      </div>
    </div>
    <div class="photo-tabbar"  data-html2canvas-ignore>
      <div class="item" @click="back">
        <image src="./images/fanhui.png" />
        <div>返回</div>
      </div>
      <div class="item" @click="isHide = false, currIndex = 0">
        <image src="./images/shuiyin.png" />
        <div>水印</div>
      </div>
      <div class="item" @click="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: []
      }
    },

    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.getWatermarkList()

      this.getLocation()

      this.$http.post('/api/appdvcpconfig/apiForward', 'https://apis.map.qq.com/ws/geocoder/v1/?location=39.984154,116.307490&key=3RZBZ-LZUCF-CT6J5-NWKZH-FCWOQ-UUFKY&get_poi=1').then(res => {
        console.log(res)
      })
    },

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

      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)
                  }
                })
              }
            })
            // this.waterSrc = dataURL
          }).catch(e => {
            console.log(e)
          })
        })
      },

      getLocation () {
        this.injectJWeixin(['getLocation']).then(res => {
          console.log(res)
          wx.getLocation({
            type: 'wgs84',
            success: function (res) {
              var lat = res.latitude
              var lng = res.longitude
              console.log(lat, lng)
              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 => {
                console.log(res)
              })
            },
            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, {
          parmas: {
            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 {
    position: relative;
    width: 100%;
    height: 800px;
    background: #444;
    overflow: hidden;

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

    * {
      box-sizing: border-box;
    }

    .watermark {
      position: fixed;
      left: 32px;
      bottom: 512px;
      z-index: 111;
      color: #FFFFFF;
      font-size: 28px;
    }

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

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

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

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

    .photo-bottom {
      position: fixed;
      bottom: 0;
      left: 0;
      z-index: 11;
      width: 100%;
      height: 474px;
      background: #FFFFFF;
      border-radius: 32px 32px 0px 0px;

      .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: 176px;
            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: 336px;
        height: 72px;
        line-height: 1;
        background: #0B111F;
        border-radius: 40px;
        font-size: 28px;
        color: #cbcbcb;

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

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

      .watermark {
        bottom: 38px;
      }
    }

    & > image {
      width: 100%;
      height: 100%;
    }
  }
</style>
