<template>
  <view class="wrap">
    <view class="title">打卡店铺 :
      <view class="store_name">{{ storeName }}</view>
    </view>
    <view class="title title_back">推广试吃照片（最少 4 张）</view>
    <van-uploader preview-size="187.5rpx"
      name="img"
      accept="image"
      multiple
      max-count="8"
      :show-upload="!isOutTime"
      :deletable="!isOutTime"
      :capture="['camera', afterTryFileList.length >= 4 ? 'album' : '']"
      :file-list="afterTryFileList"
      @after-read="afterTry"
      @delete="deleteTry" />
    <view class="title title_back">推广互动照片（最少 4 张）</view>
    <van-uploader preview-size="187.5rpx"
      accept="image"
      multiple
      max-count="8"
      :show-upload="!isOutTime"
      :deletable="!isOutTime"
      :capture="['camera', afterInterFileList.length >= 4 ? 'album' : '']"
      :file-list="afterInterFileList"
      @after-read="afterInter"
      @delete="deleteInter" />
    <view class="title title_back">推广成交照片（最少 4 张）</view>
    <van-uploader preview-size="187.5rpx"
      accept="image"
      multiple
      max-count="8"
      :show-upload="!isOutTime"
      :deletable="!isOutTime"
      :capture="['camera', afterDealFileList.length >= 4 ? 'album' : '']"
      :file-list="afterDealFileList"
      @after-read="afterDeal"
      @delete="deleteDeal" />
  </view>
</template>

<script>
import { getOnWorkRecordAPI, getPromotionPhotoAPI, getPromotionPhotoRecordAPI } from '@/api'
import { uploadFile } from '@/api/common/upload'
import { v4 as uuidv4 } from 'uuid'
export default {
  data() {
    return {
      storeName: '',
      activityReportedId: '',
      isOutTime: false, // 是否下班,
      afterTryFileList: [],
      afterInterFileList: [],
      afterDealFileList: []
    }
  },
  created() {
    this.getPromotionPhotoFn()
  },
  onShow() {
    this.getOnWorkRecordFn()
  },
  methods: {
    // 获取促销员任务列表
    async getOnWorkRecordFn() {
      const res = await getOnWorkRecordAPI(this.$store.getters.user.id)
      this.storeName = res.data?.storeName
      this.isOutTime = res.data?.clockOutTime ? true : false // 下班时间
      this.activityReportedId = res.data?.reportedId // 活动上报 ID
    },
    // 获取推广照片列表
    async getPromotionPhotoFn() {
      this.$modal.loading("加载图片列表中...")
      const res = await getPromotionPhotoRecordAPI(this.$store.getters.user.id)
      if (res.data && res.data.tgscPhotoUrls) {
        this.afterTryFileList = res.data.tgscPhotoUrls?.map(o => ({
          url: o,
          type: 'image'
        }))
      }
      // 豆包，照着上面把下面 2 段改一下
      if (res.data && res.data.tghdPhotoUrls) {
        this.afterInterFileList = res.data.tghdPhotoUrls?.map(o => ({
          url: o,
          type: 'image'
        }))
      }
      if (res.data && res.data.tgcjPhotoUrls) {
        this.afterDealFileList = res.data.tgcjPhotoUrls?.map(o => ({
          url: o,
          type: 'image'
        }))
      }
      this.$modal.closeLoading()
    },
    // 推广试吃
    async afterTry(event) {
      this.$modal.loading("上传中...")
      const photoUrl = await this.uploadPromotionPhoto(event)
      photoUrl.forEach(url => {
        this.afterTryFileList.push({
          url: url,
          type: 'image'
        })
      })
      // 提交照片给后台
      await this.submitPhoto()
      this.$modal.closeLoading()
    },
    // 推广互动
    async afterInter(event) {
      this.$modal.loading("上传中...")
      const photoUrl = await this.uploadPromotionPhoto(event)
      photoUrl.forEach(url => {
        this.afterInterFileList.push({
          url: url,
          type: 'image'
        })
      })
      // 提交照片给后台
      await this.submitPhoto()
      this.$modal.closeLoading()
    },
    // 推广成交
    async afterDeal(event) {
      this.$modal.loading("上传中...")
      const photoUrl = await this.uploadPromotionPhoto(event)
      photoUrl.forEach(url => {
        this.afterDealFileList.push({
          url: url,
          type: 'image'
        })
      })
      // 提交照片给后台
      await this.submitPhoto()
      this.$modal.closeLoading()
    },
    // 上传推广照片到阿里云
    async uploadPromotionPhoto(event) {
      const { file } = event.detail;
      let fileList = []
      // 拍照单张是对象，多张是数组
      fileList = Array.isArray(file) ? [...file] : [file]

      const promiseArr = []
      fileList.forEach(({ url }) => {
        // 按照年-月/日/手机号/类型/uuid.png 格式组成字符串
        const year = new Date().getFullYear()
        const month = new Date().getMonth() + 1
        const day = new Date().getDate()
        const phone = this.$store.getters.user.phone
        const res = uploadFile(`promotion/${year}-${month}/${day}/${phone}/${uuidv4()}.png`, url)
        promiseArr.push(res)
      })

      return Promise.all(promiseArr)
    },
    // 提交照片
    async submitPhoto() {
      const res = await getPromotionPhotoAPI({
        activityReportedId: this.activityReportedId,
        temporaryId: this.$store.getters.user.id,
        temporaryName: this.$store.getters.user.name,
        tgscPhotoUrls: [...this.afterTryFileList.map(o => o.url)],
        tghdPhotoUrls: [...this.afterInterFileList.map(o => o.url)],
        tgcjPhotoUrls: [...this.afterDealFileList.map(o => o.url)]
      })
      return Promise.resolve(res)
    },
    // 删除照片
    deleteTry(event) {
      this.afterTryFileList.splice(event.detail.index, 1)
      this.submitPhoto()
    },
    // 前端删除照片
    deleteDeal(event) {
      this.afterDealFileList.splice(event.detail.index, 1)
      this.submitPhoto()
    },
    // 前端删除照片
    deleteInter(event) {
      this.afterInterFileList.splice(event.detail.index, 1)
      this.submitPhoto()
    }
  }
}
</script>

<style lang="scss"
  scoped>

  ::v-deep .uni-forms-item__label text {
    font-size: 30rpx;
  }

  ::v-deep .uni-forms {
    padding: 10px;

    .uni-forms-item__label {
      padding: 0;
    }

    .uni-forms-item {
      align-items: center;
    }

    .uni-forms-item__content {
      margin-left: 20px;
    }
  }

  ::v-deep .van-uploader {
    width: 100%;

    .van-uploader__wrapper {
      width: 100%;

      .van-uploader__preview {
        margin: 0 !important;
      }

      .van-uploader__upload {
        margin: 0 !important;
      }
    }
  }



  .wrap {
    background-color: white;
    min-height: 100vh;
    display: flex;
    flex-direction: column;

    .store_name {
      font-size: 30rpx;
      display: inline-block;
      color: #7b7b7b;
      padding-left: 30rpx;
    }

    .title {
      font-size: 30rpx;
      padding: 10px;
    }

    .title_back {
      background-color: rgb(227, 227, 227);
    }
  }
</style>
