import { Modal } from 'ant-design-vue'
import { defineComponent, ref, watch } from 'vue'
import { VueCropper } from 'vue-cropper'
import 'vue-cropper/dist/index.css'
import upload from './upload'
import { v4 as uuid } from 'uuid'
import { MdCroprotateRound, BiPlusLg } from 'oh-vue-icons/icons'
import { OhVueIcon, addIcons } from 'oh-vue-icons'
import NativeColorPicker from './NativeColorPicker'
import useUserStore from '@/user/useUserStore'
import { globalToast } from '@/main'
import useRouterStore from '@/useRouterStore'
addIcons(MdCroprotateRound, BiPlusLg)

export default defineComponent({
  emits: {
    'update:value': (() => true) as (val: string) => boolean
  },
  setup(props, ctx) {
    const inputRef = ref<HTMLInputElement | null>(null)
    const showCutModel = ref(false)
    const originFile = ref('')
    const fillColor = ref('transparent')
    const cropper = ref<any>(null)
    const handleFile = (e: any) => {
      const target = e.target as HTMLInputElement

      const file = target.files?.[0]
      target.value = ''

      if (!file) return
      // upload(file).then(res => {
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = (e: any) => {
        originFile.value = e?.target.result // 显示原始图片
        showCutModel.value = true
      }
      //   emit('update:icon', res || '')
      // })
    }
    const handleFinish = (blob: any) => {
      // 根据前几个字节推测文件类型（这里只考虑常见的图片类型）

      // 使用 FileReader 对象读取 Blob 的前几个字节
      const reader = new FileReader()
      reader.onloadend = function () {
        // 打印 File 对象以验证

        const fileData = new File([blob], `${uuid()}.png`, {
          type: 'image/jpg',
          lastModified: Date.now()
        })
        upload(fileData, 'customIcon').then((res) => {
          showCutModel.value = false

          ctx.emit('update:value', res || '')
        })
      }
      reader.readAsArrayBuffer(blob)
    }
    watch(
      fillColor,
      (e: string) => {
        const elements = document.querySelectorAll('.cropper-crop-box')
        elements.forEach((element: any) => {
          element.style.backgroundColor = e // 修改颜色为蓝色
        })
      },
      {
        immediate: true
      }
    )
    return () => (
      <>
        <Modal
          open={showCutModel.value}
          onCancel={() => (showCutModel.value = false)}
          onOk={() => {
            cropper.value.getCropBlob((blob: any) => {
              handleFinish(blob)
            })
          }}
        >
          <div class="w-full flex flex-col items-center gap-y-2">
            <div
              class="w-[250px] h-[250px]"
              style={{
                backgroundColor: fillColor.value || 'transparent'
              }}
            >
              <VueCropper
                ref={cropper}
                autoCropWidth="250px"
                autoCropHeight="250px"
                mode="contain"
                outputType="png"
                img={originFile.value}
                autoCrop={true}
                fillColor={fillColor.value}
              />
            </div>
            <div class="flex justify-between w-[250px]">
              {/* <ArrowRotateClockwise24Regular
                                class="text-[10px] w-8 h-8 cursor-pointer"
                                onClick={() => ($refs.cropper as any).rotateRight()}
                            /> */}
              <span
                class="flex items-center cursor-pointer"
                onClick={() => {
                  cropper.value.rotateRight()
                }}
              >
                <OhVueIcon name="md-croprotate-round" scale={1} fill="#707070"></OhVueIcon>
              </span>
              <span class="flex items-center gap-x-1">
                <svg
                  onClick={() => cropper.value?.changeScale(1)}
                  class="icon cursor-pointer"
                  viewBox="0 0 1024 1024"
                  width="2rem"
                  height="2rem"
                >
                  <path
                    d="M886.51776 799.66208l-139.93984-139.93984c-10.50624-10.50624-23.90016-16.13824-37.60128-17.44896 42.16832-52.59264 67.54304-119.1936 67.54304-191.6928 0-169.39008-137.80992-307.2-307.2-307.2s-307.2 137.80992-307.2 307.2 137.80992 307.2 307.2 307.2c63.91808 0 123.31008-19.6608 172.52352-53.18656 0.34816 15.23712 6.22592 30.37184 17.85856 42.00448l139.93984 139.93984c11.9808 12.00128 27.72992 18.00192 43.43808 18.00192s31.45728-6.00064 43.43808-18.00192C910.52032 862.55616 910.52032 823.66464 886.51776 799.66208zM469.31968 655.38048c-112.92672 0-204.8-91.87328-204.8-204.8s91.87328-204.8 204.8-204.8 204.8 91.87328 204.8 204.8S582.2464 655.38048 469.31968 655.38048zM610.14016 450.58048c0 22.60992-18.35008 40.96-40.96 40.96l-56.32 0 0 56.32c0 22.60992-18.35008 40.96-40.96 40.96s-40.96-18.35008-40.96-40.96l0-56.32-56.32 0c-22.60992 0-40.96-18.35008-40.96-40.96s18.35008-40.96 40.96-40.96l56.32 0 0-56.32c0-22.60992 18.35008-40.96 40.96-40.96s40.96 18.35008 40.96 40.96l0 56.32 56.32 0C591.79008 409.62048 610.14016 427.95008 610.14016 450.58048z"
                    fill="#707070"
                  />
                </svg>
                <svg
                  onClick={() => cropper.value?.changeScale(-1)}
                  class="icon cursor-pointer"
                  viewBox="0 0 1024 1024"
                  width="2rem"
                  height="2rem"
                >
                  <path
                    d="M886.51776 799.66208l-139.93984-139.93984c-10.50624-10.50624-23.90016-16.13824-37.60128-17.44896 42.16832-52.59264 67.54304-119.1936 67.54304-191.6928 0-169.39008-137.80992-307.2-307.2-307.2s-307.2 137.80992-307.2 307.2 137.80992 307.2 307.2 307.2c63.91808 0 123.31008-19.6608 172.52352-53.18656 0.34816 15.23712 6.22592 30.37184 17.85856 42.00448l139.93984 139.93984c11.9808 12.00128 27.72992 18.00192 43.43808 18.00192s31.45728-6.00064 43.43808-18.00192C910.52032 862.55616 910.52032 823.66464 886.51776 799.66208zM469.31968 655.38048c-112.92672 0-204.8-91.87328-204.8-204.8s91.87328-204.8 204.8-204.8 204.8 91.87328 204.8 204.8S582.2464 655.38048 469.31968 655.38048zM610.14016 450.58048c0 22.60992-18.35008 40.96-40.96 40.96l-194.56 0c-22.60992 0-40.96-18.35008-40.96-40.96s18.35008-40.96 40.96-40.96l194.56 0C591.79008 409.62048 610.14016 427.95008 610.14016 450.58048z"
                    fill="#707070"
                  />
                </svg>
              </span>
            </div>
            <NativeColorPicker
              value={fillColor.value}
              onUpdate:value={(e) => (fillColor.value = e)}
              transparent={true}
            />
            {/* {props.colorList && (
                            <div class="w-[250px] flex justify-center">
                                <NativeColorPicker
                                    colorList={colorList}
                                    v-model={fillColor}
                                    onUpdate:modelValue={(e) => { }}
                                    transparent={true}
                                />
                            </div>
                        )} */}
          </div>
        </Modal>
        <div
          class="w-full h-full bg-white flex items-center justify-center"
          onClick={() => {
            if (useUserStore().isLogin) {
              inputRef.value?.click?.()
            } else {
              globalToast.warning('请先登录')
              useRouterStore().go('global-login')
            //   useAdderPageStore().type = 2
            }
          }}
        >
          <OhVueIcon name={BiPlusLg.name} fill="#666666" scale={2}></OhVueIcon>
        </div>
        <input
          ref={inputRef}
          style={{
            display: 'none'
          }}
          accept=".jpg,.jpeg,.png,.svg"
          type="file"
          onChange={handleFile}
        />
      </>
    )
  }
})
