import { uniq } from 'lodash';
import { IMatterNode } from '@sc/types';

// 获取表单必填的字段名称
export const getRequiredFields = (data: any, nameList: string[] = []) => {
  if (!data) return [];
  for (const key in data.properties) {
    if (data.properties[key].name) {
      if (data.properties[key].required) nameList.push(data.properties[key].name);
    } else getRequiredFields(data.properties[key], nameList);
  }
  return uniq(nameList);
};

// 获取可编辑的表单
export const getEditAbleForms = (data: IMatterNode[]) => {
  const forms: any[] = [];
  data.forEach(d => {
    d.components.forEach(c => {
      if (c.name === 'form' && c.permission.editable) {
        forms.push(c.data);
      }
    });
  });
  return forms;
};

// 获取所有表单的所有必填字段
export const getAllRequiredFields = (matters: IMatterNode[]) => {
  const forms = getEditAbleForms(matters);
  if (!forms.length) return [];
  const requiredFieldNames: string[] = [];
  forms.forEach(form => {
    requiredFieldNames.push(...getRequiredFields(form));
  });
  return requiredFieldNames;
};
