<template>
  <div class="ai-uploader">
    <div class="imgs flex-align">
      <div class="img" v-for="(item, index) in fileList" :key="index">
        <image :src="item.url" hover-class="text-hover" @click="prev(index)" class="image" />
        <!-- <i class="iconfont" @click="remove(index)">&#xe6b3;</i> -->
        <img src="https://cdn.cunwuyun.cn/dvcp/upload/del-icon.png" alt="" class="del-icon" @click="remove(index)"/>
      </div>
      <div class="upload" @click="upload" v-if="fileList.length < limit">
        <!-- <i class="iconfont">&#xe6b2;</i> -->
        <img src="https://cdn.cunwuyun.cn/dvcp/upload/add-icon.png" alt="" class="add-icon"/>
        <span>添加照片</span>
      </div>
    </div>
  </div>
</template>

<script>
import axios from '@/utils/axios.js'

export default {
  name: 'AiUploader',

  model: {
    event: 'input',
    prop: 'value',
  },

  props: {
    limit: {
      type: Number,
      default: 1,
    },

    type: {
      type: 'img',
    },

    value: {
      type: Array,
      default: () => [],
    },
  },

  watch: {
    value: {
      handler(val) {
        if (val) {
          this.fileList = [...val]
        }
      },
      immediate: true,
      deep: true,
    },
  },

  data() {
    return {
      fileList: [],
      hideStatus: false,
    }
  },

  methods: {
    remove(index) {
      this.fileList.splice(index, 1)

      this.$nextTick(() => {
        this.$emit('input', [...this.fileList])
        this.$emit('change', [...this.fileList])
      })
    },

    prev(index) {
      uni.previewImage({
        current: this.fileList[index].url,
        urls: this.fileList.map((v) => v.url),
      })
    },

    upload() {
      uni.chooseImage({
        count: this.limit,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          if (this.fileList.length + res.tempFilePaths.length > this.limit && this.limit !== 1) {
            this.$toast(`图片不能超过${this.limit}张`)

            return false
          }

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

    uploadFile(img) {
      uni.uploadFile({
        url: axios.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) {
            if (this.limit === 1) {
              this.fileList = [
                {
                  id: data.data[0].split(';')[1],
                  url: data.data[0].split(';')[0],
                },
              ]
            } else {
              this.fileList.push({
                id: data.data[0].split(';')[1],
                url: data.data[0].split(';')[0],
              })
            }

            this.$nextTick(() => {
              this.$emit('input', [...this.fileList])
              this.$emit('change', [...this.fileList])
            })
          } else {
            this.$toast(data.msg)
          }
        },
        complete: () => {
          if (this.hideStatus) {
            this.$hideLoading()
            this.hideStatus = false
          }
        },
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.ai-uploader {
  .del-icon {
    position: absolute;
    right: 0;
    top: 0;
    z-index: 11;
    width: 32px;
    height: 32px;
    -webkit-transform: translate(50%, -50%);
    transform: translate(50%, -50%);
  }

  .imgs {
    flex-wrap: wrap;

    div {
      position: relative;
      width: 220px;
      height: 220px;
      margin-right: 8px;
      margin-bottom: 8px;

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

      .image {
        width: 220px;
        height: 220px;
      }
    }

    .img {
      i {
        position: absolute;
        right: 0;
        top: 0;
        z-index: 11;
        font-size: 28px;
        opacity: 0.8;
        color: #f72c27;
        transform: translate(50%, -50%);
      }
    }

    .upload {
      width: 224px;
      height: 224px;
      text-align: center;
      border: 1px solid #dddddd;
      box-sizing: border-box;

      i {
        padding: 42px 0 16px;
        color: #ddd;
        font-size: 64px;
      }

      .add-icon {
        margin: 50px 0 16px;
        width: 64px;
        height: 64px;
      }

      span {
        display: block;
        text-align: center;
        color: #dddddd;
        font-size: 24px;
      }
    }
  }
}
</style>
