<template>
  <div>
    <!--如果是grid 组件 需要新增grid布局包裹-->
    <template v-if="schema.component.includes('Grid')">
      <Row
        type="flex"
        :gutter="(schema.componentProps as any ).gutter ?? 0"
        :justify="(schema.componentProps as any ).justify"
        :align="(schema.componentProps as any ).align"
        v-show="getIsShow(schema)"
        :class="{ 'grid-box': getIsShow(schema) }"
        :style="{
          padding: schema.componentProps.padding || '10px',
          margin: schema.componentProps.margin || '0 0 10px ',
        }"
      >
        <Col v-for="(col, colIndex) in schema.children" :key="colIndex" :span="col.span">
          <template v-for="childSchema in col.list" :key="childSchema.field">
            <SimpleFormItem
              v-if="showComponent(childSchema)"
              :refreshFieldObj="refreshFieldObj"
              :form-api="formApi"
              :schema="childSchema"
              v-model:value="formModel![childSchema.field]"
              :label-col="labelCol"
              :isWorkFlow="isWorkFlow"
              :slots="props.slots"
              ref="gridFormItemRefs"
            />
          </template>
        </Col>
      </Row>
    </template>
    <!--如果是tab 组件 需要新增tab组件包裹-->
    <template v-else-if="schema.component === 'Tab'">
      <Tabs
        v-model:activeKey="activeKey"
        :tabPosition="(schema.componentProps as any ).tabPosition"
        :type="(schema.componentProps as any ).type"
        :size="(schema.componentProps as any ).tabSize"
        v-show="getIsShow(schema)"
        :id="`simptabs-${schema.key}`"
        @change="handleTabsChange"
      >
        <TabPane v-for="(tab, tabIndex) in schema.children" :forceRender="true" :key="tabIndex">
          <template #tab>
            <div :style="`background: url(${tab.imageUrl}) no-repeat`">
              <Icon :icon="tab.prefix" v-if="tab.prefix" />
              <span
                :style="`color:${activeKey == tabIndex ? tab.activeColor : 'rgba(0, 0, 0, 0.85)'}`"
                >{{ tab.name }}</span
              >
              <Icon :icon="tab.suffix" v-if="tab.suffix" class="!mr-0 ml-3" />
            </div>
          </template>
          <div :style="`background: url(${tab.conImageUrl}) no-repeat`">
            <div v-for="childSchema in tab.list" :key="childSchema.field">
              <SimpleFormItem
                v-if="showComponent(childSchema)"
                :refreshFieldObj="refreshFieldObj"
                :form-api="formApi"
                :schema="childSchema"
                :isWorkFlow="isWorkFlow"
                v-model:value="formModel![childSchema.field]"
                :slots="props.slots"
                ref="gridFormItemRefs"
              />
            </div>
          </div>
        </TabPane>
      </Tabs>
    </template>
    <!--如果是子表单 组件 需要v-model:value="表单对象[字段名]"-->
    <template v-else-if="schema.component.includes('Form') && schema.component !== 'SelectForm'">
      <FormItem
        :key="schema.key"
        :name="schema.field"
        :label="getComponentsProps.showLabel ? schema.label : ''"
        :label-col="labelCol"
        :labelAlign="formProps?.labelAlign"
        :wrapperCol="itemLabelWidthProp.wrapperCol"
        v-if="getShow(schema)"
        v-show="getIsShow(schema)"
      >
        <component
          :disabled="getDisable"
          :key="schema.component==='FormView'?refreshFieldObj[schema.field!]:refreshFieldObj[schema.key!]"
          :refreshFieldObj="refreshFieldObj[schema.field!]"
          :is="formComponent(schema)"
          :size="formProps?.size"
          :form-api="formApi"
          :tableName="schema.label"
          v-bind="schema.componentProps"
          v-model:value="formModel![schema.field]"
          :slots="props.slots"
          :isView="getIsView"
          ref="tableFormRefs"
        />
      </FormItem>
    </template>
    <!--如果是子表单 组件 需要v-model:value="表单对象[字段名]"-->
    <template v-else-if="schema.component.includes('OneForOne')">
      <FormItem
        :key="schema.key"
        :name="schema.field"
        :label="getComponentsProps.showLabel ? schema.label : ''"
        :label-col="labelCol"
        :labelAlign="formProps?.labelAlign"
        :wrapperCol="itemLabelWidthProp.wrapperCol"
        v-if="getShow(schema)"
        v-show="getIsShow(schema)"
      >
        <component
          :disabled="getDisable"
          :refreshFieldObj="refreshFieldObj"
          :is="componentMap.get(schema.component)"
          :size="formProps?.size"
          :form-api="formApi"
          v-bind="schema.componentProps"
          v-model:value="formModel![schema.field]"
          :slots="props.slots"
          :isView="getIsView"
        />
      </FormItem>
    </template>
    <template v-else-if="schema.component === 'TableLayout'">
      <TableLayoutPreview :element="schema" v-if="getShow(schema)" v-show="getIsShow(schema)">
        <template #tdElement="{ tdElement }">
          <div class="h-full">
            <div
              :style="{
                height: tdElement.height ? tdElement.height + 'px' : '',
                minHeight: (tdElement.height || '42') + 'px',
                overflow: 'hidden',
                padding: '10px',
              }"
            >
              <template v-for="childSchema in tdElement.children" :key="childSchema.field">
                <SimpleFormItem
                  v-if="showComponent(childSchema)"
                  :refreshFieldObj="refreshFieldObj"
                  :form-api="formApi"
                  :schema="childSchema"
                  :isWorkFlow="isWorkFlow"
                  v-model:value="formModel![childSchema.field]"
                  :slots="props.slots"
                  ref="gridFormItemRefs"
                />
              </template>
            </div>
          </div>
        </template>
      </TableLayoutPreview>
    </template>
    <!--如果是时间区间 组件 需要v-model:startField="表单对象[字段名]" v-model:endField="表单对象[字段名]"-->
    <template v-else-if="schema.component.includes('Range')">
      <FormItem
        :key="schema.key"
        :name="schema.field"
        :label="getComponentsProps.showLabel ? schema.label : ''"
        :label-col="labelCol"
        :wrapperCol="itemLabelWidthProp.wrapperCol"
        :validateTrigger="['blur', 'change']"
        :rules="rules"
        v-if="getShow(schema)"
        v-show="getIsShow(schema)"
      >
        <TooltipWrapper :tooltipConfig="getTooltipConfig">
          <component
            :disabled="getDisable"
            :is="componentMap.get(schema.component)"
            :size="formProps?.size"
            v-bind="schema.componentProps"
            v-model:startField="schema.field.split(',')[0]"
            v-model:endField="schema.field.split(',')[1]"
            v-model:value="formModel![schema.field]"
          />
        </TooltipWrapper>
      </FormItem>
      <!-- 因为Range会变为 开始时间 和 结束时间 2个属性给与表单数据 所以需要2个隐藏框绑定  starTime  和 endTime -->
      <FormItem
        :key="schema.key"
        v-show="false"
        :name="schema.field.split(',')[0]"
        :label="getComponentsProps.showLabel ? schema.label : ''"
      >
        <input type="hidden" />
      </FormItem>
      <FormItem
        :key="schema.key"
        v-show="false"
        :name="schema.field.split(',')[1]"
        :label="getComponentsProps.showLabel ? schema.label : ''"
      >
        <input type="hidden" />
      </FormItem>
    </template>
    <!--如果checked  或者 switch组件 需要v-model:checked="表单对象[字段名]" "-->
    <template v-else-if="checkedValueComponents.includes(schema.component)">
      <FormItem
        :key="schema.key"
        :name="schema.field"
        :label="getComponentsProps.showLabel ? schema.label : ''"
        :label-col="labelCol"
        :wrapperCol="itemLabelWidthProp.wrapperCol"
        :rules="rules"
        v-if="getShow(schema)"
        v-show="getIsShow(schema)"
      >
        <TooltipWrapper :tooltipConfig="getTooltipConfig">
          <component
            :key="refreshFieldObj[schema.field]"
            :is="componentMap.get(schema.component)"
            :disabled="getDisable"
            :size="formProps?.size"
            v-bind="getComponentsProps"
            v-model:checked="formModel![schema.field]"
          />
        </TooltipWrapper>
      </FormItem>
    </template>
    <!--如果是card 组件 需要新增card组件包裹-->
    <template v-else-if="schema.component.includes('Card')">
      <CustomCollapseContainer
        :title="(schema.componentProps as any ).title"
        :bordered="false"
        :hasLeftBorder="true"
        :iconStyle="{ fontSize: '12px' }"
        :cardStyle="(schema.componentProps as any ).cardStyle"
        v-show="getIsShow(schema)"
      >
        <template v-for="childSchema  in schema.children![0].list" :key="childSchema.field">
          <SimpleFormItem
            v-if="showComponent(childSchema)"
            :refreshFieldObj="refreshFieldObj"
            :form-api="formApi"
            :schema="childSchema"
            :isWorkFlow="isWorkFlow"
            v-model:value="formModel![childSchema.field]"
            :slots="props.slots"
            ref="gridFormItemRefs"
          />
        </template>
      </CustomCollapseContainer>
    </template>
    <!--如果是 分割线 组件 需要新增divider组件包裹-->
    <template v-else-if="schema.component.includes('Divider')">
      <FormItem v-show="getIsShow(schema)">
        <Divider v-bind="getComponentsProps"> {{ getComponentsProps.text }}</Divider>
      </FormItem>
    </template>
    <!--如果是 意见簿 组件 需要使用defaultValue直接赋值 -->
    <template v-else-if="schema.component.includes('Opinion')">
      <FormItem
        v-if="getShow(schema)"
        v-show="getIsShow(schema)"
        :key="schema.key"
        :name="schema.field"
        :label="getComponentsProps.showLabel ? schema.label : ''"
        :label-col="labelCol"
        :wrapperCol="itemLabelWidthProp.wrapperCol"
        :rules="rules"
        :validateTrigger="['blur', 'change']"
      >
        <TooltipWrapper :tooltipConfig="getTooltipConfig">
          <component
            :is="componentMap.get(schema.component)"
            :key="refreshFieldObj[schema.field]"
            :disabled="getDisable"
            :size="formProps?.size"
            v-bind="getComponentsProps"
            :value="schema.defaultValue"
          />
        </TooltipWrapper>
      </FormItem>
    </template>

    <!--如果是 iframe 组件 需要使用defaultValue直接赋值 -->

    <template v-else-if="schema.component.includes('XjrIframe')">
      <FormItem
        v-if="getShow(schema)"
        v-show="getIsShow(schema)"
        :key="schema.key"
        :name="schema.field"
        :label="getComponentsProps.showLabel ? schema.label : ''"
        :label-col="labelCol"
        :wrapperCol="itemLabelWidthProp.wrapperCol"
        :rules="rules"
        :validateTrigger="['blur', 'change']"
      >
        <component
          :is="componentMap.get(schema.component)"
          :id="schema.key"
          :disabled="getDisable"
          :size="formProps?.size"
          v-bind="getComponentsProps"
          :value="schema.defaultValue"
          ref="formItemRefs"
        />
      </FormItem>
    </template>
    <template
      v-else-if="schema.component === 'XjrCustomModal' || schema.component === 'XjrCustomDrawer'"
    >
      <FormItem
        v-if="getShow(schema)"
        v-show="getIsShow(schema)"
        :key="schema.key"
        :name="schema.field"
        :label="getComponentsProps.showLabel ? schema.label : ''"
        :label-col="labelCol"
        :wrapperCol="itemLabelWidthProp.wrapperCol"
        :rules="rules"
        :validateTrigger="['blur', 'change']"
        :style="getComponentsProps.formItemStyle || {}"
      >
        <TooltipWrapper :tooltipConfig="getTooltipConfig">
          <component
            :is="defaultComponent(schema)"
            :disabled="getDisable"
            :isView="getIsView"
            :size="formProps?.size"
            :title="schema.label"
            :componentKey="schema.key"
            :mainformModel="formModel"
            v-bind="getComponentsProps"
            ref="customModalRefs"
          />
        </TooltipWrapper>
      </FormItem>
    </template>
    <template v-else-if="schema.component.includes('Slot')">
      <FormItem
        v-if="getShow(schema)"
        v-show="getIsShow(schema)"
        :key="schema.key"
        :name="schema.field"
        :label="getComponentsProps.showLabel ? schema.label : ''"
        :label-col="labelCol"
        :wrapperCol="itemLabelWidthProp.wrapperCol"
        :rules="rules"
        :validateTrigger="['blur', 'change']"
      >
        <component
          :is="props.slots![schema.slot!]"
          :key="refreshFieldObj[schema.field]"
          :disabled="getDisable"
          :size="formProps?.size"
          v-bind="getComponentsProps"
          v-model:value="formModel![schema.field]"
          :formModel="formModel"
          :field="schema.field"
        />
      </FormItem>
    </template>
    <template v-else>
      <FormItem
        v-if="getShow(schema)"
        v-show="getIsShow(schema)"
        :key="schema.key"
        :name="schema.field"
        :label="getComponentsProps.showLabel ? schema.label : ''"
        :label-col="labelCol"
        :wrapperCol="itemLabelWidthProp.wrapperCol"
        :rules="rules"
        :validateTrigger="['blur', 'change']"
        :style="getComponentsProps.formItemStyle || {}"
      >
        <TooltipWrapper :tooltipConfig="getTooltipConfig">
          <component
            :is="defaultComponent(schema)"
            :key="refreshFieldObj[schema.field]"
            :disabled="getDisable"
            :isView="getIsView"
            :size="formProps?.size"
            :componentKey="schema.key"
            v-bind="getComponentsProps"
            v-model:value="formModel![schema.field]"
          />
        </TooltipWrapper>
      </FormItem>
    </template>
  </div>
