<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    title="原始数据上传"
    :showCancelBtn="false"
    @visible-change="handleVisibleChange"
    @cancel="resetFields"
    @ok="handleSubmit"
    :loading="loading"
    :confirmLoading="loading"
    :min-height="0"
  >
    <div class="pt-2px pr-3px">
      <BasicForm @register="registerForm" :model="model">
        <template #text="{ model, field }">
          {{ model[field] }}
        </template>
      </BasicForm>
      <!-- <span>注意：迁移后该场景的权限配置将被清空，如需保留，请复制后再做迁移</span> -->
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, nextTick, onMounted, reactive, h } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { uploadSceneOrig, uploadSceneCheck } from '/@/api/operate';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { uploadApi } from '/@/api/product/index';

  const { t } = useI18n();
  export default defineComponent({
    components: { BasicModal, BasicForm },
    props: {
      userData: { type: Object },
    },
    emits: ['update', 'register'],
    setup(props, { emit }) {
      const modelRef = ref({});
      const fileFlow = reactive({
        filePath: null,
      });
      const loading = ref(false);
      const { createMessage, createConfirm } = useMessage();
      const schemas: FormSchema[] = [
        {
          field: 'filePath',
          component: 'Upload',
          label: t('routes.product.file'),
          required: true,
          rules: [{ required: true, message: t('common.uploadMessge') }],
          // helpMessage: t('routes.corporation.uploadHelp'),
          itemProps: {
            validateTrigger: 'onBlur',
          },
          componentProps: {
            api: uploadApi,
            maxNumber: 1,
            sizeUnit: 'GB',
            maxSize: 5,
            // accept: ['xls', 'xlsx'],
            afterFetch: function (data) {
              fileFlow.filePath = data.file;
              return data;
            },
          },

          colProps: {
            span: 22,
          },
        },
      ];
      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();
        setFieldsValue({
          type: data.sceneName,
        });
      }
      const handleSubmit = async () => {
        try {
          const params = await validate();
          let filePath = params.filePath[0];
          const resCheck = await uploadSceneCheck(filePath);
          if (resCheck.code == 60042) {
            return createConfirm({
              iconType: 'warning',
              title: '提示',
              content: () =>
                h('div', {}, [
                  h('div', null, `此场景原属于${resCheck.data}，继续上传将重新计算并覆盖原场景：`),
                  h('div', null, `归属权转移至当前账号；`),
                  h('div', null, `清除原所有者的权限设置；`),
                  h('div', null, `清空场景内由用户手动添加的空间模型。`),
                  h('div', null, `确定继续吗？`),
                ]),
              onOk: async () => {
                Submit(filePath)
              },
            });
          }
          if(resCheck.code == 60043) {
            return createConfirm({
              iconType: 'warning',
              title: '提示',
              content: `此场景此前已上传过‌，继续上传将重新计算并覆盖原场景，场景内由用户手动添加的空间模型也会清空，确定继续吗？`,
              onOk: async () => {
                Submit(filePath)
              },
            });
          }
          Submit(filePath)
        } catch (error) {
          console.log('not passing', error);
        }
      };
      function handleVisibleChange(v) {
        // console.log(v);
        // v && props.userData && nextTick(() => onDataReceive(props.userData));
      }
      async function Submit(filePath) {
        loading.value = true;
        try {
          const res = await uploadSceneOrig(filePath);
          loading.value = false;
          console.log('res', res, filePath);
          closeModal();
          resetFields();
          createMessage.success('上传成功。');
          emit('update');
        } catch (error) {
          loading.value = false;
        }

      }
      return {
        register,
        schemas,
        registerForm,
        model: modelRef,
        fileFlow,
        handleVisibleChange,
        handleSubmit,
        addListFunc,
        loading,
        resetFields,
        t,
      };
    },
  });
</script>
