<template>
  <div class="more-form-box" :style="{ overflowX: formWidth ? 'auto' : 'hidden' }">
    <div class="more-content" :style="{ width: formWidth ? formWidth + 'px' : '100%' }">
      <div>
        <a-tabs v-model:activeKey="activeKey" v-if="formDesignConfigList && formDesignConfigList.length > 1">
          <a-tab-pane :key="forIndex" :tab="forItem.formModelName" v-for="(forItem, forIndex) in formDesignConfigList"></a-tab-pane>
        </a-tabs>
      </div>
      <div>
        <a-form layout="vertical" style="height: 100%; width: 100%" ref="formRef" :model="props.form">
          <template v-for="(fItem, fIndex) in formDesignConfigList" :key="fIndex + 'form'">
            <form-viewer
              v-model:formData="props.form[fItem.formDefinitionId]"
              ref="formViewRef"
              :record="fItem"
              :isEdit="props.isEdit"
              :readonly="props.readonly"
              v-show="activeKey == fIndex"
            ></form-viewer>
          </template>
        </a-form>
      </div>
    </div>
  </div>
</template>

<script setup name="MoreFormViewer">
import { message } from 'ant-design-vue/es';
import { onMounted, ref } from 'vue';
import FormViewer from './form-viewer.vue';

const props = defineProps({
  // 表单配置列表
  formDesignConfigList: {
    type: Array,
    default: []
  },
  // 表单数据
  form: Object,
  // 是否是编辑
  isEdit: {
    type: Boolean,
    default: false
  },
  // 是否只读
  readonly: {
    type: Boolean,
    default: false
  }
});

const activeKey = ref(0);

// 表单宽度
const formWidth = ref(null);

// ref
const formRef = ref();
const formViewRef = ref();

onMounted(() => {
  if (props.formDesignConfigList?.length > 0) {
    formWidth.value = props.formDesignConfigList[0].formConfig?.formWidth || null;
  }
});

// 校验是否必填
const validate = () => {
  return new Promise((resolve, reject) => {
    let arr = [];
    formViewRef.value.forEach((key, index) => {
      arr.push(key.$refs.formRef.validate());
    });

    Promise.all(arr)
      .then(result => {
        if (result.indexOf(false) >= 0) {
          resolve(false);
        } else {
          resolve(true);
        }
      })
      .catch(e => {
        message.warning(e.errorFields[0].errors[0]);
        reject(e);
      });
  });
};

defineExpose({
  validate
});
</script>

<style scoped lang="less">
.more-form-box {
  width: 100%;
  height: 100%;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}
.more-form-content {
  display: flex;
  flex: auto;
  overflow-y: auto;
  overflow-x: hidden;
}
.more-content {
  height: 100%;
  background-color: #fff;
}
:deep(.ant-tabs-nav-wrap) {
  justify-content: center;
}
:deep(.ant-tabs-tab) {
  // font-size: 16px !important;
  font-weight: 400;
  padding: 8px 16px !important;
}
</style>
