<template>
  <v-form ref="formRef" v-model="valid" class="login-form" @submit.prevent>
    <div>
      <v-row dense no-gutters class="justify-space-between">
        <template v-for="(item) in props.items.options">
          <slot :name="item.prevSlot"></slot>
          <v-col :key="item.key" v-if="!item.hide" :cols="item.col || '12'" class="position">
            <template v-if="item.slotTitle">
              <div :class="item.class" :style="item.slotTitleStyle">{{ item.slotTitle }}</div>
            </template>
            <div class="d-flex" :class="item.flexStyle || 'flex-row'">
              <span>{{ item.value }}</span>
              <textUI
                v-if="['text', 'password', 'number'].includes(item.type)"
                v-model="item.value"
                :item="item"
                @change="handleChange(item)"
              ></textUI>
              <autocompleteUI
                v-if="item.type === 'autocomplete'"
                v-model="item.value"
                :item="item"
                @change="handleChange(item)"
              ></autocompleteUI>
              <template v-if="item.slotName">
                <slot :name="item.slotName" :item="item"></slot>
              </template>
            </div>
          </v-col>
        </template>
      </v-row>
    </div>
    <slot></slot>
  </v-form>
</template>
<script setup>
defineOptions({ name:'components-ct-form'})
import textUI from './../FormUI/TextInput'
import autocompleteUI from './../FormUI/autocomplete'
import { ref, defineEmits } from 'vue'
const emit = defineEmits(['change', 'inputUpdateAutocomplete'])// 定义一个或多个自定义事件
const props = defineProps({items: Object})
const valid = ref(false)
const isValid = ref(true)
const formRef = ref()

const handleChange = (item) => {
  // console.log('handleChange', item)
  if (item.type === 'date' && item.value) item.option.validate = false
  if (item?.change) item.change(item.value, item)
  emit('change', false)
}

const validateTime = () => {
  isValid.value = true
  props.items.options.forEach((e) => {
    if (e.type !== 'date' || e.hide || !e.rules) return
    const rules = e.rules[0]
    const check = rules(e.value)
    if (typeof check === 'string') {
      isValid.value = false
      e.option.error = true
      e.option.errorMsg = check
    } else {
      e.option.error = false
      e.option.errorMsg = null
    }
  })
}
  
const validate = () => {
  const form = formRef.value.validate()
  const time = validateTime()
  return form && time
}
defineExpose({
  validate
})
</script>
<style lang="scss" scoped>
.position {
  position: relative;
}
.label {
  font-size: 14px;
  color: rgba(0, 0, 0, .6);
}
</style>