<template>
  <div class="photo" v-if="pageShow">
    <div class="header" :class="[isFixed ? 'header-active' : '']">
      <div class="status-bar" :style="{height: statusBarHeight + 'px'}"></div>
      <div class="nav-bar">
        <image src="/static/img/left.png" @click="back"/>
        <h2>乡村相册</h2>
      </div>
    </div>
    <div class="back-wrapper" @click="back" v-show="!isFixed" :style="{marginTop : statusBarHeight + 'px'}">
      <image src="/static/img/left.png"/>
    </div>
    <div class="photo-header">
      <image :src="coverImg" mode="aspectFill"/>
      <h2>{{ name }}</h2>
    </div>
    <div class="photo-info">
      <div class="photo-info__item">
        <h2>{{ info.total }}</h2>
        <span>照片</span>
      </div>
      <div class="photo-info__item">
        <h2>{{ info.thisMonth }}</h2>
        <span>本月</span>
      </div>
      <div class="photo-info__item">
        <h2>{{ info.lastMonth }}</h2>
        <span>上月</span>
      </div>
      <div class="photo-info__item">
        <h2>{{ info.thisYear }}</h2>
        <span>今年</span>
      </div>
    </div>
    <div class="photo-list">
      <div class="photo-group" v-for="(group, index) in list" :key="index">
        <h2>{{ group.name }}</h2>
        <div class="photo-wrapper">
          <div class="photo-item" v-for="(item, i) in group.list" :key="i">
            <image :src="item.url" @click="preview(item.url)" mode="aspectFill"/>
            <div class="photo-item__text">
              <span>{{ item.createUserName }} 上传</span>
            </div>
          </div>
        </div>
      </div>
      <AiEmpty v-if="!list.length" description="暂无照片"></AiEmpty>
    </div>
    <div class="btn-wrapper">
      <div class="btn" @click="upload" hover-class="text-hover">上传图片</div>
    </div>
    <AiLogin ref="login"/>
  </div>
</template>

<script>
import {mapState} from 'vuex'

export default {
  name: "AppPhotoAlbum",
  appName: "乡村相册",
  customNavigation: true,
  data() {
    return {
      isFixed: false,
      statusBarHeight: 20,
      list: [],
      type: '',
      info: {},
      name: '',
      coverImg: '',
      imgList: [],
      hideStatus: false,
      pageShow: false
    }
  },

  computed: {
    ...mapState(['user', 'token'])
  },

  onLoad(query) {
    this.type = query.type
    this.name = query.name
    this.coverImg = query.url
    this.statusBarHeight = uni.getSystemInfoSync().statusBarHeight

    this.$loading()
    this.getList(query.type)
    this.getTotalInfo(query.type)
  },

  onUnload() {
    // uni.$off('update')
  },

  methods: {
    back() {
      uni.navigateBack({
        delta: 1
      })
    },

    preview(url) {
      let imgs = []
      this.list.forEach(item => {
        imgs = [...imgs, ...item.list.map(v => v.url)]
      })

      uni.previewImage({
        urls: imgs,
        current: url
      })
    },

    upload() {
      if (!this.token) {
        this.$refs.login.show()

        return false
      }

      this.imgList = []
      this.hideStatus = false
      uni.chooseImage({
        count: this.limit,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          if (res.tempFilePaths.length > 9) {
            this.$toast(`图片不能超过9张`)

            return false
          }

          this.$loading('上传中')
          res.tempFilePaths.forEach((item, index) => {
            if (index === res.tempFilePaths.length - 1) {
              this.hideStatus = true
            }

            this.$nextTick(() => {
              this.uploadFile(item, res.tempFilePaths.length)
            })
          })
        },
      })
    },

    uploadFile(img, total) {
      uni.uploadFile({
        url: this.$instance.defaults.baseURL + '/admin/file/add',
        filePath: img,
        name: 'file',
        header: {
          'Content-Type': 'multipart/form-data',
          Authorization: uni.getStorageSync('token'),
        },
        success: (res) => {
          const data = JSON.parse(res.data)

          if (data.code === 0) {
            this.imgList.push(data.data[0].split(';')[0])
          } else {
            this.$toast(data.msg)
          }
        },
        complete: () => {
          this.$nextTick(() => {
            if (this.imgList.length === total && this.hideStatus) {
              this.$instance.post(`/app/appvillagepicturealbum/addPictures`, {
                areaName: uni.getStorageSync('areaName'),
                areaId: uni.getStorageSync('areaId'),
                type: this.type,
                urlList: this.imgList
              }).then(res => {
                if (res.code == 0) {
                  this.getList(this.type)
                  this.getTotalInfo(this.type)
                  uni.$emit('update')
                }
                this.$hideLoading()
                this.hideStatus = false
              })
            }
          })
        }
      })
    },

    getTotalInfo(type) {
      this.$instance.post(`/app/appvillagepicturealbum/statistic?areaId=${uni.getStorageSync('areaId')}&type=${type}`).then(res => {
        if (res.code === 0) {
          this.info = res.data
        }
      })
    },

    getList(type) {
      this.$instance.post(`/app/appvillagepicturealbum/queryAlbum?areaId=${uni.getStorageSync('areaId')}&type=${type}`).then(res => {
        if (res.code === 0) {
          this.list = Object.keys(res.data).map(v => {
            return {
              name: v,
              list: res.data[v]
            }
          })

          this.$nextTick(() => {
            this.pageShow = true
          })
        }

        this.$hideLoading()
      })
    }
  },

  onPageScroll(params) {
    this.isFixed = params.scrollTop > 60;
  }
}
</script>

