<script lang="ts" setup>
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { ALG, formSchema, PackageField } from '../config/packageDetail.config';
  import { ref } from 'vue';
  import { createOtaPackage, uploadOtaPackages, deleteOtaPackage } from '/@/api/ota';
  import { CreateOtaPackageParams } from '/@/api/ota/model';

  interface FieldsValue extends CreateOtaPackageParams {
    fileList: { file: File }[];
    checksum?: string;
    checksumAlgorithm?: ALG;
  }

  const emit = defineEmits(['register', 'update:list']);

  const loading = ref(false);

  const [registerModal, { changeLoading, closeModal }] = useModalInner();

  const setLoading = (status: boolean) => {
    changeLoading(status);
    loading.value = status;
  };

  const [registerForm, { getFieldsValue, validate }] = useForm({
    schemas: formSchema,
    showActionButtonGroup: false,
    // labelCol: { span: 8 },
    labelWidth: 100,
    wrapperCol: { span: 16 },
  });

  const handleUploadFile = async (value: FieldsValue, id: string) => {
    try {
      const file = new FormData();
      file.append('file', value.fileList.at(0)!.file);
      await uploadOtaPackages({
        otaPackageId: id,
        file,
        checksumAlgorithm: value.checksumAlgorithm,
      });
    } catch (error) {
      console.log(error);
      if ((error as { status: number }).status) {
        await deleteOtaPackage(id);
      }
    } finally {
      closeModal();
      emit('update:list');
    }
  };

  const handleCreatePackages = async (value: FieldsValue) => {
    try {
      setLoading(true);
      const { id } = await createOtaPackage(value);
      const { isURL } = value;
      if (!isURL) {
        await handleUploadFile(value, id.id);
      }
    } catch (error) {
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async () => {
    try {
      await validate();
      const value = getFieldsValue();
      value[PackageField.DEVICE_PROFILE_INFO] = JSON.parse(value[PackageField.DEVICE_PROFILE_INFO]);
      value[PackageField.ADDITIONAL_INFO] = {
        [PackageField.DESCRIPTION]: value[PackageField.DESCRIPTION],
      };
      handleCreatePackages(value as unknown as FieldsValue);
    } catch (error) {
      window.console.error(error);
    }
  };
</script>

<template>
  <BasicModal
    title="包管理"
    destroy-on-close
    :ok-button-props="{ loading }"
    @register="registerModal"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" class="package-manage-form" />
  </BasicModal>
</template>

<style scoped lang="less">
  .package-manage-form {
    :deep(.ant-form-item-control-input-content > div > div) {
      width: 100% !important;
    }
  }
</style>
