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

  const props = defineProps<{
    record: DeviceRecord;
    openModalMode: OpenModelMode;
  }>();

  const [register, { validate, resetFields, setFieldsValue, setProps }] = useForm({
    labelWidth: 100,
    schemas: serviceSchemas(props.record.transportType === 'TCP'),
    actionColOptions: {
      span: 14,
    },
    disabled: props.openModalMode === OpenModelMode.VIEW,
    showResetButton: false,
    submitOnReset: false,
    showActionButtonGroup: false,
  });

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

  //回显数据
  const setFormData = (record: ModelOfMatterParams) => {
    const { functionJson = {}, functionName, identifier, remark, callType } = record;
    const { inputData = [], outputData } = functionJson;
    const { serviceCommand } =
      (inputData.at(0) as unknown as { serviceCommand: string }) ||
      ({} as { serviceCommand: string });
    const value = {
      functionName,
      identifier,
      remark,
      inputData,
      outputData,
      serviceCommand,
      callType,
    };
    setFieldsValue(value);
  };

  //获取数据
  async function getFormData() {
    const _values = (await validate()) as StructFormValue;
    const {
      functionName,
      remark,
      identifier,
      inputData: _inputData = [],
      outputData: _outputData = [],
      serviceCommand,
      callType,
    } = _values;
    if (!_values) return {};

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

    const value = {
      functionName,
      identifier,
      remark,
      functionType: FunctionType.SERVICE,
      callType,
      functionJson: {
        inputData,
        outputData,
        ...(serviceCommand ? { inputData: [{ serviceCommand }] } : {}),
      },
    } as ModelOfMatterParams;

    return value;
  }

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

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