<template>
  <div style="display: flex; flex-wrap: wrap; width: 880px">
    <a-image-preview-group
      ref="imageGroup"
      :preview="{
        getContainer: getContainer,
        src: currentImageSrcUrl,
        onVisibleChange: handlerImageChange,
      }"
      @keydown.native.stop
    >
      <div
        v-for="(item, index) in fileList"
        :key="index"
        style="display: inline-block; position: relative"
      >
        <div v-if="!$attrs.disabled" class="video-delete-btn" @click="handlerDelete(index)">
          <CloseOutlined />
        </div>
        <a-image
          style="width: 100px; height: 100px"
          :src="item.url"
          @click="handlerPreviewImage(item, index)"
          @keydown.native.stop
        ></a-image>
      </div>
    </a-image-preview-group>
    <Upload
      v-if="!$attrs.disabled"
      v-bind="$attrs"
      :list-type="listType"
      :accept="getStringAccept"
      :multiple="multiple"
      :showUploadList="false"
      :maxCount="maxNumber"
      :before-upload="beforeUpload"
      :custom-request="customRequest"
      @preview="handlePreview"
      @remove="handleRemove"
    >
      <div v-if="fileList && fileList.length < maxNumber">
        <plus-outlined />
        <div style="margin-top: 8px">{{ t('component.upload.upload') }}</div>
      </div>
    </Upload>
    <!-- <Modal :open="previewOpen" :title="previewTitle" :footer="null" @cancel="handleCancel">
      <img alt="" style="width: 100%" :src="previewImage" />
    </Modal> -->
  </div>
</template>

