<script lang="ts" setup>
  import { computed, ref, unref } from 'vue';
  import { BasicModal, useModal } from '/@/components/Modal';
  import { Steps, Button, Tooltip } from 'ant-design-vue';
  import BasicInfoForm from './BasicInfoForm.vue';
  import ImportCsv from './ImportCsv.vue';
  import { CreateEntityValue, UploadFileParseValue } from './type';
  import ColumnType from './ColumnType.vue';
  import CreateEntity from './CreateEntity.vue';
  import CompleteResult from './CompleteResult.vue';
  import { ImportDeviceResponse } from '/@/api/device/model/batchImportModel';
  import { csvTemplate, downloadFile } from './config';

  const emit = defineEmits(['importFinally']);

  const [register] = useModal();

  const basicInfo = ref({});

  const fileParseValue = ref<UploadFileParseValue>({ header: [], content: [] });

  const columnConfiguration = ref<Record<'type', string>[]>([]);

  const importResult = ref<ImportDeviceResponse>({} as unknown as ImportDeviceResponse);

  const assemblyData = computed(() => {
    return {
      basicInfo: unref(basicInfo),
      fileParseValue: unref(fileParseValue),
      columnConfiguration: unref(columnConfiguration),
    } as CreateEntityValue;
  });

  enum StepsEnum {
    BASIC_INFO,
    IMPORT_FILE,
    COLUMN_CONFIGURATION,
    CREATE_ENTITY,
    FINISH,
  }

  enum StepsNameEnum {
    BASIC_INFO = '基本信息',
    IMPORT_FILE = '选择一个文件',
    COLUMN_CONFIGURATION = '选择列类型',
    CREATE_ENTITY = '创建新实体',
    FINISH = '完成',
  }

  const currentStep = ref<StepsEnum>(StepsEnum.BASIC_INFO);

  const goNextStep = () => {
    if (unref(currentStep) >= StepsEnum.FINISH) return;
    currentStep.value = unref(currentStep) + 1;
  };

  const goPreviousStep = () => {
    if (unref(currentStep) <= StepsEnum.BASIC_INFO) return;
    currentStep.value = unref(currentStep) - 1;
  };

  const reset = () => {
    basicInfo.value = {};
    fileParseValue.value = { header: [], content: [] };
    columnConfiguration.value = [];
    importResult.value = {} as unknown as ImportDeviceResponse;
  };

  const handleCancel = async () => {
    if (unref(currentStep) === StepsEnum.FINISH) {
      emit('importFinally');
    }
    currentStep.value = StepsEnum.BASIC_INFO;
    reset();
    return true;
  };

  const handleTemplateDownload = () => {
    downloadFile(csvTemplate, 'template', 'text/csv', 'csv');
  };
</script>

<template>
  <BasicModal
    title="导入设备"
    @register="register"
    width="60%"
    wrap-class-name="import-device-modal"
    :show-ok-btn="false"
    cancel-text="关闭"
    :close-func="handleCancel"
    :destroy-on-close="true"
  >
    <section class="overflow-auto relative">
      <Steps direction="vertical" :current="currentStep">
        <Steps.Step
          v-for="item in Object.keys(StepsEnum).filter((key) => isNaN(key as unknown as number))"
          :key="item"
        >
          <template #title>
            <div>
              {{ StepsNameEnum[item] }}
            </div>
            <BasicInfoForm
              v-if="StepsEnum[item] === StepsEnum.BASIC_INFO && StepsEnum[item] === currentStep"
              v-model:value="basicInfo"
              :go-next-step="goNextStep"
              :go-previous-step="goPreviousStep"
            />
            <ImportCsv
              v-if="StepsEnum[item] === StepsEnum.IMPORT_FILE && StepsEnum[item] === currentStep"
              v-model:value="fileParseValue"
              :go-next-step="goNextStep"
              :go-previous-step="goPreviousStep"
            />
            <ColumnType
              v-model:value="columnConfiguration"
              v-if="
                StepsEnum[item] === StepsEnum.COLUMN_CONFIGURATION &&
                StepsEnum[item] === currentStep
              "
              :file-parse-value="fileParseValue"
              :go-next-step="goNextStep"
              :go-previous-step="goPreviousStep"
            />
            <CreateEntity
              v-model:result="importResult"
              :value="assemblyData"
              v-if="StepsEnum[item] === StepsEnum.CREATE_ENTITY && StepsEnum[item] === currentStep"
              :go-next-step="goNextStep"
              :go-previous-step="goPreviousStep"
            />
            <CompleteResult
              v-if="StepsEnum[item] === StepsEnum.FINISH && StepsEnum[item] === currentStep"
              :value="importResult"
            />
          </template>
        </Steps.Step>
      </Steps>
      <Tooltip
        title="模板表头的第一列为设备名称,且不能重复,如需预置访问凭证(ACCESS_TOKEN、MQTT client ID、MQTT user name、MQTT password)添加新的列即可。例如:username、password"
      >
        <Button
          type="text"
          class="!absolute top-0 right-0 !text-blue-400"
          @click="handleTemplateDownload"
        >
          模版下载
        </Button>
      </Tooltip>
    </section>
  </BasicModal>
</template>

<style lang="less">
  .import-device-modal {
    .ant-steps-item-title {
      width: 100%;
    }
  }
</style>
