<template>
  <el-form v-bind="getBindValue" :model="formModel" ref="formElRef">
    <el-row v-bind="getRow">
      <el-col
        v-bind="getCol"
        v-for="schema in getSchema"
        :key="schema.field"
        :span="getHidden(schema) ? 0 : getCol.span"
      >
        <el-form-item
          v-bind="schema"
          :label="schema.label"
          :prop="schema.field"
          :showFeedback="schema.showFeedback"
          v-if="!getHidden(schema)"
        >
          <!--标签名右侧温馨提示-->
          <template #label v-if="schema.labelMessage">
            <div class="flex items-center">
              {{ schema.label }}
              <el-tooltip
                trigger="hover"
                :style="schema.labelMessageStyle"
                :content="schema.labelMessage"
              >
                <el-icon size="18" class="ml-1 text-gray-400 cursor-pointer el-input__icon">
                  <QuestionCircleOutlined />
                </el-icon>
              </el-tooltip>
            </div>
          </template>

          <!--判断插槽-->
          <template v-if="schema.slot">
            <slot
              :name="schema.slot"
              :model="formModel"
              :field="schema.field"
              :value="formModel[schema.field]"
            ></slot>
          </template>

          <!--NCheckbox-->
          <template v-else-if="schema.component === 'Checkbox'">
            <el-checkbox-group
              v-bind="getSpecComponentProps(schema)"
              v-model="formModel[schema.field]"
              :class="{ isFull: schema.isFull != false && getProps.isFull }"
            >
              <el-space>
                <el-checkbox
                  v-for="item in schema.componentProps?.options"
                  :key="item.value"
                  :value="item.value"
                >
                  {{ item.label }}
                </el-checkbox>
              </el-space>
            </el-checkbox-group>
          </template>

          <!--elRadioGroup-->
          <template v-else-if="schema.component === 'RadioGroup'">
            <el-radio-group
              v-bind="getSpecComponentProps(schema)"
              v-model="formModel[schema.field]"
              :class="{ isFull: schema.isFull != false && getProps.isFull }"
            >
              <el-space>
                <el-radio
                  v-for="item in schema.componentProps?.options"
                  :key="item.value"
                  :value="item.value"
                >
                  {{ item.label }}
                </el-radio>
              </el-space>
            </el-radio-group>
          </template>

          <!--elSelect-->
          <template v-else-if="schema.component === 'Select'">
            <el-select
              v-bind="getSpecComponentProps(schema)"
              v-model="formModel[schema.field]"
              :class="{ isFull: schema.isFull != false && getProps.isFull }"
            >
              <el-option
                v-for="item in schema.componentProps?.options"
                :key="item.value"
                :value="item.value"
                :label="item.label"
              />
            </el-select>
          </template>

          <!--BasicSelect-->
          <template v-else-if="schema.component === 'BasicSelect'">
            <BasicSelect v-bind="getSpecComponentProps(schema)" v-model="formModel[schema.field]" />
          </template>

          <!--动态渲染表单组件-->
          <component
            v-else
            v-bind="getComponentProps(schema)"
            :is="`el-${schema.component}`"
            v-model="formModel[schema.field]"
            :type="schema.type"
          />
          <!--组件后面的内容-->
          <template v-if="schema.suffix">
            <slot
              :name="schema.suffix"
              :model="formModel"
              :field="schema.field"
              :value="formModel[schema.field]"
            ></slot>
          </template>
        </el-form-item>
      </el-col>
      <!--提交 重置 展开 收起 按钮-->
      <el-col :span="6" v-if="getProps.showActionButtonGroup">
        <el-form-item :label-width="isHorizontal ? '20px' : getProps.labelWidth">
          <el-space>
            <el-button
              v-if="getProps.showSubmitButton"
              v-bind="getSubmitBtnOptions"
              @click="handleSubmit"
              icon="Search"
              :loading="loadingSub"
              >{{ getProps.submitButtonText }}</el-button
            >
            <el-button
              v-if="getProps.showResetButton"
              v-bind="getResetBtnOptions"
              @click="resetFields"
              >{{ getProps.resetButtonText }}</el-button
            >
            <!-- <el-button
            type="primary"
            text
            icon-placement="right"
            v-if="isHorizontal  && getProps.showAdvancedButton"
            @click="unfoldToggle"
          >
            <template #icon>
              <el-icon size="14" class="el-input__icon unfold-icon" v-if="overflow">
                <DownOutlined />
              </el-icon>
              <el-icon size="14" class="el-input__icon unfold-icon" v-else>
                <UpOutlined />
              </el-icon>
            </template>
            {{ overflow ? '展开' : '收起' }}
          </el-button> -->
          </el-space>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>

