<template>
  <div id="MyAlbum">
    <div class="photo_box">
      <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="getUserAlbum">
        <div class="day_box" v-for="(dayItem, dayIndex) in photoArr" :key="dayIndex">
          <p class="day_time">{{ dayItem.time }}</p>
          <div
            class="item"
            v-for="(item, index) in dayItem.photos"
            :key="index"
            :style="'background-image:url(' + item.img + ')'"
            @click="handlePhoto(dayIndex, index)"
          >
            <div class="check_icon" :class="item.checked ? 'checked' : ''" v-if="controlStatus == 'del'">
              <van-icon class="icon" name="success" />
            </div>
          </div>
        </div>
      </van-list>
    </div>
    <div class="control_panel">
      <p class="control_btn" @click="controlStatus = 'control'" v-if="controlStatus == 'default'">管理相册({{ spaceSize }}/2G)</p>
      <div class="control_box" v-if="controlStatus == 'control'">
        <van-uploader multiple :after-read="afterRead">
          <div class="btn add">
            <van-icon class="icon" name="add-o" />
            <p class="text">添加</p>
          </div>
        </van-uploader>
        <div class="btn del" @click="controlStatus = 'del'">
          <van-icon class="icon" name="delete-o" />
          <p class="text">删除</p>
        </div>
        <van-button class="blue_btn" type="info" round color="#3074FF" @click="controlStatus = 'default'">完成</van-button>
      </div>
      <p class="cancel_btn" @click="controlStatus = 'control'" v-if="controlStatus == 'del'">取消</p>
      <p class="del_btn" @click="handleDel" v-if="controlStatus == 'del'">删除相片</p>
    </div>
    <van-image-preview v-model="showPreview" :images="previewArr" :start-position="startPosition" @change="previewChange">
    </van-image-preview>
  </div>
