import { cloneDeep } from 'lodash-es';
import { DataTypeEnum } from './config';
import { StructFormValue } from './type';
import { DataType, ModelOfMatterParams, StructJSON } from '/@/api/device/model/modelOfMatterModel';
import { isArray } from '/@/utils/is';

export function transfromToStructJSON(value: StructFormValue): StructJSON {
  const {
    type,
    valueRange,
    step,
    length = '',
    boolClose,
    boolOpen,
    unit,
    unitName,
    functionName,
    identifier,
    remark,
    specs,
    accessMode,
  } = value;
  const basic = { functionName, identifier, remark, accessMode };
  let dataType = {} as unknown as DataType;

  switch (type) {
    case DataTypeEnum.IS_NUMBER_INT:
      dataType = {
        type,
        specs: { valueRange, step, unit, unitName },
      };
      break;

    case DataTypeEnum.IS_NUMBER_DOUBLE:
      dataType = {
        type,
        specs: { valueRange, step, unit, unitName },
      };
      break;

    case DataTypeEnum.IS_BOOL:
      dataType = {
        type,
        specs: {
          boolOpen: boolOpen,
          boolClose: boolClose,
        },
      };
      break;

    case DataTypeEnum.IS_STRING:
      dataType = {
        type,
        specs: { length },
      };
      break;

    case DataTypeEnum.IS_STRUCT:
      dataType = {
        type,
        specs: specs! as unknown as ModelOfMatterParams[],
      };
      break;
  }
  return { ...basic, dataType };
}

export const excludeIdInStructJSON = (struct: DataType) => {
  const _value = cloneDeep(struct);
  const { specs } = _value;
  const list = [specs];

  while (list.length) {
    for (const item of list) {
      if (isArray(item)) {
        (item as StructJSON[]).forEach((temp) => {
          if (temp.dataType?.specs) {
            list.push(temp.dataType.specs);
          }
          Reflect.deleteProperty(temp, 'id');
        });
      } else {
        Reflect.deleteProperty(item as Recordable, 'id');
      }
      list.shift();
    }
  }

  return _value;
};
