import { NButton, NGi, NGrid, NSpace } from 'naive-ui'
import { defineComponent, nextTick, onMounted, reactive, ref } from 'vue'
import Cropper from 'cropperjs'
import 'cropperjs/dist/cropper.css'

export default defineComponent({
  name: 'copper',
  emits: ['close', 'cropperNo', 'cropperOk'],
  setup(props, { slots, attrs, emit, expose }) {
    const state = reactive({
      visible: false,
      img: null,
      confirmLoading: false,
      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: {},
      url: {
        upload: '/sys/common/saveToImgByStr'
      },
      myCropper: null as any
    })
    const imgCropper = ref()

    const edit = (record: any) => {
      const { options } = state
      state.visible = true
      state.options = Object.assign({}, options, record)

      nextTick(() => {
        initImgCropper()
      })
    }

    const initImgCropper = () => {
      state.myCropper = new Cropper(imgCropper.value, {
        viewMode: 1, //定义裁剪器的视图模式。如果将viewMode设置为0，则裁剪框可以延伸到画布外部，而值为1、2或3将限制裁剪框的大小为画布的大小。viewMode为2或3会将画布限制为容器。请注意，如果画布和容器的比例相同，则2和3之间没有差别。
        dragMode: 'move', //定义的拖动模式裁剪器.canvas和容器一样，2和3没有区别。move:移动画布 crop:创建新的裁剪框（默认） none:什么也不做
        //定义裁剪框的固定纵横比。默认情况下，裁剪框为自由比率。
        aspectRatio: state.options.autoCropWidth / state.options.autoCropHeight,
        initialAspectRatio: 1,
        autoCropArea: 1, //定义0到1之间的fA编号。定义自动裁剪区域大小（百分比）。默认0.8
        cropBoxMovable: true, //允许通过拖动移动裁剪框。默认true
        cropBoxResizable: false, //以通过拖动来调整裁剪框的大小 默认true
        background: true, //显示容器的网格背景
        movable: true, //移动图像
        modal: true,
        preview: '.before'
      })
    }

    const onOperation = (type: string) => {
      switch (type) {
        case 'left':
          state.myCropper.rotate(90)
          break
        case 'right':
          state.myCropper.rotate(-90)
          break
        case 'zoomIn':
          state.myCropper.zoom(0.1)
          break
        case 'zoomOut':
          state.myCropper.zoom(-0.1)
          break
      }
    }

    const onSubmit = () => {
      state.confirmLoading = true
      state.myCropper
        .getCroppedCanvas({
          imageSmoothingQuality: 'high'
        })
        .toBlob((blob: any) => {
          emit('cropperOk', blob)
          state.confirmLoading = false
        })
    }

    expose({
      edit
    })
    return () => (
      <div>
        <NGrid cols={2} xGap={24} style={{ paddingTop: '12px' }}>
          <NGi>
            <div style="width: 100%; height: 300px">
              <img ref={imgCropper} id="myImages" src={state.options.img} alt="" />
            </div>

            <NSpace justify="end" style={{ paddingTop: '12px' }}>
              <NButton type="primary" size="small" onClick={() => onOperation('left')}>
                逆时针旋转
              </NButton>
              <NButton type="primary" size="small" onClick={() => onOperation('right')}>
                顺时针旋转
              </NButton>
              <NButton type="primary" size="small" onClick={() => onOperation('zoomIn')}>
                放大
              </NButton>
              <NButton type="primary" size="small" onClick={() => onOperation('zoomOut')}>
                缩小
              </NButton>
            </NSpace>
          </NGi>
          <NGi>
            {/* font-weight: 600; padding-bottom: 8px; display: inline-block; */}
            <span
              style={{
                fontSize: '15px',
                fontWeight: 600,
                paddingBottom: '8px',
                display: 'inline-block'
              }}
            >
              预览图片
            </span>
            <div
              class="before"
              style={{
                width: state.options.autoCropWidth + 'px',
                height: state.options.autoCropHeight + 'px',
                overflow: 'hidden'
              }}
            ></div>
          </NGi>
        </NGrid>
        <NSpace justify="end">
          <NButton
            type="default"
            onClick={() => {
              state.confirmLoading = false
              emit('close')
              emit('cropperNo')
            }}
          >
            取消
          </NButton>
          <NButton type="primary" loading={state.confirmLoading} onClick={onSubmit}>
            确认
          </NButton>
        </NSpace>
      </div>
    )
  }
})
