<template>
  <template v-for="item in formItems" :key="item.title">
    <form-cell v-bind="item" :form="formModel" :disableChange="disabledMap[item.title]" @change="change" />
  </template>
</template>
<script setup>
import { computed, provide, ref } from 'vue';
import verifyForm from './verify.js';
import { createAliasedForm } from '@/utils/form-alias';

import FormCell from './form-cell/index.vue';

const emits = defineEmits(['change']);
const props = defineProps({
  form: {
    type: Object,
    default: () => ({})
  },
  items: {
    type: Array,
    default: () => []
  },
  disableTitles: {
    type: Array,
    default: () => ([])
  },
  rule: {
    type: Object,
    default: () => ({})
  },
  filterRule: {
    type: Object,
    default: () => ({})
  }
})

const disabledMap = computed(() => props.disableTitles.reduce((m, i) => {
  if (typeof i === 'string' && i.trim()) {
    m[i] = true;
  }
  return m
}, {}))

provide('addRule', addRule);

const customRule = ref({});

const formItems = computed(() => {
  return props.items
    .filter((i) => {
      if (!i) return false;
      const fn = props.filterRule && typeof props.filterRule[i.title] === 'function' ? props.filterRule[i.title] : null;
      return fn ? fn(props.form) : true;
    })
    .map((i) => ({ ...i }));
})

const formModel = computed(() => createAliasedForm(props.form, props.items));

const rules = computed(() => ({ ...customRule.value, ...props.rule }));

function addRule(arg1, arg2) {
  // 兼容两种调用方式：addRule({title, fn}) / addRule(title, fn)
  if (typeof arg1 === 'string' && typeof arg2 === 'function') {
    const title = arg1;
    const fn = arg2;
    if (title && props.items.some((i) => i.title === title)) customRule.value[title] = fn;
    return;
  }

  if (arg1 && typeof arg1 === 'object') {
    const title = arg1.title;
    const fn = arg1.fn;
    if (title && props.items.some((i) => i.title === title) && typeof fn === 'function') customRule.value[title] = fn;
  }
}

function change(data) {
  emits('change', data)
}

function verify() {
  const visible = formItems.value.filter((i) => i && !i.hidden);
  return verifyForm(visible, rules.value, formModel.value)
}

defineExpose({ verify })

</script>

<style>
@import './cell-style.css';
</style>
