import { defineComponent } from 'vue'
import styles from './index.module.less'
import { VueCropper } from 'vue-cropper'
import umiRequest from 'umi-request'
import 'vue-cropper/dist/index.css'
import {
  ElButton,
  ElCol,
  ElDialog,
  ElIcon,
  ElImage,
  ElMessage,
  ElRow
} from 'element-plus'
import { CirclePlus, Remove } from '@element-plus/icons-vue'
import iconRate from '../col-upload/images/icon_rate.png'
import request from '@/helpers/request'

import Cropper from 'cropperjs'
import 'cropperjs/dist/cropper.css'
import { getUploadSign, onOnlyFileUpload } from '@/helpers/oss-file-upload'
export default defineComponent({
  name: 'cropper',
  props: {
    cropperNo: {
      type: Function,
      default: (data: any) => {}
    },
    cropperOk: {
      type: Function,
      default: (data: any) => {}
    },
    bucket: {
      type: String,
      default: 'daya'
    }
  },
  data() {
    return {
      // ossUploadUrl: 'https://ks3-cn-beijing.ksyuncs.com/' + this.bucket,
      ossUploadUrl: `https://${this.bucket}.ks3-cn-beijing.ksyuncs.com/`,
      dataObj: {
        policy: '',
        signature: '',
        key: '',
        KSSAccessKeyId: '',
        acl: 'public-read',
        name: ''
      },
      visible: false,
      img: null,
      options: {
        img: '', //裁剪图片的地址
        autoCrop: true, //是否默认生成截图框
        autoCropWidth: 180, //默认生成截图框宽度
        autoCropHeight: 180, //默认生成截图框高度
        fixedBox: true, //是否固定截图框大小 不允许改变
        full: false,
        enlarge: 1, // 是否按照截图框比例输出 默认为1
        previewsCircle: true, //预览图是否是原圆形
        centerBox: true,
        outputType: 'png',
        title: '修改头像',
        name: null // 文件名称
      },
      previews: {} as any,
      url: {
        upload: '/sys/common/saveToImgByStr'
      },
      submitLoading: false,
      myCropper: null as any
    }
  },
  methods: {
    edit(record: any) {
      const { options } = this
      this.visible = true
      this.options = Object.assign({}, options, record)
      console.log(this.options)
    },
    /**
     * 取消截图
     */
    cancelHandel() {
      this.visible = false
      this.cropperNo()
    },
    /**
     * 确认截图
     */
    okHandel() {
      ;(this as any).myCropper
        .getCroppedCanvas({
          imageSmoothingQuality: 'high'
        })
        .toBlob(async data => {
          this.submitLoading = true
          const options: any = this.options
          const fileName =
            (options.name ? options.name.split('.')[0] : +new Date()) + '.png'
          try {
            const key = new Date().getTime() + fileName
            const obj = {
              filename: key,
              bucketName: this.bucket,
              postData: {
                filename: key,
                acl: 'public-read',
                key: key
              }
            }
            // const res = await request.post('/api-website/getUploadSign', {
            //   data: obj
            // })
            const res = await getUploadSign(obj)
            this.dataObj = {
              policy: res.data.policy,
              signature: res.data.signature,
              key: key,
              KSSAccessKeyId: res.data.kssAccessKeyId,
              acl: 'public-read',
              name: key
            }

            const uploadUrl = await onOnlyFileUpload(this.ossUploadUrl, {
              ...this.dataObj,
              file: data
            })
            // const formData = new FormData()
            // for (const key in this.dataObj) {
            //   formData.append(key, this.dataObj[key])
            // }
            // // this.blobToFile(data, fileName)
            // formData.append('file', data, fileName)
            // await umiRequest(this.ossUploadUrl, {
            //   method: 'POST',
            //   data: formData
            // })
            // console.log(this.ossUploadUrl + key)
            // const uploadUrl = this.ossUploadUrl + key
            this.cropperOk(uploadUrl)
          } catch (err: any) {
            ElMessage.error(err)
          } finally {
            this.submitLoading = false
            this.cancelHandel()
          }
        })
    },
    //转成blob
    blobToFile(Blob: any, fileName: any) {
      //兼容IE
      Blob.lastModifiedDate = new Date()
      Blob.name = fileName
      return Blob
    },
    base64ToFile(urlData: any, fileName: any) {
      const arr = urlData.split(',')
      const mime = arr[0].match(/:(.*?);/)[1]
      const bytes = atob(arr[1]) // 解码base64
      let n = bytes.length
      const ia = new Uint8Array(n)
      while (n--) {
        ia[n] = bytes.charCodeAt(n)
      }
      return new File([ia], fileName, { type: mime })
    },
    //移动框的事件
    realTime(data: any) {
      this.previews = data
    },
    //图片缩放
    changeScale(num: number) {
      num = num || 1
      ;(this as any).$refs.cropperRef.changeScale(num)
    },
    //向左旋转
    rotateLeft() {
      ;(this as any).$refs.cropperRef.rotateLeft()
    },
    //向右旋转
    rotateRight() {
      ;(this as any).$refs.cropperRef.rotateRight()
    },
    initImgCropper() {
      this.myCropper = new Cropper((this as any).$refs.imgCropper, {
        viewMode: 1, //定义裁剪器的视图模式。如果将viewMode设置为0，则裁剪框可以延伸到画布外部，而值为1、2或3将限制裁剪框的大小为画布的大小。viewMode为2或3会将画布限制为容器。请注意，如果画布和容器的比例相同，则2和3之间没有差别。
        dragMode: 'move', //定义的拖动模式裁剪器.canvas和容器一样，2和3没有区别。move:移动画布 crop:创建新的裁剪框（默认） none:什么也不做
        //定义裁剪框的固定纵横比。默认情况下，裁剪框为自由比率。
        aspectRatio: this.options.autoCropWidth / this.options.autoCropHeight,
        initialAspectRatio: 1,
        autoCropArea: 1, //定义0到1之间的fA编号。定义自动裁剪区域大小（百分比）。默认0.8
        cropBoxMovable: true, //允许通过拖动移动裁剪框。默认true
        cropBoxResizable: false, //以通过拖动来调整裁剪框的大小 默认true
        background: false, //显示容器的网格背景
        movable: true, //移动图像
        modal: true,
        preview: '.before'
      })
    }
  },
  render() {
    return (
      <ElDialog
        modelValue={this.visible}
        onUpdate:modelValue={val => (this.visible = val)}
        appendToBody
        title={this.options.title}
        closeOnClickModal={false}
        width={'900px'}
        destroyOnClose={true}
        onOpened={() => {
          this.initImgCropper()
        }}
        v-slots={{
          footer: () => (
            <span class="dialog-footer !text-center block">
              <ElButton
                onClick={this.cancelHandel}
                disabled={this.submitLoading}
              >
                取消
              </ElButton>
              <ElButton
                type="primary"
                onClick={this.okHandel}
                loading={this.submitLoading}
              >
                保 存
              </ElButton>
            </span>
          )
        }}
      >
        <ElRow>
          <ElCol xs={24} md={12} style={{ width: '350px' }}>
            <div class={styles.imgwarp}>
              <img
                ref="imgCropper"
                id="myImages"
                src={this.options.img}
                alt=""
                style={{ height: '350px' }}
              />
            </div>
            {/* <VueCropper
              ref="cropperRef"
              img={this.options.img}
              info={true}
              autoCrop={true}
              centerBox={false}
              autoCropWidth={this.options.autoCropWidth}
              full={this.options.full}
              outputType={this.options.outputType}
              autoCropHeight={this.options.autoCropHeight}
              fixedBox={this.options.fixedBox}
              enlarge={this.options.enlarge}
              onRealTime={this.realTime}
              style={{ height: '350px' }}
            /> */}
            {/* <div class="flex pt-2">
              <div
                onClick={() => {
                  this.changeScale(1)
                }}
                class="mr-2 cursor-pointer"
                title="放大"
              >
                <ElIcon size={30} color="#333">
                  <CirclePlus />
                </ElIcon>
              </div>
              <div
                onClick={() => {
                  this.changeScale(-1)
                }}
                class="mr-2 cursor-pointer"
                title="缩小"
              >
                <ElIcon size={30} color="#333">
                  <Remove />
                </ElIcon>
              </div>
              <div
                onClick={this.rotateRight}
                title="向右旋转"
                class="cursor-pointer"
              >
                <img src={iconRate} class="w-[30px] h-[30px]" />
              </div>
            </div> */}
          </ElCol>
          <ElCol xs={24} md={12} style={{ height: '350px' }}>
            <div class={styles.previewImg}>
              <span>预览图片</span>
              <div
                class={[
                  this.options.previewsCircle
                    ? styles['avatar-upload-preview']
                    : styles['avatar-upload-preview_range'],
                  'before'
                ]}
                style={{
                  width: this.options.autoCropWidth + 'px',
                  height: this.options.autoCropHeight + 'px'
                }}
              >
                {/* <ElImage src={this.previews.url} style={this.previews.img} /> */}
              </div>
            </div>
          </ElCol>
        </ElRow>
      </ElDialog>
    )
  }
})