<script setup lang="ts">
  import { ref, toRefs, watch, reactive, onMounted, provide, inject } from 'vue';
  import { PlusOutlined, CloseOutlined } from '@ant-design/icons-vue';
  import type { UploadFile, UploadProps, UploadChangeParam } from 'ant-design-vue';
  import { Modal, Upload } from 'ant-design-vue';
  import { UploadRequestOption } from 'ant-design-vue/lib/vc-upload/interface';
  import { useMessage } from '@/hooks/web/useMessage';
  import { isArray, isFunction, isObject, isString } from '@/utils/is';
  import { warn } from '@/utils/log';
  import { useI18n } from '@/hooks/web/useI18n';
  import { useUploadType } from '../hooks/useUpload';
  import { uploadContainerProps } from '../props';
  import { isImgTypeByName } from '../helper';
  import { UploadResultStatus } from '@/components/Upload/src/types/typing';
  import { actions } from '@/views/demo/page/account/center/data';
  import { fileUploadApi } from '@/api/sys/upload';
  import ImagePreview from '@/components/Upload/src/components/image_preview.vue';
  import { userFormFileStore } from '@/store/modules/formFileUrl';
  import ImageUploadSelectOtherModal from './ImageUploadSelectOtherModal.vue';

  const formFileStore = userFormFileStore();

  const currentImageSrcUrl = ref<String>('');

  onMounted(() => {});

  defineOptions({ name: 'ImageUpload' });

  const emit = defineEmits(['change', 'update:value', 'delete']);
  const props = defineProps({
    ...uploadContainerProps,
  });

  const { t } = useI18n();
  const { createMessage } = useMessage();
  const { accept, helpText, maxNumber, maxSize } = toRefs(props);
  const isInnerOperate = ref<boolean>(false);
  const { getStringAccept } = useUploadType({
    acceptRef: accept,
    helpTextRef: helpText,
    maxNumberRef: maxNumber,
    maxSizeRef: maxSize,
  });

  const previewOpen = ref<boolean>(false);
  const previewImage = ref<string>('');
  const previewTitle = ref<string>('');

  const fileList = ref<UploadProps['fileList']>([]);
  const imageList = reactive([]);
  const isLtMsg = ref<boolean>(true);
  const isActMsg = ref<boolean>(true);

  const getContainer = () => {
    return document.getElementById('form-container');
  };

  watch(
    () => props.value,
    (v) => {
      if (isInnerOperate.value) {
        isInnerOperate.value = false;
        return;
      }

      if (v) {
        let value: string[] = [];
        if (isArray(v)) {
          value = v;
        } else {
          value.push(v);
        }

        fileList.value = value.map((item, i) => {
          if (item && isString(item)) {
            return {
              uid: -i + '',
              name: item.substring(item.lastIndexOf('/') + 1),
              status: 'done',
              url: item,
            };
          } else if (item && isObject(item)) {
            return item;
          } else {
            return;
          }
        }) as UploadProps['fileList'];
      }

      let arr = props.value?.split(',') as [];
      fileList.value = [];
      const { server } = props;
      arr?.forEach((item, index) => {
        if (item) {
          fileList.value?.push({
            uid: '-1',
            name: item,
            status: 'done',
            url: server + '/' + item,
          });
        }
      });
    },
  );

  // function getBase64<T extends string | ArrayBuffer | null>(file: File) {
  //   return new Promise<T>((resolve, reject) => {
  //     const reader = new FileReader();
  //     reader.readAsDataURL(file);
  //     reader.onload = () => {
  //       resolve(reader.result as T);
  //     };
  //     reader.onerror = (error) => reject(error);
  //   });
  // }

  const handlePreview = async (file: UploadFile) => {
    const { server, azimuth } = props;
    if (!file.url && !file.preview) {
      // file.preview = await getBase64<string>(file.originFileObj!);
    }
    previewImage.value = file.url || file.preview || '';
    previewOpen.value = true;
    previewTitle.value =
      file.name || previewImage.value.substring(previewImage.value.lastIndexOf('/') + 1);
  };

  // const handleChange = (info: UploadChangeParam) => {
  //   if (info.file.status === 'uploading') {
  //     return;
  //   }
  //   if (info.file.status === 'done') {
  //     console.log("donw",info);
  //   }
  //   if (info.file.status === 'error') {

  //   }
  // };
  const handlerDelete = (index) => {
    fileList.value.splice(index, 1);
    let value = getValue();
    emit('change', value);
    emit('update:value', value);
  };

  const handleRemove = async (file: UploadFile) => {
    if (fileList.value) {
      const index = fileList.value.findIndex((item) => item.uid === file.uid);
      index !== -1 && fileList.value.splice(index, 1);

      const value = getValue();
      isInnerOperate.value = true;
      emit('change', value);
      emit('delete', file);
    }
  };

  const handleCancel = () => {
    previewOpen.value = false;
    previewTitle.value = '';
  };

  const beforeUpload = (file: File) => {
    const { maxSize, accept } = props;
    const { name } = file;
    const isAct = isImgTypeByName(name);
    if (!isAct) {
      createMessage.error(t('component.upload.acceptUpload', [accept]));
      isActMsg.value = false;
      // 防止弹出多个错误提示
      setTimeout(() => (isActMsg.value = true), 1000);
    }
    const isLt = file.size / 1024 / 1024 > maxSize;
    if (isLt) {
      createMessage.error(t('component.upload.maxSizeMultiple', [maxSize]));
      isLtMsg.value = false;
      // 防止弹出多个错误提示
      setTimeout(() => (isLtMsg.value = true), 1000);
    }
    return (isAct && !isLt) || Upload.LIST_IGNORE;
  };

  async function customRequest(info: UploadRequestOption<any>) {
    const { api, server, action } = props;

    // if (!api || !isFunction(api)) {
    //   return warn('upload api must exist and be a function');
    // }

    try {
      const res = await fileUploadApi?.(
        {
          data: {
            ...(props.uploadParams || {}),
          },
          file: info.file,
          name: props.name,
          filename: props.filename,
        },
        server + action,
      );

      fileList.value?.push({
        uid: '-1',
        name: info.file.name,
        status: 'done',
        url: server + '/' + res.data.result[0].filePath,
      });

      info.onSuccess!();
      const value = getValue();
      // isInnerOperate.value = true;
      emit('change', value);
    } catch (e: any) {
      info.onError!(e);
    }
  }

  function getValue() {
    // fileList.value.forEach((item,index)=>{
    //   item.url?.splice(server,"");
    //   saveData+=item.url+","
    // })
    // return saveData;
    let path = '';
    const { server } = props;
    fileList.value?.forEach((item, index) => {
      path += item.url?.replace(server + '/', '') + ',';
    });
    return path;
    // const list = (fileList.value || [])
    //   .filter((item) => item?.status === UploadResultStatus.DONE)
    //   .map((item: any) => {
    //     return item?.url || item?.response?.url;
    //   });
    // return props.multiple ? list : list.length > 0 ? list[0] : '';
  }

  const globalImagePreviewUrl = ref<Number>();

  function handlerPreviewImage(item, index): void {
    const { azimuth } = props;
    // if(azimuth){
    globalImagePreviewUrl.value = index;

    // }
    // globalImagePreviewUrl.value = url + '?' + Math.random();
    formFileStore.setUrl(item.url);
    formFileStore.setUrlList(fileList);
  }

  const isInitImageLisener = ref<Boolean>(false);
  // 监听预览图片地址变化进行箭头切换
  function handlerImageChange(e): void {
    isInitImageLisener.value = false;
    if (e && !isInitImageLisener.value) {
      setTimeout(function () {
        const targetNode = document.getElementsByClassName('ant-image-preview-img');
        targetNode?.forEach((node, index) => {
          let imageObserver = new MutationObserver((mutationsList) => {
            for (const mutation of mutationsList) {
              if (node.getAttribute(mutation.attributeName).match('http')) {
                formFileStore.setUrl(node.getAttribute(mutation.attributeName));
              }
            }
          });
          const config = { attributes: true };
          imageObserver.observe(node, config);
          isInitImageLisener.value = true;
        });
      }, 250);
    }
  }
