<template>
  <div>
    <Col v-for="(col, colIndex) in children" :key="colIndex" :span="col.span">
      <template v-for="(schema, key) in col.list" :key="key">
        <template v-if="schema.component.includes('Range')">
          <SimpleFormItem
            :schema="schema"
            :value="
              convertToDayjs(
                formModel[spiltRangeDateField(schema.field)[0]],
                formModel[spiltRangeDateField(schema.field)[1]],
              )
            "
            :form-props="formProps"
            v-model:value="formModel[schema.field]"
            v-model:startTime="formModel[spiltRangeDateField(schema.field)[0]]"
            v-model:endTime="formModel[spiltRangeDateField(schema.field)[1]]"
          />
        </template>
        <template v-else>
          <SimpleFormItem
            :schema="schema"
            :form-props="formProps"
            v-model:value="formModel[schema.field]"
          />
        </template>
      </template>
    </Col>
  </div>
</template>
<script lang="ts" setup>
  import { Col } from 'ant-design-vue';
  import dayjs, { Dayjs } from 'dayjs';
  import { trim } from 'lodash-es';
  import { reactive, watch } from 'vue';
  import SimpleFormItem from './SimpleFormItem.vue';
  import { FormSchema, GridComponentProps, FormProps } from '/@/components/Form';

  const props = defineProps({
    // 表单配置规则
    config: {
      type: Object as PropType<FormSchema>,
      default: () => {},
    },
    //整个表单配置
    formProps: {
      type: Object as PropType<FormProps>,
      default: () => ({}),
    },
    //子组件
    children: {
      type: Array as PropType<GridComponentProps[]>,
      default: () => [],
    },
    //表单数据
    formModel: {
      type: Object as PropType<Recordable>,
      default: () => {},
    },
  });

  const formModel = reactive<Recordable>(props.formModel);

  /**
   * 当有range组件 schema的field格式为 startTime,endTime  默认逗号隔开  开始时间在前 结束时间在后
   */
  const spiltRangeDateField = (field: string): string[] => {
    return field.split(',').map(trim);
  };

  const convertToDayjs = (
    startTime: string,
    endTime: string,
    format = 'YYYY-MM-DD',
  ): [Dayjs, Dayjs] => {
    return [dayjs(startTime, format), dayjs(endTime, format)];
  };

  const emit = defineEmits(['update:formModel']);

  watch(
    () => formModel,
    () => {
      emit('update:formModel', formModel);
    },
  );
</script>
