<script lang="ts" setup>
  import { Spin } from 'ant-design-vue';
  import { onMounted, ref } from 'vue';
  import { DelimiterEnum } from './config';
  import { basicProps } from './props';
  import StepContainer from './StepContainer.vue';
  import { CreateEntityValue, UploadFileParseValue } from './type';
  import { batchImportDevice } from '/@/api/device/batchImport';
  import { ImportDeviceParams, ImportDeviceResponse } from '/@/api/device/model/batchImportModel';

  const props = defineProps({
    ...basicProps,
    value: {
      required: true,
      type: Object as PropType<CreateEntityValue>,
    },
    result: {
      required: true,
      type: Object as PropType<ImportDeviceResponse>,
    },
  });

  const emit = defineEmits(['update:result']);

  const spinning = ref(true);

  const sleep = (time: number) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve(time);
      }, time);
    });
  };

  const submit = async () => {
    spinning.value = true;
    try {
      const value = transfromData(JSON.parse(JSON.stringify(props.value)));
      const result = await batchImportDevice(value);
      await sleep(3000);
      emit('update:result', result);
      props.goNextStep?.();
    } catch (error) {
      throw error;
    } finally {
      spinning.value = false;
    }
  };

  const insertDeviceTypeName = (
    deviceTypeName: string,
    fileParseValue: UploadFileParseValue,
    columns: Record<'type', string>[]
  ): { file: string; columns: Record<'type', string>[] } => {
    const { header, content } = fileParseValue;
    const insertIndex = 1;

    const csvArray = content.map((item) => header.map((key) => item[key]) as string[]);
    for (const item of csvArray) {
      item.splice(insertIndex, 0, deviceTypeName);
    }

    const _header = [...header];
    _header.splice(insertIndex, 0, deviceTypeName);
    csvArray.unshift(_header);
    const file = csvArray.map((item) => item.join(DelimiterEnum.COMMA)).join('\n');

    columns.splice(insertIndex, 0, { type: 'TYPE' });

    return {
      file,
      columns,
    };
  };

  const transfromData = (data: CreateEntityValue) => {
    const { basicInfo, columnConfiguration, fileParseValue } = data;
    const { tkDeviceProfileId, organizationId, deviceTypeEnum, deviceTypeName } = basicInfo;
    const { file, columns } = insertDeviceTypeName(
      deviceTypeName,
      fileParseValue,
      columnConfiguration
    );
    return {
      file,
      tkDeviceProfileId,
      organizationId,
      deviceTypeEnum,
      mapping: {
        columns: columns,
        delimiter: DelimiterEnum.COMMA,
        header: true,
        update: true,
      },
    } as ImportDeviceParams;
  };

  onMounted(() => {
    submit();
  });
</script>

<template>
  <StepContainer class="flex justify-center">
    <Spin :spinning="spinning" tip="正在创建..." />
  </StepContainer>
</template>
