<!--
 * @Author: Devin
 * @Date: 2022-11-15 11:23:35
 * @LastEditors: Devin
 * @LastEditTime: 2023-02-22 14:51:28
 * @Description: ts工程开发
-->
<template>
  <el-form ref="ruleFormRef" :inline="true" label-width="auto">
    <!--form-->
    <template v-if="formType === 'form'">
      <el-row class="row" :gutter="20">
        <el-col
          v-for="(form, index) in forms"
          :key="index"
          :span="form?.['span'] || 12"
        >
          <form-item
            :form-item="form"
            @change-event="changeEvent"
            @input-event="inputEvent"
          ></form-item>
        </el-col>
        <el-col></el-col>
      </el-row>
    </template>

    <!-- search -->
    <template v-else>
      <el-row :gutter="20">
        <el-col
          v-for="formItem in forms"
          :key="formItem['name']"
          :span="formItem['col']"
        >
          <form-item
            :form-item="formItem"
            @change-event="changeEvent"
            @input-event="inputEvent"
          ></form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item class="form-last-btns">
            <slot name="btns"></slot>
          </el-form-item>
        </el-col>
      </el-row>
    </template>
  </el-form>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import type { FormInstance } from 'element-plus';
import FormItem from './FormItem.vue';

defineProps({
  forms: {
    type: Array,
    default: () => []
  },
  formType: {
    type: String,
    default: () => 'form'
  }
});
const emits = defineEmits(['changeEvent', 'blurEvent']);
const enteredNum = ref(0);
const isTextarea = ref(false);
const surplusNum = ref(0);

// 触发change事件
const changeEvent = (form: any) => {
  emits('changeEvent', form);
};

function inputEvent(form: any) {
  if (form?.type === 'input') {
    if (form?.attrs?.type === 'textarea' && form?.attrs?.maxlength > 0) {
      enteredNum.value = form.value?.length || 0;
      isTextarea.value = true;
      surplusNum.value =
        Number(form.attrs?.maxlength) - Number(enteredNum.value);
    }
  }
}

// 校验规则
const ruleFormRef = ref<FormInstance>();

function checkRules() {
  ruleFormRef.value.validate((valid) => {
    if (valid) {
      return true;
    }
    return false;
  });
}

defineExpose({
  ruleFormRef,
  checkRules
});
</script>

<script lang="ts">
export default {
  name: 'CommonForm'
};
</script>

<style lang="scss" scoped>
.row {
  margin-bottom: 20px;
}
.el-form-item {
  width: calc(100% - 24px);
  margin-top: 18px;
}
</style>
