<template>
  <div :class="$style.tabAvatar">
    <a-upload
      ref="upload"
      name="avatar"
      :disabled="uploadControl"
      list-type="picture-card"
      :class="$style.avatarUploader"
      :show-upload-list="false"
      :custom-request="selfUpload"
      :before-upload="beforeUpload"
      accept="image/*"
      @change="handleChange"
    >
      <div :class="$style.avatar">
        <a-avatar v-if="imageUrl !== ''" icon="user" :src="imageUrl" alt="avatar" />
        <a-avatar v-else icon="user" :src="computedSrc | sdResource" alt="avatar" />
      </div>
    </a-upload>
    <div
      :class="{
        [$style.notEditor]: uploadControl,
      }"
    >
      <span :class="$style.uploadSpan">点击可上传头像 </span>
      <span :class="$style.uploadSpan">建议图片为正方形，且大小不超过5M </span>
    </div>
  </div>
</template>

<script>
import { Modal, Message } from 'ant-design-vue'
import storeMixin from '@/common/store-mixin'
import components from './_import-components/sd-upload-avatar-import'
function getBase64(img, callback) {
  const reader = new FileReader()
  reader.addEventListener('load', () => callback(reader.result))
  reader.readAsDataURL(img) // 将文件读取为 DataURL
}
const duration = 1
export default {
  name: 'SdUploadAvatar',
  components,
  mixins: [storeMixin],
  props: {
    userinfoAccount: {
      type: String,
      default: '',
    },
    userinfoAvatar: {
      type: String,
      default: '',
    },
    recordId: {
      type: Number,
      default: null,
    },
    permission: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      loading: false,
      imageUrl: '',
    }
  },
  computed: {
    // 没照片时返回undefined  不加载头像
    computedSrc() {
      let url
      if (this.recordId) {
        url = `api/framework/v1/oa-base-address-user/userAvatar/userId/${this.recordId}`
      }
      return url
    },
    uploadControl() {
      if (this.permission) {
        return false
      } else if (this.userinfoAccount === this.userInfo.account) {
        return false
      } else {
        return true
      }
    },
  },
  methods: {
    handleChange(info) {
      this.loading = true
      // 上传头像
      if (info.file.status === 'uploading') {
        this.loading = true
        return
      }
      if (info.file.status === 'done') {
        getBase64(info.file.originFileObj, (imageUrl) => {
          this.imageUrl = imageUrl
          this.loading = false
        })
      }
    },
    beforeUpload(file) {
      // 上传前头像校验
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        Modal.warning({
          title: '提示',
          content: '请上传不超过5M的jpg或png格式的图片!',
        })
        return false
      }
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isLt5M) {
        Modal.warning({
          title: '提示',
          content: '请上传不超过5M的jpg或png格式的图片!',
        })
        return false
      }
      return isJpgOrPng && isLt5M
    },
    // 保存头像
    submitForm() {
      const key = Symbol.for()
      if (this.imageUrl === '') {
        if (this.userinfoAvatar) {
          Message.warn({ content: '当前图像并未改变', key, duration })
        } else {
          Message.warn({ content: '当前图像并未上传图像', key, duration })
        }
        return
      }

      const index = this.imageUrl.indexOf('base64,')
      const filestr = this.imageUrl.substring(index + 7) // 图片base64编码
      const param = {
        fileStr: filestr,
        userAccount: this.recordId,
      }
      this.$emit('uploadAvatar', param)
    },
    selfUpload({ action, file, onSuccess, onError, onProgress }) {
      const base64 = new Promise((resolve) => {
        const fileReader = new FileReader()
        fileReader.readAsDataURL(file)
        fileReader.onload = () => {
          resolve(fileReader.result)
          this.imageUrl = fileReader.result
          this.submitForm()
        }
      })
      return base64
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.tab-avatar {
  text-align: center;
  .upload-span {
    display: block;
  }
  .avatar-uploader {
    :global(.ant-upload) {
      display: inline-table;
      display: flex;
      align-content: center;
      justify-content: center;
      float: none;
      width: 200px;
      height: 200px;
      margin: auto;
      overflow: hidden;
      border: none;
      border-radius: 50%;
    }
    :global(.ant-avatar.ant-avatar-icon) {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 100%;
      img {
        /* object-fit: none; */
      }
    }

    .avatar {
      display: flex;
      align-items: center;
      justify-content: center;
      img {
        display: block;
        width: 100%;
      }
    }
    $avatar-icon-size: 200px;
    :global(.anticon.anticon-user) {
      font-size: $avatar-icon-size;
    }
  }
  .not-editor {
    display: none;
  }
}
.btnsubmit {
  margin-top: $list-item-meta-margin-bottom;
}
</style>
