<template>
  <BasicForm @register="register" />
</template>
<script lang="ts" setup>
  import { BasicForm, useForm } from '/@/components/Form';
  import { DataType, ModelOfMatterParams } from '/@/api/device/model/modelOfMatterModel';
  import { StructFormValue } from '/@/components/Form/src/externalCompns/components/StructForm/type';
  import {
    transfromToStructJSON,
    excludeIdInStructJSON,
  } from '/@/components/Form/src/externalCompns/components/StructForm/util';
  import { FunctionType } from './config';
  import { isArray } from 'lodash';
  import { OpenModelMode } from '../types';
  import { formSchemas } from '/@/components/Form/src/externalCompns/components/StructForm/config';

  defineProps<{ openModalMode: OpenModelMode }>();

  const [register, { validate, resetFields, setFieldsValue, setProps }] = useForm({
    labelWidth: 100,
    schemas: formSchemas(false),
    actionColOptions: {
      span: 14,
    },
    showResetButton: false,
    submitOnReset: false,
    showActionButtonGroup: false,
  });

  const setDisable = (flag: boolean) => {
    setProps({ disabled: flag });
  };

  async function getFormData(): Promise<Partial<ModelOfMatterParams>> {
    const _values = (await validate()) as StructFormValue;
    if (!_values) return {};
    const { functionName, remark, identifier, accessMode } = _values;
    const structJSON = transfromToStructJSON(_values);
    const dataType = excludeIdInStructJSON(structJSON.dataType!);

    const value = {
      functionName,
      functionType: FunctionType.PROPERTIES,
      remark,
      identifier,
      accessMode,
      functionJson: {
        dataType: dataType,
      },
    } as ModelOfMatterParams;
    return value;
  }

  const resetFormData = () => {
    resetFields();
  };

  const setFormData = (record: ModelOfMatterParams) => {
    const { functionJson } = record;
    const { dataType = {} } = functionJson!;

    const { specs } = dataType! as DataType;

    const value = {
      ...record,
      ...functionJson,
      ...dataType,
      ...(isArray(specs) ? specs : { ...specs }),
    };

    setFieldsValue(value);
  };

  defineExpose({
    resetFormData,
    getFormData,
    setFormData,
    setDisable,
  });
</script>
<style lang="less" scoped></style>
