<template>
  <div>
    <div class="video-item" v-for="(item,index) in fileList" :key="index">
      <div v-if="!$attrs.disabled" class="video-delete-btn" @click="handlerDelete(index)">
        <CloseOutlined/>
      </div>
      <img src="./video.png" @click="handlePreview(item)" alt="">
      <p>{{ item.name}}</p>
    </div>

    <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" /> -->
      <video :src="previewImage" class="video-player" controls muted autoplay></video>
    </Modal>
  </div>
</template>

<script lang="ts" setup>
  import { ref, toRefs, watch,reactive, onMounted } from 'vue';
  import { PlusOutlined,CloseOutlined } from '@ant-design/icons-vue';
  import type { UploadFile, UploadProps } 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 { isVideoTypeByName } from '../helper';
  import { UploadResultStatus } from '@/components/Upload/src/types/typing';
import { fileUploadApi } from '@/api/sys/upload';

  defineOptions({ name: 'VideoUpload' });

  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 isLtMsg = ref<boolean>(true);
  const isActMsg = ref<boolean>(true);

  const showUploadList = reactive({
        showRemoveIcon: true,
        showPreviewIcon: true
      })
  

  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
            })
            console.log("fileListItem",fileList.value)
          }
        })
        console.log("fileList",fileList.value);
    },
  );

  onMounted(()=>{
        
  })

  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) => {
    
    previewImage.value = file.url || file.preview || '';
    previewOpen.value = true;
    previewTitle.value =
      file.name || previewImage.value.substring(previewImage.value.lastIndexOf('/') + 1);
  };

  const handlerDelete = (index) => {
    fileList.value.splice(index,1);
    let value = getValue();
    emit("change",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 = isVideoTypeByName(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,action,server } = 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() {
    const { server } = props;
    let saveData = "";
    fileList.value.forEach((item,index)=>{
      console.log("fileListItem",item);
      saveData+=item.url?.replace(server,"")+","
    })
    return saveData;
  }
</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:-5px;
    right:-5px;
    width:30px;
    height:30px;
    border-bottom-left-radius: 80%;
    background:rgb(0 0 0 / 20%);
    color:#fff;
    line-height: 30px;
    text-align: center;
  }

  .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;
  }
</style>
