<script lang="ts">
  export default {
    inheritAttrs: false,
  };
</script>
<script lang="ts" setup>
  import { BasicForm, useForm } from '/@/components/Form';
  import { formSchemas } from './config';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { OpenModalMode, OpenModalParams, StructRecord } from './type';
  import { ref, unref } from 'vue';
  import { transfromToStructJSON } from './util';
  import { cloneDeep } from 'lodash-es';
  import { DataType, StructJSON } from '/@/api/device/model/modelOfMatterModel';
  import { isArray } from '/@/utils/is';
  import { useMessage } from '/@/hooks/web/useMessage';

  const modalReceiveRecord = ref<OpenModalParams>({
    mode: OpenModalMode.CREATE,
  });

  const props = defineProps<{
    disabled: boolean;
    hasStructForm: boolean;
    valueList: StructRecord[];
  }>();

  const emit = defineEmits(['register', 'submit']);

  const { createMessage } = useMessage();

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

  const [registerModal, { closeModal }] = useModalInner((record: OpenModalParams) => {
    modalReceiveRecord.value = record;
    const data = record.record || {};
    const { dataType = {} } = data! as StructJSON;
    const { specs = {}, type } = dataType as DataType;

    if (record.record) {
      const value = {
        type,
        ...data,
        ...(isArray(specs) ? { specs } : { ...specs }),
      };

      setFieldsValue(value);
    }
    setProps({ disabled: props.disabled });
  });

  const validateRepeat = (value: StructRecord, valueList: StructRecord[]) => {
    return valueList.filter((item) => item.identifier === value.identifier).length >= 1;
  };

  const handleSubmit = async () => {
    try {
      const _value = await validate();
      let structJSON = transfromToStructJSON(_value);
      const value = {
        ...structJSON,
        ...(unref(modalReceiveRecord)?.record?.id
          ? { id: unref(modalReceiveRecord)?.record?.id }
          : {}),
      };

      if (validateRepeat(_value, props.valueList)) {
        createMessage.error('存在一致的标识符');
        return;
      }

      emit('submit', unref(modalReceiveRecord).mode, cloneDeep(value));
      closeModal();
    } catch (error) {}
  };
</script>

<template>
  <BasicModal
    @register="registerModal"
    :title="modalReceiveRecord.mode === OpenModalMode.CREATE ? '创建参数' : '编辑参数'"
    :width="800"
    @ok="handleSubmit"
    destroy-on-close
    :show-ok-btn="!$props.disabled"
  >
    <BasicForm @register="register" />
  </BasicModal>
</template>

<style lang="less" scoped></style>
