import { getDefaultDeviceProfile, getDeviceProfileInfos } from '/@/api/ota';
import { Id } from '/@/api/ota/model';
import { FormSchema } from '/@/components/Form';
import { FileItem } from '/@/components/Form/src/components/ApiUpload.vue';

export enum PackageField {
  TITLE = 'title',
  VERSION = 'version',
  VERSION_TAG = 'tag',
  PACKAGE_TYPE = 'type',
  URL = 'url',
  IS_URL = 'isUrl',
  CHECK_SUM_ALG = 'checksumAlgorithm',
  CHECK_SUM = 'checksum',
  DESCRIPTION = 'description',
  DEVICE_PROFILE_INFO = 'deviceProfileId',

  CREATE_TIME = 'createdTime',
  FILE_SIZE = 'dataSize',
  FILE_NAME = 'fileName',
  ADDITIONAL_INFO = 'additionalInfo',
  FILE_TYPE = 'contentType',

  PACKAGE_BINARY_FILE = 'fileList',
  VALIDATE_WAY = 'validateWay',
}

export enum PackageType {
  FIRMWARE = 'FIRMWARE',
  SOFTWARE = 'SOFTWARE',
}

export enum CheckSumWay {
  AUTO = 'auto',
  MANUAL = 'manual',
}

export enum ALG {
  MD5 = 'MD$',
  SHA_256 = 'SHA256',
  SHA_384 = 'SHA384',
  SHA_512 = 'SHA512',
  CRC_32 = 'CRC32',
  MURMUR3_32 = 'MURMUR332',
  MURMUR3_128 = 'MURMUR3128',
}

const getVersionTag = (title: string, version: string) => {
  return `${title ?? ''} ${version ?? ''}`;
};