<style lang="scss" socped>
.photo {
  width: 100vw;
  overflow-x: hidden;
  padding-bottom: 130px;

  * {
    box-sizing: border-box;
  }

  .back-wrapper {
    position: fixed;
    z-index: 11;
    left: 20px;
    top: 24px;
    width: 40px;
    height: 40px;

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

  .header {
    position: fixed;
    left: 0;
    top: 0;
    z-index: 0;
    width: 100%;
    opacity: 0;
    transition: all 0.2s ease;

    &.header-active {
      z-index: 1111;
      opacity: 1;
      background: linear-gradient(180deg, #4670F5 0%, #4772F5 100%);
    }

    .nav-bar {
      position: relative;
      height: 88px;
      line-height: 88px;
      color: #fff;
      font-size: 32px;
      text-align: center;

      image {
        position: absolute;
        top: 0;
        left: 0;
        z-index: 1;
        width: 40px;
        height: 40px;
        padding: 24px 20px 0 20px;
        box-sizing: content-box;
      }
    }
  }

  .photo-header {
    position: relative;
    height: 400px;

    image {
      width: 100%;
      height: 400px;
      filter: blur(2px);
    }

    h2 {
      display: flex;
      position: absolute;
      align-items: center;
      justify-content: center;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      z-index: 1;
      color: #fff;
      background: rgba(0, 0, 0, 0.1);
      font-size: 56px;
    }
  }

  .photo-info {
    display: flex;
    align-items: center;
    height: 168px;
    background: #FFFFFF;
    box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.02);

    & > div {
      flex: 1;
      text-align: center;

      h2 {
        margin-bottom: 10px;
        font-weight: 600;
        font-size: 38px;
        color: #333333;
      }

      span {
        color: #999999;
        font-size: 26px;
      }
    }
  }

  .photo-list {
    margin-top: 32px;
    padding: 0 32px;

    h2 {
      margin-bottom: 32px;
      color: #333333;
      font-size: 38px;
    }

    .photo-wrapper {
      display: flex;
      flex-wrap: wrap;

      .photo-item {
        position: relative;
        width: 328px;
        height: 328px;
        margin-right: 30px;
        margin-bottom: 32px;
        border-radius: 12px;
        overflow: hidden;

        &:nth-of-type(2n) {
          margin-right: 0;
        }

        .photo-item__text {
          position: absolute;
          bottom: 0;
          left: 0;
          z-index: 1;
          width: 100%;
          height: 80px;
          line-height: 80px;
          padding: 0 16px;
          color: #FFFFFF;
          font-size: 26px;
          background: linear-gradient(180deg, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.5) 100%);
        }

        image {
          width: 328px;
          height: 328px;
        }
      }
    }
  }
}
</style>
