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

  defineProps<{ openModalMode: OpenModelMode }>();

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

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

  //回显数据
  const setFormData = (record: ModelOfMatterParams) => {
    const { functionJson = {}, functionName, identifier, remark, eventType } = record;
    const { outputData } = functionJson;
    const value = {
      functionName,
      identifier,
      remark,
      outputData,
      eventType,
    };
    setFieldsValue(value);
  };

  async function getFormData() {
    const _values = (await validate()) as StructFormValue;
    const { functionName, remark, identifier, outputData: _outputData = [], eventType } = _values;
    if (!_values) return {} as unknown as ModelOfMatterParams;

    const outputData = (_outputData as unknown as StructJSON[]).map((item) => {
      const dataType = excludeIdInStructJSON(item.dataType!);
      return {
        ...item,
        dataType,
      };
    });

    const value = {
      functionName,
      identifier,
      remark,
      functionType: FunctionType.EVENTS,
      eventType,
      functionJson: {
        outputData,
      },
    } as ModelOfMatterParams;

    return value;
  }

  //清空数据
  const resetFormData = () => {
    resetFields();
  };

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