<template>
  <a-modal
    v-model:visible="data.visible"
    title="修改头像"
    :mask-closable="false"
    :confirm-loading="data.confirmLoading"
    :width="800"
    :footer="null"
    @cancel="cancelHandel"
  >
    <a-row>
      <a-col :xs="24" :md="12" :style="{height: '350px'}">
        <vue-cropper
          ref="cropper"
          :img="data.options.img"
          :info="true"
          :auto-crop="data.options.autoCrop"
          :auto-crop-width="data.options.autoCropWidth"
          :auto-crop-height="data.options.autoCropHeight"
          :fixed-box="data.options.fixedBox"
          @realTime="realTime"
        />
      </a-col>
      <a-col :xs="24" :md="12" :style="{height: '350px'}">
        <div class="avatar-upload-preview">
          <img :src="data.previews.url" :style="data.previews.img">
        </div>
      </a-col>
    </a-row>
    <br>
    <a-row>
      <a-col :lg="2" :md="2">
        <a-upload name="file" :before-upload="beforeUpload" :show-upload-list="false">
          <a-button>
            <upload-outlined />
            选择图片
          </a-button>
        </a-upload>
      </a-col>
      <a-col :lg="{span: 1, offset: 2}" :md="2">
        <a-button icon="plus" @click="changeScale(1)" />
      </a-col>
      <a-col :lg="{span: 1, offset: 1}" :md="2">
        <a-button icon="minus" @click="changeScale(-1)" />
      </a-col>
      <a-col :lg="{span: 1, offset: 1}" :md="2">
        <a-button icon="undo" @click="rotateLeft" />
      </a-col>
      <a-col :lg="{span: 1, offset: 1}" :md="2">
        <a-button icon="redo" @click="rotateRight" />
      </a-col>
      <a-col :lg="{span: 2, offset: 6}" :md="2">
        <a-button type="primary" @click="finish('blob')">
          保存
        </a-button>
      </a-col>
    </a-row>
  </a-modal>
</template>
<script lang="ts" setup>
import { upload, $updateUserInfo } from '@/api/manage'
import {reactive,ref} from  'vue'
import {message} from 'ant-design-vue'
import {useUserStore} from '@/store/modules/user'
    const emit = defineEmits(['ok'])
    const cropper = ref()
    const data =reactive({
     recordId: useUserStore().userInfo.sysUserId, // 拿到ID
      userLoad: upload.avatar, // 图片上传地址
      visible: false,
      id: null,
      confirmLoading: false,
      fileList: [],
      uploading: false,
      options: {
        // img: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
        img:'' as any ,
        autoCrop: true,
        autoCropWidth: 200,
        autoCropHeight: 200,
        fixedBox: true
      },
      previews: {} as any
    }) 

defineExpose({edit,okHandel})
   function edit (id) {
      data.visible = true
      data.id = id
      /* 获取原始头像 */
    }
   function close () {
      data.id = null
      data.visible = false
    }
   function cancelHandel () {
     close()
    }
   function  changeScale (num) {
      num = num || 1
      cropper.value.changeScale(num)
    }
   function rotateLeft () {
     cropper.value.rotateLeft()
    }
   function rotateRight () {
     cropper.value.rotateRight()
    }
   function beforeUpload (file) {
      const reader = new FileReader()
      // 把Array Buffer转化为blob 如果是base64不需要
      // 转化为base64
      reader.readAsDataURL(file)
      reader.onload = () => {
        data.options.img = reader.result
      }
      // 转化为blob
      // reader.readAsArrayBuffer(file)

      return false
    }

    // 上传图片（点击上传按钮）
  function  finish (type) {
      console.log('finish')
     
      // 创建一个空对象
      const reqData:any ={}
      // 输出
      if (type === 'blob') {
       cropper.value.getCropBlob((data) => {
          // 通过该方法可以获取当前文件的一个内存URL
          const img = window.URL.createObjectURL(data)
          data.model = true
          data.modelSrc = img
          reqData.avatarUrl = img
          // this.$http.post('https://www.mocky.io/v2/5cc8019d300000980a055e76', reqData, { contentType: false, processData: false, headers: { 'Content-Type': 'application/x-www-form-urlencoded' } })
          $updateUserInfo(reqData).then((response) => {
              message.success('上传成功')
              emit('ok', response.url)
              data.visible = false
            }).catch(err => {
             
            })
            console.log(data.userLoad, data.recordId, data.modelSrc)
        })
      } else {
        cropper.value.getCropData((data) => {
          data.model = true
          data.modelSrc = data
        })
      }
    }
   function okHandel () {

      data.confirmLoading = true
      setTimeout(() => {
        data.confirmLoading = false
        close()
        message.success('上传头像成功')
      }, 2000)
    }

    function realTime (data) {
      data.previews = data
    }

</script>

<style lang="less" scoped>

  .avatar-upload-preview {
    position: absolute;
    top: 50%;
    transform: translate(50%, -50%);
    width: 180px;
    height: 180px;
    border-radius: 50%;
    box-shadow: 0 0 4px #ccc;
    overflow: hidden;

    img {
      width: 100%;
      height: 100%;
    }
  }
</style>