export const formSchema: FormSchema[] = [
  {
    field: PackageField.TITLE,
    label: '标题',
    component: 'Input',
    rules: [{ required: true, message: '标题为必填项' }],
    componentProps: ({ formActionType, formModel }) => {
      const { setFieldsValue } = formActionType;
      return {
        placeholder: '请输入标题',
        maxLength: 36,
        onChange: (value: Event) => {
          setFieldsValue({
            [PackageField.VERSION_TAG]: getVersionTag(
              (value.target as HTMLInputElement).value,
              formModel[PackageField.VERSION]
            ),
          });
        },
      };
    },
  },
  {
    field: PackageField.VERSION,
    label: '版本',
    component: 'Input',
    rules: [{ required: true, message: '版本为必填项' }],
    componentProps: ({ formActionType, formModel }) => {
      const { setFieldsValue } = formActionType;
      return {
        placeholder: '请输入版本',
        maxLength: 36,
        onChange: (value: Event) => {
          setFieldsValue({
            [PackageField.VERSION_TAG]: getVersionTag(
              formModel[PackageField.TITLE],
              (value.target as HTMLInputElement).value
            ),
          });
        },
      };
    },
  },
  {
    field: PackageField.VERSION_TAG,
    label: '版本标签',
    component: 'Input',
    helpMessage: ['自定义标签应与您设备报告的软件包版本相匹配'],
    componentProps: () => {
      return {
        maxLength: 36,
        placeholder: '请输入版本标签',
      };
    },
  },
  {
    field: PackageField.DEVICE_PROFILE_INFO,
    label: '所属产品',
    component: 'ApiSearchSelect',
    helpMessage: ['上传的包仅适用于具有所选配置文件的设备'],
    defaultValue: 'default',
    rules: [{ required: true, message: '所属产品为必填项' }],
    componentProps: ({ formActionType }) => {
      const { setFieldsValue } = formActionType;
      return {
        placeholder: '请选择所属产品',
        showSearch: true,
        resultField: 'data',
        labelField: 'name',
        valueField: 'id',
        api: async () => {
          const data = await getDefaultDeviceProfile();
          data.id = JSON.stringify(data.id) as unknown as Id;
          setFieldsValue({ [PackageField.DEVICE_PROFILE_INFO]: data.id });
          return { data: [data] };
        },
        searchApi: async (params: Recordable) => {
          const data = await getDeviceProfileInfos({ textSearch: params.text });
          data.data = data.data.map((item) => ({
            ...item,
            id: JSON.stringify(item.id) as unknown as Id,
          }));
          return data;
        },
      };
    },
  },
  {
    field: PackageField.PACKAGE_TYPE,
    label: '包类型',
    component: 'Select',
    helpMessage: ['上传包后，您将无法修改标题、版本、产品文件和包类型'],
    defaultValue: PackageType.FIRMWARE,
    rules: [{ required: true, message: '包类型为必填项' }],
    componentProps: () => {
      return {
        options: [
          { label: '固件', value: PackageType.FIRMWARE },
          { label: '软件', value: PackageType.SOFTWARE },
        ],
        placeholder: '请选择所属产品',
      };
    },
  },
  {
    field: PackageField.IS_URL,
    label: '上传方式',
    component: 'RadioGroup',
    defaultValue: false,
    componentProps: () => {
      return {
        defaultValue: false,
        options: [
          { label: '上传二进制文件', value: false },
          { label: '使用外部URL', value: true },
        ],
      };
    },
  },
  {
    field: PackageField.PACKAGE_BINARY_FILE,
    label: '二进制文件',
    ifShow: ({ model }) => {
      return !model[PackageField.IS_URL];
    },
    component: 'ApiUpload',
    valueField: PackageField.PACKAGE_BINARY_FILE,
    changeEvent: `update:${PackageField.PACKAGE_BINARY_FILE}`,
    rules: [{ required: true, message: '请上传二进制文件', type: 'array' }],
    componentProps: {
      maxFileLimit: 1,
      api: (file: FileItem) => {
        return { uid: file.uid, name: file.name, file };
      },
    },
  },
  {
    field: PackageField.URL,
    label: '外部URL',
    component: 'Input',
    ifShow: ({ model }) => {
      return model[PackageField.IS_URL];
    },
    rules: [{ required: true, message: '外部URL为必填项' }],
    componentProps: {
      maxLength: 36,
      placeholder: '请输入外部URL',
    },
  },
  {
    field: PackageField.VALIDATE_WAY,
    label: '校验和方式',
    component: 'RadioGroup',
    defaultValue: CheckSumWay.AUTO,
    ifShow: ({ model }) => {
      return !model[PackageField.IS_URL];
    },
    componentProps: () => {
      return {
        options: [
          { label: '自动生成', value: CheckSumWay.AUTO },
          { label: '手动生成', value: CheckSumWay.MANUAL },
        ],
      };
    },
  },
  {
    field: PackageField.CHECK_SUM_ALG,
    label: '校验和算法',
    component: 'Select',
    ifShow: ({ model }) => {
      return model[PackageField.VALIDATE_WAY] === CheckSumWay.MANUAL && !model[PackageField.IS_URL];
    },
    defaultValue: ALG.SHA_256,
    componentProps: {
      placeholder: '请选择校验和算法',
      options: Object.keys(ALG).map((key) => {
        return {
          label: String(ALG[key]).toUpperCase(),
          value: ALG[key],
        };
      }),
    },
  },
  {
    field: PackageField.CHECK_SUM,
    label: '校验和',
    component: 'Input',
    ifShow: ({ model }) => {
      return model[PackageField.VALIDATE_WAY] === CheckSumWay.MANUAL && !model[PackageField.IS_URL];
    },
    helpMessage: ['如果校验和为空,会自动生成'],
    componentProps: {
      maxLength: 36,
      placeholder: '请输入校验和',
    },
  },
  {
    field: PackageField.DESCRIPTION,
    label: '描述',
    component: 'InputTextArea',
    componentProps: {
      maxLength: 255,
      placeholder: '请输入描述',
    },
  },
];
