<template>
  <basicModal
    ref="modalRef"
    class="cropperModal"
    @register="modalRegister"
    @ok="handleOk"
    @cancel="handleClose"
  >
    <template #default>
      <div class="cropper-box">
        <div class="cropper-box-left">
          <div class="cropper-box-left-cropper">
            <CropperImage
              v-if="src"
              :circled="circled"
              :src="src"
              height="300px"
              @cropend="handleCropend"
              @ready="handleReady"
            />
          </div>
          <div class="cropper-box-left-toolbar">
            <a-upload
              :showUploadList="false"
              accept="image/*"
              :before-upload="beforeUpload"
              :customRequest="customRequest"
            >
              <a-tooltip placement="bottom" trigger="hover">
                <template #title> 上传图片 </template>
                <a-button size="small" type="primary">
                  <template #icon>
                    <UploadOutlined />
                  </template>
                </a-button>
              </a-tooltip>
            </a-upload>
            <a-space>
              <a-tooltip placement="bottom" trigger="hover">
                <template #title> 重置 </template>
                <a-button
                  :disabled="!src"
                  size="small"
                  type="primary"
                  @click="handlerToolbar('reset')"
                >
                  <template #icon>
                    <ReloadOutlined />
                  </template>
                </a-button>
              </a-tooltip>
              <a-tooltip placement="bottom" trigger="hover">
                <template #title> 逆时针旋转 </template>
                <a-button
                  :disabled="!src"
                  size="small"
                  type="primary"
                  @click="handlerToolbar('rotate', -45)"
                >
                  <template #icon>
                    <RotateLeftOutlined />
                  </template>
                </a-button>
              </a-tooltip>
              <a-tooltip placement="bottom" trigger="hover">
                <template #title> 顺时针旋转 </template>
                <a-button
                  :disabled="!src"
                  size="small"
                  type="primary"
                  @click="handlerToolbar('rotate', 45)"
                >
                  <template #icon>
                    <RotateRightOutlined />
                  </template>
                </a-button>
              </a-tooltip>
              <a-tooltip placement="bottom" trigger="hover">
                <template #title> 水平翻转 </template>
                <a-button
                  :disabled="!src"
                  size="small"
                  type="primary"
                  @click="handlerToolbar('scaleX')"
                >
                  <template #icon>
                    <SwapOutlined />
                  </template>
                </a-button>
              </a-tooltip>
              <a-tooltip placement="bottom" trigger="hover">
                <template #title> 垂直翻转 </template>
                <a-button
                  :disabled="!src"
                  size="small"
                  type="primary"
                  @click="handlerToolbar('scaleY')"
                >
                  <template #icon>
                    <VerticalAlignMiddleOutlined />
                  </template>
                </a-button>
              </a-tooltip>
              <a-tooltip placement="bottom" trigger="hover">
                <template #title> 放大 </template>
                <a-button
                  :disabled="!src"
                  size="small"
                  type="primary"
                  @click="handlerToolbar('zoom', 0.1)"
                >
                  <template #icon>
                    <ZoomInOutlined />
                  </template>
                </a-button>
              </a-tooltip>
              <a-tooltip placement="bottom" trigger="hover">
                <template #title> 缩小 </template>
                <a-button
                  :disabled="!src"
                  size="small"
                  type="primary"
                  @click="handlerToolbar('zoom', -0.1)"
                >
                  <template #icon>
                    <ZoomOutOutlined />
                  </template>
                </a-button>
              </a-tooltip>
            </a-space>
          </div>
        </div>
        <div class="cropper-box-right">
          <div
            :class="{ 'cropper-box-right-preview-radius': circled }"
            class="cropper-box-right-preview"
          >
            <img v-if="previewSource" :src="previewSource" />
          </div>
          <template v-if="previewSource">
            <div class="cropper-box-right-group">
              <a-avatar :src="previewSource" size="large" />
              <a-avatar :size="48" :src="previewSource" />
              <a-avatar :size="64" :src="previewSource" />
              <a-avatar :size="80" :src="previewSource" />
            </div>
          </template>
        </div>
      </div>
    </template>
  </basicModal>
</template>