</template>
<script lang="ts" setup>
  import { Form, Col, Row, Tabs, TabPane, Divider } from 'ant-design-vue';
  import { isBoolean, isFunction, upperFirst, cloneDeep } from 'lodash-es';
  import { computed, onMounted, unref, inject, Ref, watch, ref } from 'vue';
  import { componentMap } from '/@/components/Form/src/componentMap';
  import { checkedValueComponents } from '/@/components/Form/src/helper';
  import { useItemLabelWidth } from '/@/components/Form/src/hooks/useLabelWidth';
  import { FormActionType, FormProps, FormSchema } from '/@/components/Form/src/types/form';
  import { CustomCollapseContainer } from '/@/components/Container';
  import {
    noShowWorkFlowComponents,
    noShowGenerateComponents,
  } from '/@/components/Form/src/helper';
  import { useMessage } from '/@/hooks/web/useMessage';
  import TableLayoutPreview from '/@/components/Form/src/components/TableLayoutPreview.vue';
  //import { camelCaseString } from '/@/utils/event/design';
  import { getFileList } from '/@/api/system/file';
  import { primaryColor } from '../../../../../build/config/themeConfig';
  import { Icon } from '/@/components/Icon';
  import { getFileUrl } from '/@/utils/event/design';
  import { TooltipWrapper } from '/@/components/ModalPanel/index';

  const FormItem = Form.Item;
  const props = defineProps({
    // 表单配置规则
    schema: {
      type: Object as PropType<FormSchema>,
      default: () => {},
    },
    value: [Object, String, Number, Boolean, Array],
    formApi: {
      type: Object as PropType<FormActionType>,
    },
    //刷新api使用
    refreshFieldObj: {
      type: Object,
      default: () => {},
    },
    //是否是工作流
    isWorkFlow: {
      type: Boolean,
      default: false,
    },
    //插槽节点
    slots: [Object, Array],
  });

  let formItemRefs = ref() as any;
  const tableFormRefs = ref() as any;
  const customModalRefs = ref() as any;
  const gridFormItemRefs = ref() as any;
  const formModel = inject<Recordable>('formModel');
  const formProps = inject<Ref<FormProps>>('formProps');
  // const tabActiveKey = inject<Ref<number>>('tabActiveKey', ref(0));
  const activeKey = ref<number>(0);
  //const isCamelCase = inject<boolean>('isCamelCase', false);
  // watch(
  //   () => tabActiveKey?.value,
  //   (val) => {
  //     if (props.isWorkFlow) activeKey.value = val!;
  //   },
  //   {
  //     immediate: true,
  //   },
  // );
  // watch(
  //   () => activeKey?.value,
  //   (val) => {
  //     if (props.isWorkFlow) tabActiveKey.value = val!;
  //   },
  //   {
  //     immediate: true,
  //   },
  // );

  // watch(
  //   () => props.value,
  //   (val) => {
  //     if (!val) return;
  //     let { componentProps = {} } = props.schema;
  //     if (componentProps['events']) {
  //       for (const eventKey in componentProps['events']) {
  //         try {
  //           const event = new Function(
  //             'schema',
  //             'formModel',
  //             'formActionType',
  //             `${componentProps['events'][eventKey]}`,
  //           );
  //           event(props.schema, formModel, props.formApi);
  //         } catch (error) {
  //           notification.error({
  //             message: 'Tip',
  //             description: '触发事件填写有误！',
  //           });
  //         }
  //       }
  //     }
  //   },
  //   {
  //     immediate: true,
  //   },
  // );

  const { notification } = useMessage();
  const getSchema = computed(() => {
    return props.schema as FormSchema;
  });

  const getDisable = computed(() => {
    const { disabled: globDisabled } = formProps!.value;
    const { dynamicDisabled } = getSchema.value;
    const { disabled: itemDisabled = false } = unref(getComponentsProps);
    let disabled = !!globDisabled || itemDisabled;
    if (isBoolean(dynamicDisabled)) {
      disabled = dynamicDisabled;
    }
    if (isFunction(dynamicDisabled)) {
      disabled = dynamicDisabled({
        values: formModel![getSchema.value.field],
        model: formModel!,
        schema: unref(getSchema),
        field: unref(getSchema).field,
      });
    }
    return disabled;
  });
  const getIsView = computed(() => {
    const { disabled: globDisabled } = formProps!.value;
    const { dynamicDisabled } = getSchema.value;

    let disabled = !!globDisabled;
    if (isBoolean(dynamicDisabled)) {
      disabled = dynamicDisabled;
    }
    if (isFunction(dynamicDisabled)) {
      disabled = dynamicDisabled({
        values: formModel![getSchema.value.field],
        model: formModel!,
        schema: unref(getSchema),
        field: unref(getSchema).field,
      });
    }
    return disabled;
  });
  const getTooltipConfig = computed(() => {
    let { componentProps = {} } = props.schema;
    return {
      ...componentProps?.tooltipConfig,
      visible: componentProps?.tooltipConfig?.visible ?? false,
    };
  });
  const getComponentsProps = computed(() => {
    let { componentProps = {} } = props.schema;

    if (isFunction(componentProps)) {
      componentProps =
        componentProps({
          schema: props.schema,
          formModel,
          formActionType: props.formApi,
        }) ?? {};
    }
    if (componentProps['events']) {
      for (const eventKey in componentProps['events']) {
        try {
          const event = new Function(
            'schema',
            'formModel',
            'formActionType',
            'eventData',
            'options',
            `${componentProps['events'][eventKey]}`,
          );
          // let cloneFormModel = cloneDeep(formModel);

          // for (let item in cloneFormModel) {
          //   let field = camelCaseString(item);
          //   if (field) cloneFormModel[field] = cloneFormModel[item];
          // }
          if (isFunction(componentProps['events'][eventKey])) {
            componentProps['on' + upperFirst(eventKey)] = function (e, opt) {
              componentProps['events'][eventKey](props.schema, formModel, props.formApi, e, opt);
            };
          } else {
            componentProps['on' + upperFirst(eventKey)] = function (e, opt) {
              try {
                event(props.schema, formModel, props.formApi, e, opt);
              } catch (error) {}

              // if (isCamelCase) {
              //   for (let item in formModel) {
              //     let field = camelCaseString(item);
              //     if (cloneFormModel && field && cloneFormModel[field] !== undefined) {
              //       formModel[item] = cloneFormModel[field];
              //     }
              //   }
              // }
            };
          }
        } catch (error) {
          notification.error({
            message: 'Tip',
            description: '触发事件填写有误！',
          });
        }
      }
    }
    if (isBoolean(props.schema.dynamicDisabled)) {
      componentProps['disabled'] = props.schema.dynamicDisabled;
    }
    if (isBoolean(props.schema.required)) {
      componentProps['required'] = props.schema.required;
    }

    if (props.schema.component == 'Button') {
      componentProps.formItemStyle = { margin: 0 };
    }
    return componentProps as Recordable;
  });

  const labelCol = computed(() => {
    return unref(getComponentsProps).span
      ? { span: unref(getComponentsProps).span }
      : unref(itemLabelWidthProp).labelCol;
  });

  const checkSign = (_, value) => {
    if (value && typeof value === 'string' && JSON.parse(value)) {
      const values = Object.values(JSON.parse(value));
      const hasNoSign = values.some((item) => !item);
      return hasNoSign ? Promise.reject(`${props.schema.label}是必填项`) : Promise.resolve();
    }
    return Promise.resolve();
  };

  const rules = computed(() => {
    const requiredRule = {
      required: unref(getComponentsProps).required || false,
      message: `${props.schema.label}是必填项`,
    };
    if (
      props.schema.type === 'signature' &&
      (props.schema.required || props.schema.componentProps?.required)
    ) {
      const rules = { validator: checkSign };
      return [requiredRule, rules];
    }
    const rulesList = cloneDeep(unref(getComponentsProps).rules);
    if (!rulesList) return [requiredRule];
    rulesList?.map((item) => (item.pattern = eval(item.pattern)));
    return [...rulesList, requiredRule];
  });

  //根据labelwidth 生成labelCol
  const itemLabelWidthProp = useItemLabelWidth(getSchema, formProps!);
  watch(
    () => formModel,
    () => {
      // console.log('formitem watch!!!!!!!!');
      //填值以后需要手动校验的组件
      const validateComponents = [
        'Role',
        'User',
        'RichTextEditor',
        'Upload',
        'SelectMap',
        'Signature',
        'SelectForm',
        'SelectDesignList',
      ];
      if (validateComponents.includes(props.schema.component) && formModel![props.schema.field]) {
        setTimeout(() => {
          props.formApi?.validateFields([props.schema.field]);
        }, 100);
      }
    },
    {
      deep: true,
    },
  );
  onMounted(() => {
    if (props.schema.type == 'tab') {
      handleTabsChange(0);
      props.schema.children.forEach((o) => {
        if (o.folderId) {
          getFileList({ folderId: o.folderId }).then((fileList) => {
            if (fileList.length) {
              o.imageUrl = getFileUrl(fileList[0]);
            }
          });
        }
        if (o.conFolderId) {
          getFileList({ folderId: o.conFolderId }).then((fileList) => {
            if (fileList.length) {
              o.conImageUrl = getFileUrl(fileList[0]);
            }
          });
        }
      });
    }
    // if (
    //   staticDataComponents.includes(props.schema.component) &&
    //   (props.schema.componentProps as any)?.datasourceType === 'staticData'
    // ) {
    //   let { defaultSelect } = props.schema.componentProps as any;
    //   emit('update:value', defaultSelect);
    //   console.log('update:value1', defaultSelect);
    // } else {
    //   let { defaultValue } = props.schema;
    //   if (!!props.schema.field && !noDefaultValueComponents.includes(props.schema.component)) {
    //     console.log('update:value', props.schema.component === 'SubForm' ? [] : defaultValue);
    //     emit('update:value', defaultValue);
    //   }
    // }
  });

  function handleTabsChange(idx) {
    if (document.getElementById('simptabs-' + props.schema.key)) {
      document
        .getElementById('simptabs-' + props.schema.key)
        .querySelector('.ant-tabs-ink-bar').style.background =
        props.schema.children[idx].activeColor || primaryColor;
    }
    let { componentProps = {} } = props.schema;
    if (componentProps['events']) {
      for (const eventKey in componentProps['events']) {
        try {
          const event = new Function(
            'schema',
            'formModel',
            'formActionType',
            'eventData',
            `${componentProps['events'][eventKey]}`,
          );
          let eventData = { index: idx, name: props.schema.children[idx].name };
          if (isFunction(componentProps['events'][eventKey])) {
            componentProps['events'][eventKey](props.schema, formModel, props.formApi, eventData);
          } else {
            event(props.schema, formModel, props.formApi, eventData);
          }
        } catch (error) {
          notification.error({
            message: 'Tip',
            description: '触发事件填写有误！',
          });
        }
      }
    }
  }

  const bordershowtype = computed(() => {
    return (props.schema.componentProps as any)?.bordershowtype || [true, true, true, true];
  });

  const borderwidth = computed(() => {
    const componentProps = props.schema.componentProps as any;
    return componentProps?.showBorder ? componentProps?.borderwidth + 'px' : 0;
  });

  const bordercolor = computed(() => {
    return (props.schema.componentProps as any)?.bordercolor;
  });

  const formComponent = (schema) => {
    return componentMap.get(
      ['caseErpApplyDetailList', 'case_erp_apply_detailList', 'CASE_ERP_APPLY_DETAILList'].includes(
        schema.field,
      )
        ? 'ErpApply'
        : schema.component,
    );
  };

  const defaultComponent = (schema) => {
    return componentMap.get(
      schema.key === 'ac18952da41b45c9a66ffba3e42b7f3d'
        ? 'ErpUpload'
        : schema.key === 'b3ba87573cf0466d951bc63fd4df1c78'
        ? 'ErpCheck'
        : schema.component,
    );
  };

  function showComponent(schema) {
    return props.isWorkFlow
      ? !noShowWorkFlowComponents.includes(schema.type)
      : !noShowGenerateComponents.includes(schema.type);
  }
  function getShow(schema: FormSchema): boolean {
    const { show } = schema;
    let isIfShow = true;

    if (isBoolean(show)) {
      isIfShow = show;
    }
    return isIfShow;
  }

  function getIsShow(schema: FormSchema): boolean {
    const { componentProps, show } = schema as any;
    let isShow = true;
    if (componentProps && isFunction(componentProps)) {
      isShow = componentProps({
        schema: props.schema,
        formModel,
        formActionType: props.formApi,
      })?.isShow;
    }
    if (isBoolean(componentProps?.isShow)) {
      isShow = componentProps?.isShow;
    }
    if (isBoolean(show)) {
      isShow = show;
    }
    if (isShow === false) return false;
    if (['tab', 'card', 'grid', 'form'].includes(schema.type!)) {
      return changeLayoutShow(schema);
    }
    return isShow;
  }

  function changeLayoutShow(schema) {
    let isShow = true;
    if (schema.type === 'card') {
      if (!schema.children![0].list.length) {
        isShow = false;
      } else {
        isShow = !schema.children![0].list?.every((item) => {
          if (['tab', 'card', 'grid', 'form'].includes(item.type!)) {
            return !changeLayoutShow(item);
          } else {
            let componentShow = !item.componentProps?.isShow;
            if (item.componentProps && isFunction(item.componentProps)) {
              componentShow = !item.componentProps({
                schema: props.schema,
                formModel,
                formActionType: props.formApi,
              })?.isShow;
            }
            return componentShow;
          }
        });
      }
    }
    if (schema.type === 'tab' || schema.type === 'grid') {
      isShow = !schema.children!.every((item) => {
        if (!item.list.length) return true;
        return item.list.every((com) => {
          if (['tab', 'card', 'grid', 'form'].includes(com.type!)) {
            return !changeLayoutShow(com);
          } else {
            let componentShow = !com.componentProps?.isShow;
            if (com.componentProps && isFunction(com.componentProps)) {
              componentShow = !com.componentProps({
                schema: props.schema,
                formModel,
                formActionType: props.formApi,
              })?.isShow;
            }
            return componentShow;
          }
        });
      });
    }
    if (schema.type === 'form') {
      if (!schema.componentProps!.columns.length) {
        isShow = false;
      } else {
        isShow = !schema.componentProps!.columns?.every((item) => {
          return !item.componentProps?.isShow;
        });
      }
    }
    return isShow;
  }
  async function sendMessageForIframe() {
    formItemRefs.value.sendMessage();
  }
  function getTableSelectedRows() {
    return tableFormRefs.value.getSelectedRows();
  }
  function gridFormApi(key, type) {
    let rows = null;
    for (let index = 0; index < gridFormItemRefs.value.length; index++) {
      if (gridFormItemRefs.value[index]) {
        if (gridFormItemRefs.value[index].key == key) {
          if (gridFormItemRefs.value[index]) {
            rows = gridFormItemRefs.value[index][type]();
            if (rows) return rows;
          }
        } else if (
          ['Grid', 'Tab', 'Card', 'TableLayout'].includes(
            gridFormItemRefs.value[index].componentType,
          )
        ) {
          rows = gridFormItemRefs.value[index].gridFormApi(key, type);
          if (rows) return rows;
        }
      }
    }
    return rows;
  }
  function customOpenModal() {
    customModalRefs.value.customOpenModal();
    return true;
  }
  defineExpose({
    sendMessageForIframe,
    componentType: getSchema.value.component,
    key: getSchema.value.key,
    getTableSelectedRows,
    gridFormApi,
    customOpenModal,
  });
</script>
<style lang="less" scoped>
  :deep(.ant-form-item-label > label) {
    white-space: normal;
    line-height: normal;
    min-height: 32px;
    height: auto;
  }

  .grid-box {
    border: 1px solid;
    border-top: v-bind('bordershowtype[0] ? borderwidth: 0') solid v-bind(bordercolor);
    border-right: v-bind('bordershowtype[1] ? borderwidth: 0') solid v-bind(bordercolor);
    border-bottom: v-bind('bordershowtype[2] ? borderwidth: 0') solid v-bind(bordercolor);
    border-left: v-bind('bordershowtype[3] ? borderwidth: 0') solid v-bind(bordercolor);
  }
</style>