<script lang="ts" setup>
  import { reactive, ref, useAttrs, computed, unref, onMounted, watch } from 'vue';
  import { createPlaceholderMessage } from './helper';
  import { useFormEvents } from './hooks/useFormEvents';
  import { useFormValues } from './hooks/useFormValues';
  import { BasicSelect } from '@/components/Select';

  import { basicProps } from './props';
  import { QuestionCircleOutlined } from '@vicons/antd';

  import type { Ref } from 'vue';
  import type { FormSchema, FormProps, FormActionType } from './types/form';

  import { isArray, isBoolean, isFunction } from '@/utils/is/index';
  import { deepMerge } from '@/utils';

  const props = defineProps({ ...basicProps });
  const emit = defineEmits(['reset', 'submit', 'register', 'advanced']);
  const attrs = useAttrs();

  const defaultFormModel = ref<Recordable>({});
  const formModel = reactive<Recordable>({});
  const propsRef = ref<Partial<FormProps>>({});
  const schemaRef = ref<Nullable<FormSchema[]>>(null);
  const formElRef = ref<Nullable<FormActionType>>(null);
  // const gridCollapsed = ref(!props.collapsed);
  const loadingSub = ref(false);
  const isUpdateDefaultRef = ref(false);

  const getSubmitBtnOptions = computed(() => {
    return Object.assign(
      {
        size: props.size,
        type: 'primary',
      },
      props.submitButtonOptions,
    );
  });

  const getResetBtnOptions = computed(() => {
    return Object.assign(
      {
        size: props.size,
        type: 'default',
      },
      props.resetButtonOptions,
    );
  });

  function getComponentProps(schema) {
    const compProps = schema.componentProps ?? {};
    const component = schema.component;
    return {
      class: schema.isFull != false && getProps.value.isFull ? 'w-full' : '',
      clearable: true,
      placeholder: createPlaceholderMessage(unref(component)),
      ...compProps,
    };
  }

  function getHidden(schema): boolean {
    const hidden = schema.hidden;
    const field = schema.field;
    if (isBoolean(hidden)) return hidden;

    if (isFunction(hidden)) {
      const values = getFieldsValue();
      const status = hidden({ schema, values, model: formModel, field });
      return status;
    }
    return false;
  }

  function getSpecComponentProps(schema) {
    const compProps = schema.componentProps ?? {};
    return {
      ...compProps,
    };
  }

  const getProps = computed((): FormProps => {
    const formProps = { ...props, ...unref(propsRef) } as FormProps;
    const rulesObj: any = {
      rules: {},
    };
    const schemas: any = formProps.schemas || [];
    schemas.forEach((item) => {
      if (item.rules && isArray(item.rules)) {
        rulesObj.rules[item.field] = item.rules;
      }
    });
    return { ...formProps, ...unref(rulesObj) };
  });

  const isHorizontal = computed(() => {
    const { layout } = unref(getProps);
    return layout === 'horizontal';
  });

  const getRow = computed(() => {
    const { rowProps } = unref(getProps);
    return {
      ...rowProps,
      // collapsed: isHorizontal .value ? gridCollapsed.value : false,
      // responsive: 'screen',
    };
  });

  const getCol = computed(() => {
    const { colProps } = unref(getProps);
    return {
      ...colProps,
      // collapsed: isHorizontal .value ? gridCollapsed.value : false,
      // responsive: 'screen',
    };
  });

  const getBindValue = computed(() => ({ ...attrs, ...props, ...unref(getProps) } as Recordable));

  const getSchema = computed((): FormSchema[] => {
    const schemas: FormSchema[] = unref(schemaRef) || (unref(getProps).schemas as any);
    for (const schema of schemas) {
      const { defaultValue } = schema;
      // handle date type
      // dateItemType.includes(component as string)
      if (defaultValue) {
        schema.defaultValue = defaultValue;
      }
    }
    return schemas as FormSchema[];
  });

  const { handleFormValues, initDefault } = useFormValues({
    defaultFormModel,
    getSchema,
    formModel,
  });

  const { handleSubmit, validate, resetFields, getFieldsValue, clearValidate, setFieldsValue } =
    useFormEvents({
      emit,
      getProps,
      formModel,
      getSchema,
      formElRef: formElRef as Ref<FormActionType>,
      defaultFormModel,
      loadingSub,
      handleFormValues,
    });

  // function unfoldToggle() {
  //   gridCollapsed.value = !gridCollapsed.value;
  //   emit('advanced', gridCollapsed.value);
  // }

  async function setProps(formProps: Partial<FormProps>): Promise<void> {
    propsRef.value = deepMerge(unref(propsRef) || {}, formProps);
  }

  async function setSchema(schemaProps: FormSchema[]): Promise<void> {
    schemaRef.value = schemaProps;
  }

  //更新loading状态
  function setLoadingSub(status: boolean): void {
    loadingSub.value = status;
  }

  const formActionType: Partial<FormActionType> = {
    getFieldsValue,
    setFieldsValue,
    resetFields,
    validate,
    clearValidate,
    setProps,
    setSchema,
    setLoadingSub,
    submit: handleSubmit,
  };

  watch(
    () => getSchema.value,
    (schema) => {
      if (unref(isUpdateDefaultRef)) {
        return;
      }
      if (schema?.length) {
        initDefault();
        isUpdateDefaultRef.value = true;
      }
    },
  );

  onMounted(() => {
    initDefault();
    emit('register', formActionType);
  });

  defineExpose({
    ...formActionType,
  });
</script>

<style lang="scss" scoped>
  .isFull {
    width: 100%;
    justify-content: flex-start;
  }

  .unfold-icon {
    display: flex;
    align-items: center;
    height: 100%;
    margin-left: -3px;
  }
</style>