</template>
<script>
import Axios from 'axios'
export default {
  data() {
    return {
      userInfo: '',
      photoArr: [], //照片数组
      total: '', //照片总数
      showPreview: false,
      startPosition: 0,
      previewIndex: 0,
      previewArr: [],
      pageSize: 10,
      pageNum: 1,
      loading: false,
      finished: false,
      controlStatus: 'default', //默认状态:default 管理状态:control 删除状态:del
      delIds: [], //需要删除的图片id数组
      uploadImgList: [], //上传图片数组
      spaceSize: [], //用户空间
    }
  },
  mounted() {
    var userInfo = localStorage.getItem('userInfo')
    if (userInfo) {
      this.userInfo = JSON.parse(userInfo)
    }

    // this.getUserAlbum()//获取当前用户相关的商户相册
    this.getUserSpaceSize()
  },
  methods: {
    //获取当前用户相关的商户相册
    getUserAlbum() {
      this.loading = true
      this.yxAxios
        .post(`${this.proxyUrl}/api/growth/photo/userAlbum`, {
          centerNo: this.userInfo.centerNo,
          pageSize: this.pageSize,
          pageNum: this.pageNum,
        })
        .then((res) => {
          console.log('相册详情:', res)
          this.loading = false
          if (res.data.code == 200) {
            this.formatPhoto(res.data.rows)
            this.total = res.data.total
            if (this.pageSize * this.pageNum >= res.data.total) {
              this.finished = true
            } else {
              this.pageNum++
            }
          } else {
            // this.$toast(res.data.message);
            console.log(res.data.message)
          }
        })
    },
    // 获取用户空间大小
    getUserSpaceSize() {
      this.yxAxios
        .post(`${this.proxyUrl}/api/growth/photo/getUserSpaceSize`, {
          centerNo: this.userInfo.centerNo,
        })
        .then((res) => {
          console.log('空间大小:', res)
          if (res.data.code == 200) {
            const sizeM = res.data.data / 1024 / 1024
            if (sizeM / 1024 > 1000) {
              this.spaceSize = (sizeM / 1024).toFixed(2) + 'G'
            } else {
              this.spaceSize = sizeM.toFixed(2) + 'M'
            }
            console.log(this.spaceSize)
          } else {
            // this.$toast(res.data.message);
            console.log(res.data.message)
          }
        })
    },
    // 处理照片数组
    formatPhoto(data) {
      let photoArr = this.photoArr
      var weekArr = ['一', '二', '三', '四', '五', '六', '日']
      for (let i in data) {
        let week = this.Moment(data[i].createTime).isoWeekday()
        data[i].time = this.Moment(data[i].createTime).format('MM月DD日') + ' 周' + weekArr[week - 1]
        data[i].checked = false
        if (photoArr.length == 0) {
          photoArr.push({
            time: data[i].time,
            photos: [data[i]],
          })
        } else if (photoArr[photoArr.length - 1].time == data[i].time) {
          photoArr[photoArr.length - 1].photos.push(data[i])
        } else {
          photoArr.push({
            time: data[i].time,
            photos: [data[i]],
          })
        }
      }
      console.log('处理后的photoArr:', photoArr)
      this.photoArr = photoArr
    },
    // 预览图切换
    previewChange(index) {
      this.previewIndex = index
    },
    // 点击照片
    handlePhoto(dayIndex, index) {
      // 先判断状态，删除操作时为选择图片，默认状态为预览图片操作,操作状态不触发事件
      if (this.controlStatus == 'del') {
        this.photoArr[dayIndex].photos[index].checked = !this.photoArr[dayIndex].photos[index].checked
      } else if (this.controlStatus == 'default') {
        let previewArr = []
        for (let i in this.photoArr[dayIndex].photos) {
          previewArr.push(this.photoArr[dayIndex].photos[i].img)
        }
        this.previewArr = previewArr
        this.startPosition = index
        this.previewIndex = index
        this.showPreview = true
      }
    },

    // 点击删除照片
    handleDel() {
      // 计算需要删除的图片
      let delIds = []
      for (let i in this.photoArr) {
        for (let j in this.photoArr[i].photos) {
          if (this.photoArr[i].photos[j].checked) {
            delIds.push(this.photoArr[i].photos[j].id)
          }
        }
      }
      this.delIds = delIds
      if (this.delIds.length == 0) {
        this.$toast('请至少选择一张照片')
      } else {
        this.$dialog
          .confirm({
            title: '警告',
            message: '确认删除照片？',
          })
          .then(() => {
            this.delPhotoByIds()
          })
          .catch(() => {
            // on cancel
          })
      }
    },
    // 删除照片操作
    delPhotoByIds() {
      this.$toast.loading({
        message: '正在删除...',
        duration: 0,
        forbidClick: true,
      })
      this.http.removePersonPhoto(this.delIds.join(',')).then((res) => {
        this.$toast.clear()
        if (res.code == 200) {
          this.$toast('删除成功')
          this.controlStatus = 'control'
          this.pageReload() //删除成功后页面重新加载
        } else {
          this.$toast(res.message)
        }
      })
    },
    // 页面数据重新加载
    pageReload() {
      this.pageNum = 1
      this.finished = false
      this.photoArr = []
      this.getUserAlbum()
      this.getUserSpaceSize()
    },
    // 读取到文件后
    afterRead(file) {
      if (Array.isArray(file)) {
        this.fileUpload(file, 0)
      } else {
        this.fileUpload([file], 0)
      }
    },
    // 上传照片到文件服务器
    fileUpload(files, index) {
      this.$toast.loading({
        message: `上传中 ${index + 1}/${files.length}...`,
        duration: 0,
        forbidClick: true,
      })
      let size = files[index].file.size
      let params = new FormData()
      params.append('file', files[index].file, files[index].file.name)
      let config = {
        headers: {
          //添加请求头
          'Content-Type': 'multipart/form-data',
        },
      }
      Axios.post('https://market.myjxt.com:51311/file/fileUpload', params, config).then((res) => {
        this.$toast.clear()
        if (res?.status == 200) {
          this.uploadImgList.push({ path: res.data, imgSize: size })
        } else {
          this.$toast(`照片${index + 1}上传失败，自动忽略`)
        }
        if (index + 1 < files.length) {
          this.fileUpload(files, index + 1)
        } else {
          // 照片全部上传完成，统一上传到服务器
          this.uploadUserAlbum()
        }
      })
    },
    // 上传照片
    uploadUserAlbum() {
      this.$toast.loading({
        message: `同步照片到我的相册...`,
        duration: 0,
        forbidClick: true,
      })
      this.http
        .uploadUserAlbum({
          centerNo: this.userInfo.centerNo,
          imgList: this.uploadImgList,
        })
        .then((res) => {
          this.$toast.clear()
          if (res.code == 200) {
            this.$toast('同步完成')
            this.uploadImgList = []
            this.pageReload() //上传完成后页面重新加载
          } else {
            this.$toast(res.message)
          }
        })
    },
  },
}
</script>
<style lang="scss">
#MyAlbum {
  height: 100%;
  .photo_box {
    min-height: 100%;
    box-sizing: border-box;
    padding: 24px;
    padding-bottom: 168px;
    background: #f5f6fa;
    .day_box {
      padding-top: 22px;
    }
    .day_time {
      font-size: 32px;
      margin-bottom: 24px;
    }
    .item {
      display: inline-block;
      width: 346px;
      height: 456px;
      position: relative;
      margin-bottom: 10px;
      overflow: hidden;
      background-size: cover;
      background-repeat: no-repeat;
      background-position: center;
      &:not(:nth-of-type(2n)) {
        margin-right: 10px;
      }
      .check_icon {
        position: absolute;
        top: 16px;
        left: 16px;
        width: 38px;
        height: 38px;
        background: rgba(255, 255, 255, 0.62);
        border: 2px solid #ffffff;
        border-radius: 50%;
        .icon {
          display: none;
          font-size: 34px;
          margin-top: 2px;
          margin-left: 3px;
          color: #fff;
        }
        &.checked {
          background: #3074ff;
          border-color: #3074ff;
          .icon {
            display: block;
          }
        }
      }
    }
  }
  .control_panel {
    width: 100%;
    height: 168px;
    background: #fff;
    position: fixed;
    bottom: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    .control_btn,
    .cancel_btn,
    .del_btn {
      display: inline-block;
      font-size: 32px;
      color: #3074ff;
      padding: 40px;
      margin-bottom: 40px;
    }
    .del_btn {
      color: #e70000;
    }
    .cancel_btn {
      color: #999;
      margin-right: 80px;
    }
    .control_box {
      width: 100%;
      box-sizing: border-box;
      padding: 0 24px;
      display: flex;
      align-items: center;
      justify-content: space-around;
      .btn {
        width: 116px;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-wrap: wrap;
        .icon {
          font-size: 40px;
        }
        .text {
          width: 100%;
          font-size: 28px;
          margin-top: 16px;
          text-align: center;
        }
      }
      .blue_btn {
        width: 370px;
        height: 92px;
        margin-left: 80px;
      }
    }
  }
  .van-image-preview__cover {
    position: absolute;
    top: auto;
    bottom: 100px;
    left: 50%;
    transform: translateX(-50%);
    width: 360px;
    height: 80px;
  }
}
</style>
<style lang="scss">
// 长辈版
.elder {
  #MyAlbum .control_panel .control_btn,
  #MyAlbum .control_panel .cancel_btn,
  #MyAlbum .control_panel .del_btn {
    font-size: 36px;
  }
}
</style>