<script lang="ts" setup>
  import type { CropendResult, Cropper } from './typing';
  import { ref } from 'vue';
  import { message } from 'ant-design-vue';
  import { basicModal, useModal } from '@/components/Modal';
  import type { UploadProps } from 'ant-design-vue';
  import CropperImage from './CropperImage.vue';
  import { dataURLtoBlob, base64ToFile } from '@/utils/file/base64Conver';
  import { isFunction } from '@/utils/is';
  import { getOssConfig } from '@/api/common';
  import OSS from 'ali-oss';
  import {
    UploadOutlined,
    ReloadOutlined,
    RotateLeftOutlined,
    RotateRightOutlined,
    SwapOutlined,
    VerticalAlignMiddleOutlined,
    ZoomInOutlined,
    ZoomOutOutlined,
  } from '@ant-design/icons-vue';

  /**
   * 定义接收参数
   */
  const props = defineProps({
    title: { type: String, default: '图片上传' },
    circled: { type: Boolean, default: false },
    uploadApi: {
      type: Function as PropType<(params) => Promise<any>>,
    },
    name: { type: String, default: 'name' },
  });

  const emit = defineEmits(['uploadSuccess', 'register']);

  const modalRef = ref(null);

  let filename = '';
  const src = ref('');
  const previewSource = ref('');
  const cropper = ref<Cropper>();
  let scaleX = 1;
  let scaleY = 1;

  /**
   * 定义模态
   */
  const [modalRegister, { openModal, closeModal, setSubLoading }] = useModal({
    title: props.title,
    width: 800,
  });
  function customRequest() {
    // 自定义上传逻辑，这里暂时不做处理
  }

  /**
   * 上传图片
   * @param file 文件
   */
  const beforeUpload = async (file) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    src.value = '';
    previewSource.value = '';
    reader.onload = function (e) {
      src.value = (e.target?.result as string) ?? '';
      filename = file.name;
    };
    return false;
  };

  /**
   * 执行裁剪
   * @param param0 参数
   */
  function handleCropend({ imgBase64 }: CropendResult) {
    previewSource.value = imgBase64;
  }

  function handleReady(cropperInstance: Cropper) {
    cropper.value = cropperInstance;
  }

  function handlerToolbar(event: string, arg?: number) {
    if (event === 'scaleX') {
      scaleX = arg = scaleX === -1 ? 1 : -1;
    }
    if (event === 'scaleY') {
      scaleY = arg = scaleY === -1 ? 1 : -1;
    }
    cropper?.value?.[event]?.(arg);
  }

  /**
   * 执行上传
   */
  async function handleOk() {
    if (!src.value) {
      setSubLoading(false);
      return message.error('请先上传图片');
    }
    const uploadApi = props.uploadApi;
    const name = props.name;
    const file = base64ToFile(previewSource.value, filename);
    // 文件上传
    if (uploadApi && isFunction(uploadApi)) {
      // 本地文件上传
      try {
        setSubLoading(true);
        const formData = new FormData();
        formData.append('file', file);
        formData.append('name', name);
        const result = await uploadApi(formData);
        emit('uploadSuccess', result);
        closeModal();
      } finally {
        setSubLoading(false);
      }
    } else {
      // OSS文件上传
      actionFiles(file);
    }
  }

  /**
   * 阿里云OSS上传
   * @param fileChild 参数
   */
  const actionFiles = async (fileChild: any) => {
    const configData = await getOssConfig();
    let date = new Date();
    let year = date.getFullYear();
    let month: string | number = date.getMonth() + 1;
    month = month < 10 ? '0' + month : month;
    let day: string | number = date.getDate();
    day = day < 10 ? '0' + day : day;
    let h: string | number = date.getHours();
    h = h < 10 ? '0' + h : h;
    let minute: string | number = date.getMinutes();
    minute = minute < 10 ? '0' + minute : minute;
    let second: string | number = date.getSeconds();
    second = second < 10 ? '0' + second : second;
    let time = h + '' + minute + '' + second;
    let filterFileName = time + '-' + fileChild.name;
    filterFileName = filterFileName.replace(
      /[\+\_\,\!\|\~\`\(\)\#\$\%\^\&\*\{\}\:\;\"\<\>\?]/g,
      '',
    );
    let filePath = props.name + '/' + year + '/' + month + '/' + day + '/' + filterFileName;
    setSubLoading(true);
    try {
      const headers = {
        'Access-Control-Allow-Origin': '*',
      };
      const client = new OSS({
        // yourRegion填写Bucket所在地域。以华东1（杭州）为例，yourRegion填写为oss-cn-hangzhou。
        endpoint: configData.oss_endpoint,
        // 从STS服务获取的临时访问密钥（AccessKey ID和AccessKey Secret）。
        secure: true,
        region: configData.oss_region,
        accessKeyId: configData.oss_accessKeyId,
        accessKeySecret: configData.oss_accessKeySecret,
        // 填写Bucket名称。
        bucket: configData.oss_bucketName,
        timeout: 600000,
      });
      const res = await client.multipartUpload(filePath, fileChild, {
        headers: headers,
        // 设置并发上传的分片数量。
        parallel: 4,
        // 设置分片大小。默认值为1 MB，最小值为100 KB。
        partSize: 1024 * 1024,
        // headers,
        mime: fileChild.type,
      });
      emit('uploadSuccess', { fileUrl: configData.oss_domain + res.name });
      closeModal();
    } catch (error) {
      emit('uploadSuccess', {});
    } finally {
      setSubLoading(false);
    }
  };

  /**
   * 执行关闭
   */
  function handleClose() {
    src.value = '';
    previewSource.value = '';
  }

  defineExpose({
    openModal,
  });
</script>

<style lang="less" scoped>
  .cropper-box {
    display: flex;

    &-left,
    &-right {
      height: 340px;
    }

    &-left {
      width: 55%;

      &-cropper {
        height: 300px;
        background: #eee;
        background-image: linear-gradient(
            45deg,
            rgba(0, 0, 0, 0.25) 25%,
            transparent 0,
            transparent 75%,
            rgba(0, 0, 0, 0.25) 0
          ),
          linear-gradient(
            45deg,
            rgba(0, 0, 0, 0.25) 25%,
            transparent 0,
            transparent 75%,
            rgba(0, 0, 0, 0.25) 0
          );
        background-position: 0 0, 12px 12px;
        background-size: 25px 25px;
      }

      &-toolbar {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 10px;
      }
    }

    &-right {
      width: 45%;

      &-preview {
        width: 220px;
        height: 220px;
        margin: 0 auto;
        overflow: hidden;
        border: 1px solid #ddd;

        img {
          width: 100%;
          height: 100%;
        }
      }

      &-preview-radius {
        border-radius: 50%;
      }

      &-group {
        display: flex;
        padding-top: 8px;
        margin-top: 8px;
        border-top: 1px solid #d9d9d9;
        justify-content: space-around;
        align-items: center;
      }
    }
  }
</style>