</script>

<style lang="less" scoped>
  .ant-upload-select-picture-card i {
    color: #999;
    font-size: 32px;
  }

  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }

  .video-item {
    position: relative;
    width: 100px;
    height: 100px;
    margin-right: 10px;
    margin-bottom: 10px;
    float: left;
    overflow: hidden;
    border-radius: 6px;
    background: #fff;
    text-align: center;
    cursor: pointer;
  }

  .video-delete-btn {
    position: absolute;
    top: 0px;
    right: 10px;
    width: 30px;
    height: 30px;
    border-bottom-left-radius: 80%;
    background: rgb(0 0 0 / 20%);
    color: #fff;
    line-height: 30px;
    text-align: center;
    z-index: 999;
  }

  .video-item img {
    width: 80px;
    height: 80px;
  }

  .video-item p {
    overflow: hidden;
    color: #777 !important;
    font-size: 12px;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .ant-upload-wrapper {
    width: 100px !important;
  }

  .video-player {
    width: 500px;
    margin: 10px;
  }

  .image-preview {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 999;
  }
  :deep(.ant-image) {
    margin-right: 10px;
    margin-bottom: 10px;
  }
  #process-form-container {
    width: 50%;
    height: 500px;
    overflow: hidden;
    float: left;
    position: relative;
    :deep(.ant-image-preview-wrap) {
      position: absolute;
    }
    :deep(.ant-image-preview-mask) {
      position: absolute;
    }
    :deep(.ant-image-preview-operations-wrapper) {
      height: 100%;
      position: absolute;
      .ant-image-preview-operations {
        position: absolute;
        bottom: 0;
        width: 100%;
        .ant-image-preview-operations-operation {
          // flex:1;
        }
      }
      .ant-image-preview-operations-operation:nth-last-child(1) {
        display: none;
      }
      .ant-image-preview-operations-operation:nth-last-child(2) {
        display: none;
      }
    }
  }
  .copy-other {
    width: 100px;
    height: 100px;
    border: 1px dashed #d9d9d9;
    background-color: rgba(0, 0, 0, 0.02);
    cursor: pointer;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-left: 10px;
  }
  .copy-other:hover {
    border-color: #0960bd;
  }
</style>
