<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="fileFlow.title"
    @visible-change="handleVisibleChange"
    @cancel="resetFields"
    @ok="handleSubmit"
    :okText="loading ? `上传中 ${fileFlow.complete}%` : '确认'"
    :confirmLoading="loading"
    :min-height="250"
    :height="700"
  >
    <div class="pt-2px pr-3px myzdyfrmo">
      <BasicForm @register="registerForm" :model="model">
        <template #text="{ model, field }">
          {{ model[field] }}
        </template>
        <template #file="{ model, field }">
          <Upload
            :key="isAnimation"
            style="width: 300px"
            :disabled="!fileFlow.dictId"
            :accept="!isAnimation?'.jpg, .png, .jpeg, .mp4, .wav, .mp3, .shp, .zip':'.glb, .zip'"
            v-model:file-list="fileList"
            :beforeUpload="beforeUpload"
            @remove="handleRemove"
          >
            <a-button :disabled="!fileFlow.dictId"> 上传 </a-button>
          </Upload>
        </template>
      </BasicForm>
      <div style="padding: 0 0 0 82px" v-if="!isAnimation">
        <div style="margin-bottom: 10px"
          >支持jpg、png、jpeg、mp4、wav、mp3 、shp格式文件上传。文件大小 ≤ 2G</div
        >
        <!-- <span>注意：模型需使用zip包上传。包含贴图、模型、mtl文件，包内不得包含文件夹。</span> -->
        <div style="margin-bottom: 10px">
          <div>
            上传
            obj：需使用zip包上传。包含贴图、模型、mtl文件，包内不得包含文件夹，文件名不得使用中文。如图：</div
          >
          <img style="width: 150px" :src="obj" alt="" />
        </div>
        <div style="margin-bottom: 10px">
          <div>
            上传 osgb：需使用zip包上传。包含 Data 文件夹、xml
            文件，包内不得包含文件夹,文件名不得使用中文。如图：</div
          >
          <img style="width: 150px" :src="osgb" alt="" />
        </div>
      </div>
      <div v-else style="padding: 0 0 0 82px">
        <div style="margin-bottom: 10px"
          >支持obj、glb格式文件上传。文件大小 ≤ 5MB</div
        >
        <!-- <span>注意：模型需使用zip包上传。包含贴图、模型、mtl文件，包内不得包含文件夹。</span> -->
        <div style="margin-bottom: 10px">
          <div>
            上传
            obj：需使用zip包上传。包含贴图、模型、mtl文件，包内不得包含文件夹，文件名不得使用中文。如图：</div
          >
          <img style="width: 150px" :src="obj" alt="" />
        </div>
      </div>
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, nextTick, onMounted, reactive, unref } from 'vue';
  import { Upload } from 'ant-design-vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { addOrUpdate, uploadApi, getByKey } from '/@/api/media';
  import obj from '/@/assets/images/obj.jpg';
  import osgb from '/@/assets/images/osgb.jpg';
  import { useI18n } from '/@/hooks/web/useI18n';
  import type { UploadProps } from 'ant-design-vue';
  import { debounce } from 'lodash-es';
  const { t } = useI18n();
  export default defineComponent({
    components: { BasicModal, BasicForm, Upload },
    props: {
      userData: { type: Object },
    },
    emits: ['update', 'register'],
    setup(props, { emit }) {
      const modelRef = ref({});
      const isAnimation = ref(false)
      const fileList = ref<UploadProps['fileList']>([]);
      const loading = ref(false);
      const fileFlow = reactive({
        file: null,
        title: '上传',
        complete: 0,
        dictId: null,
      });
      const { createMessage } = useMessage();
      const schemas: FormSchema[] = [
        {
          field: 'file',
          component: 'InputTextArea',
          // component: 'Upload',
          label: t('routes.product.file'),
          slot: 'file',
          // rules: [{ required: true, message: t('common.uploadMessge') }],
          // // helpMessage: t('routes.corporation.uploadHelp'),
          // itemProps: {
          //   validateTrigger: 'onBlur',
          // },
          // componentProps: {
          //   api: uploadApi,
          //   maxNumber: 1,
          //   maxSize: 2000,
          //   fileFlow: true,
          //   accept: ['jpg', 'jpg', 'png', 'jpeg', 'mp4', 'wav', 'mp3', 'shp', 'zip'],
          //   afterFetch: function (data) {
          //     console.log('afterFetch', data);
          //     // Reflect.set(data, 'url', data.name);
          //     fileFlow.file = data.file;
          //     return data;
          //   },
          // },

          colProps: {
            span: 16,
          },
        },
        {
          field: 'dictId',
          label: '分组',
          component: 'ApiSelect',
          // required: true,
          componentProps: {
            api: getByKey,
            style: 'width: 350px',
            labelField: 'dictName',
            listHeight: 150,
            valueField: 'id',
            params: {
              type: 1,
            },
            onChange: (val,text) => {
              fileFlow.dictId = val
              fileList.value = [];
              isAnimation.value = text.useType == "animation"
            },
          },
          itemProps: {
            autoLink: false,
          },
          colProps: {
            xl: 18,
            xxl: 18,
          },
        },
      ];
      const [registerForm, { validate, resetFields, setFieldsValue }] = useForm({
        labelWidth: 120,
        schemas,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });
      onMounted(() => {});
      let addListFunc = () => {};
      const [register, { closeModal }] = useModalInner((data) => {
        console.log(data);
        data && onDataReceive(data);
      });

      function onDataReceive(data) {
        modelRef.value = data;
        resetFields();
        fileList.value = [];
        setFieldsValue({
          type: data.sceneName,
        });
      }
      const handleSubmit = debounce(async () => {
        let file = fileList.value[0];
        if (!file) {
          createMessage.warning('请上传文件');
          return;
        }
        console.log('handleSubmit', file, file.value);
        loading.value = true;
        fileFlow.complete = 0;
        try {
          const params = await validate();
          const apiData = {
            file: file,
            data: {
              dictId: params.dictId,
            },
          };
          console.log('res', apiData, params);
          function onUploadProgress(progressEvent: ProgressEvent) {
            const complete = ((progressEvent.loaded / progressEvent.total) * 100) | 0;
            fileFlow.complete = complete;
          }
          await uploadApi(apiData, onUploadProgress);
          closeModal();
          resetFields();
          loading.value = false;
          createMessage.success('上传成功。');
          emit('update');
        } catch (error) {
          loading.value = false;
          console.log('not passing', error);
        }
      }, 300);
      function handleVisibleChange(v) {
        // console.log(v);
        // v && props.userData && nextTick(() => onDataReceive(props.userData));
      }
      const handleRemove = (file) => {
        const index = fileList.value.indexOf(file);
        const newFileList = fileList.value.slice();
        newFileList.splice(index, 1);
        fileList.value = newFileList;
      };

      const beforeUpload: UploadProps['beforeUpload'] = (file) => {
        console.log('beforeUpload', file);
        const filetype = file.name.substring(file.name.lastIndexOf('.') + 1).toLowerCase();
        const isExcel = ['jpg', 'jpg', 'png', 'jpeg', 'mp4', 'wav', 'mp3', 'shp', 'zip'].includes(
          filetype,
        ); // 调用上面代码
        const isdonghua = ['glb', 'zip'].includes(
          filetype,
        );
        if (!isExcel && isAnimation.value) {
          createMessage.error('支持obj、glb格式文件上传');
          fileList.value = [];
          return Upload.LIST_IGNORE;
        }
        if (!isdonghua && !isAnimation.value) {
          createMessage.error('支持jpg、png、jpeg、mp4、wav、mp3 、shp、zip格式文件上传');
          fileList.value = [];
          return Upload.LIST_IGNORE;
        }
        const isLt10M = file.size / 1024 / 1024 < 2000;
        const isLt5M = file.size / 1024 / 1024 < 5;
        if (!isLt10M && !isAnimation.value) {
          fileList.value = [];
          createMessage.error('上传文件不能超过 2G!');
          return Upload.LIST_IGNORE;
        }
        if (!isLt5M && isAnimation.value) {
          fileList.value = [];
          createMessage.error('上传文件不能超过 5MB!');
          return Upload.LIST_IGNORE;
        }
        fileList.value = [file];
        return false;
      };
      return {
        register,
        schemas,
        registerForm,
        model: modelRef,
        fileFlow,
        handleVisibleChange,
        handleSubmit,
        addListFunc,
        resetFields,
        t,
        obj,
        osgb,
        loading,
        fileList,
        handleRemove,
        beforeUpload,
        isAnimation,
      };
    },
  });
</script>

<style lang="less">
  .myzdyfrmo {
    .ant-upload-span {
      max-width: 340px !important;
    }
  }
</style>
