<template>
  <div class="plg-avatar-upload">
    <a-dropdown :placement="'bottomLeft'" style="display: inline-block; vertical-align: top" :trigger="trigger">
      <a-avatar class="user-avatar-active" :size="size" :shape="shape" :src="imgSrc" :icon="icon" />
      <a-input type="hidden" :value="sateValue" />
      <div slot="overlay" refs="menu" class="user-avatar-list" :style="'max-width:460px'">
        <a-row type="flex" :gutter="10">
          <a-col class="user-avatar-item" v-for="(item, index) in srcData" :key="index">
            <a-avatar
              :shape="shape"
              :class="count === index ? 'user-avatar-active' : ''"
              @click="handleClick(index)"
              :src="!isNaN(item) ? getImagesFile(item) : item"
              :size="size"
            />
          </a-col>
        </a-row>
      </div>
    </a-dropdown>
    <a-upload
      v-if="upload"
      v-bind="sateUpload"
      accept=".png,.jpg,.gif,.svg"
      :beforeUpload="uploadFile"
      :class="shape"
      class="avatar-uploader"
      name="file"
      :style="{ width: size + 'px', height: size + 'px' }"
      listType="picture-card"
      :showUploadList="false"
    >
      <a-icon :type="loading ? 'loading' : 'plus'" />
      <div class="ant-upload-text">图片</div>
    </a-upload>
  </div>
</template>
<script>
export default {
  name: 'plgAvatarUpload',
  props: {
    trigger: String,
    options: {
      type: Array,
      default() {
        return []
      },
    },
    directoryId: {
      type: Number,
      default: 6,
    },
    getImagesFile: {
      type: Function,
      default: undefined,
    },
    upload: {
      type: Boolean | Object,
      default() {
        return false
      },
    },
    uploadFilePath: {
      type: String,
    },
    size: {
      type: Number,
      default: 64,
    },
    localPath: {
      default: '',
    },
    shape: {
      type: String,
      default: 'circle',
    },
    icon: {
      default: 'picture',
    },
    actionIndex: {
      type: Number,
      default() {
        return 0
      },
    },
    value: String,
    remoteData: Object,
  },
  data() {
    const options = this.options

    const count = Math.floor(Math.random() * options.length)
    return {
      count,
      sateValue: '',
      loading: false,
      file: [],
      imageList: options,
    }
  },

  computed: {
    sateUpload() {
      let ops = {
        name: 'file',
        multiple: false,
        showUploadList: false,
        url: this.uploadFilePath,
      }
      let _self = this.$props.upload
      if (_self && typeof _self === 'object') {
        return { ...ops, ..._self }
      } else if (_self && typeof _self === 'boolean') {
        return ops
      }
      return {}
    },
    srcData() {
      if (this.imageList.length > 0) {
        //   let _p = this.localPath && this.localPath.charAt(this.localPath.length - 1) === '/' ? '' : '/';
        return this.imageList.map((item) => {
          let path = this.localPath
          // if (item.indexOf(this.localPath) > 0) {
          //   path = ".."
          // }
          /**判断本地图片路径 */
          if (isNaN(item) && item.indexOf('//') == -1) {
            return `${path}${item}`
          } else {
            return item
          }
        }, this)
      }
    },
    imgSrc() {
      if (!this.sateValue) return ''
      let i = this.srcData.indexOf(this.sateValue)
      if (i > -1) {
        this.count = i
      } else {
        this.imageList = [...[this.sateValue], ...this.imageList]
        this.imageList = Array.from(new Set(this.imageList))
        this.count = 0
      }
      if (!isNaN(this.sateValue)) {
        /**压入id去重 */
        return this.getImagesFile(this.sateValue)
      } else {
        return this.sateValue
      }
    },
  },
  watch: {
    value(val = '') {
      if (!val || this.sateValue == val) return
      this.sateValue = val
    },
  },
  mounted() {
    var _this = this

    // this.imageList = options;
    this.sateValue = this.srcData[this.count]
  },
  methods: {
    handleClick(intex) {
      this.count = intex
      this.sateValue = this.srcData[this.count]
      this.$emit('change', this.sateValue, this.count)
    },

    uploadFile(file = {}) {
      let _this = this
      let fieldsValue = {
        directoryId: this.directoryId,
        storageType: 0,
        file,
        ...this.remoteData,
      }
      let params = new FormData()
      Object.keys(fieldsValue).forEach((key) => {
        params.append(key, fieldsValue[key])
      })

      this.loading = true
      this.axios({
        url: this.sateUpload.url,
        method: 'post',
        data: params,
        processData: false, // 告诉axios不要去处理发送的数据(重要参数)
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      })
        .then((response) => {
          if (response.success) {
            _this.sateValue = response.data //id
            _this.count = 0
            _this.$emit('change', _this.sateValue, _this.count)
          }
          _this.loading = false
        })
        .catch((error) => {
          _this.loading = false
          console.err(error)
          _this.$message.error('服务器上传错误')
        })
      return false
    },
  },
}
</script>
<style lang='less'>
.plg-avatar-upload {
  .avatar-uploader {
    margin-left: 10px;
    &.circle {
      .ant-upload.ant-upload-select-picture-card {
        border-radius: 50%;
      }
    }
    .ant-upload.ant-upload-select-picture-card {
      width: inherit;
      height: inherit;
      margin: 0;
    }
  }
}

.user-avatar {
  &-list {
    background-color: #fff;
    background-clip: padding-box;
    border-radius: 2px;
    // margin-top: 10px;
    max-width: 480px;
    position: relative;
    padding-left: 10px;
    padding-top: 10px;

    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  }
  &-item {
    cursor: pointer;
    margin-bottom: 10px;
  }

  &-active {
    i {
      opacity: 0.4;
    }
    cursor: pointer;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.15);

    display: block;
    position: relative;
    &:after {
      background: url('./check.png');
      content: '';
      position: absolute;
      bottom: 0;
      z-index: 2;
      width: 12px;
      height: 12px;
      background-size: 100%;
      right: 0;
    }
    &:before {
      content: '';
      position: absolute;
      width: 40px;
      height: 40px;
      background: red;
      right: -25px;
      bottom: -25px;
      transform: rotate(45deg);
      z-index: 1;
    }
  }
}
</style>