<template>
  <div style="height: 100%">
    <DesignForm ref="designFormRef" />
    <FormPreviewDrawer @register="registerDrawer" />
  </div>
</template>
<script lang="ts" setup>
  import { noHaveTableAndField, remoteComponents } from '/@/components/Designer';
  import FormPreviewDrawer from '/@/components/CreateCodeStep/src/components/FormPreviewDrawer.vue';
  import DesignForm from './components/DesignForm.vue';
  import { inject, ref, Ref, watch } from 'vue';
  import { useDrawer } from '/@/components/Drawer';
  import { GeneratorConfig } from '/@/model/generator/generatorConfig';
  import { TableFieldConfig } from '/@/model/generator/tableStructureConfig';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { ComponentOptionModel, FormJson } from '/@/model/generator/codeGenerator';
  import { cloneDeep } from 'lodash-es';
  import {
    noHaveField,
    shortTextComponents,
    longTextComponents,
    integerComponents,
    decimalsComponents,
    dateTimeComponents,
    timeComponents,
  } from '/@/components/Designer';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  const generatorConfig = inject<GeneratorConfig>('generatorConfig');
  const widgetForm = inject<any>('widgetForm');
  const { notification } = useMessage();
  const current = inject<Ref<number>>('current') as Ref<number>;
  const designFormRef = ref();
  watch(
    () => current.value,
    () => {
      designFormRef.value.setWidgetFormSelect(widgetForm.value);
    },
  );
  //注册抽屉 获取外部操作抽屉得方法
  const [registerDrawer] = useDrawer();

  const setStructureConfig = () => {
    //新增时的配置信息
    const addStructureConfig = cloneDeep(generatorConfig!.tableStructureConfigs || []);
    generatorConfig!.tableStructureConfigs = [];
    let tableFieldConfigs = [] as TableFieldConfig[];

    getTableStructure(generatorConfig?.formJson.list, tableFieldConfigs);
    let isCommonFields = generatorConfig?.isCommonFields;

    const fields = [
      'create_user_id',
      'modify_user_id',
      'modify_date',
      'delete_mark',
      'enabled_mark',
    ];
    if (isCommonFields) {
      const commonFields = [
        {
          key: 'create_user_id',
          fieldName: 'create_user_id',
          fieldType: 6,
          fieldLength: null,
          fieldComment: t('创建人'),
        },
        {
          key: 'modify_user_id',
          fieldName: 'modify_user_id',
          fieldType: 6,
          fieldLength: null,
          fieldComment: t('修改人'),
        },
        {
          key: 'modify_date',
          fieldName: 'modify_date',
          fieldType: 5,
          fieldLength: null,
          fieldComment: t('修改时间'),
        },
        {
          key: 'delete_mark',
          fieldName: 'delete_mark',
          fieldType: 2,
          fieldLength: null,
          fieldComment: t('删除字段'),
        },
        {
          key: 'enabled_mark',
          fieldName: 'enabled_mark',
          fieldType: 2,
          fieldLength: null,
          fieldComment: t('标记字段'),
        },
      ];
      const hasCommonField =
        generatorConfig?.tableStructureConfigs?.length &&
        generatorConfig?.tableStructureConfigs[0].tableFieldConfigs.find((x) =>
          fields.includes(x.key!),
        );
      if (hasCommonField) return;
      generatorConfig?.tableStructureConfigs?.length &&
        generatorConfig?.tableStructureConfigs[0].tableFieldConfigs.push(...commonFields);
    } else {
      if (generatorConfig?.tableStructureConfigs?.length) {
        generatorConfig.tableStructureConfigs[0].tableFieldConfigs =
          generatorConfig?.tableStructureConfigs[0].tableFieldConfigs.filter(
            (x) => !fields.includes(x.key!),
          );
      }
    }
    if (addStructureConfig.length) {
      //编辑回显
      addStructureConfig.forEach((addConfig) => {
        generatorConfig!.tableStructureConfigs!.forEach((config) => {
          if (addConfig.tableName === config.tableName) {
            config.tableComment = addConfig.tableComment;
            addConfig.tableFieldConfigs?.forEach((subAddConfig) => {
              config.tableFieldConfigs?.forEach((subConfig) => {
                if (subAddConfig.fieldName === subConfig.fieldName) {
                  subConfig.fieldType = subAddConfig.fieldType;
                  subConfig.fieldLength = subAddConfig.fieldLength;
                  subConfig.fieldComment = subAddConfig.fieldComment;
                }
              });
            });
          }
        });
      });
    }
  };

  const getTableStructure = (list, tableFieldConfigs) => {
    list?.map((item) => {
      if (!noHaveField.includes(item.type)) {
        if (
          !generatorConfig?.tableStructureConfigs?.length ||
          !generatorConfig?.tableStructureConfigs[0].isMain
        ) {
          generatorConfig?.tableStructureConfigs?.unshift({
            tableName: item.bindTable,
            tableComment: '',
            isMain: true,
            tableFieldConfigs,
          });
        }

        if (generatorConfig?.tableStructureConfigs?.length) {
          setTableFieldConfigs(item, generatorConfig?.tableStructureConfigs[0].tableFieldConfigs);
        }
      }
    });
    generatorConfig!.tableStructureConfigs![0].tableFieldConfigs.push({
      key: 'create_date',
      fieldName: 'create_date',
      fieldType: 5,
      fieldLength: null,
      fieldComment: t('创建时间'),
    });
  };

  const setTableFieldConfigs = (item, tableFieldConfigs) => {
    tableFieldConfigs.push({
      key: item.key,
      fieldName: item.bindField.substr(0, 30),
      fieldLength: !getFieldType(item.type) ? 500 : null,
      fieldType: getFieldType(item.type),
      fieldComment: item.label!,
    });
  };

  const getFieldType = (type) => {
    switch (type) {
      case shortTextComponents.find((x) => x === type):
        return 0;
      case longTextComponents.find((x) => x === type):
        return 1;
      case integerComponents.find((x) => x === type):
        return 2;
      case decimalsComponents.find((x) => x === type):
        return 3;
      case dateTimeComponents.find((x) => x === type):
        return 5;
      case timeComponents.find((x) => x === type):
        return 8;
      default:
        return 0;
    }
  };

  //验证当前步骤的数据
  const validateStep = async (): Promise<boolean> => {
    setStructureConfig();
    const formJson = designFormRef.value.getJson() as FormJson;

    //formJson 是否为空 或者 一个组件都没有
    if (!formJson || formJson.list.length === 0) {
      notification.error({
        message: t('提示'),
        description: t('表单设计不能为空！'),
      }); //提示消息
      return false;
    }

    const { tableConfigs } = generatorConfig as GeneratorConfig;
    const mainTableName = tableConfigs?.find((x) => x.isMain)?.tableName;

    //先判断所有非子表组件  是否包含主表字段  如果一个主表字段都没有 提示
    const getMainComponent = (list?) => {
      if (!list) return [];
      let mainComponents = [] as Recordable[];
      for (const item of list) {
        if (item.bindTable === mainTableName) {
          mainComponents.push(item);
        }
      }
      return mainComponents;
    };

    //主表中的所有字段
    const mainTableFieldList: string[] = [];
    getMainComponent(formJson.list).forEach((item) => {
      mainTableFieldList.push(item.bindField);
    });

    if (
      generatorConfig?.tableStructureConfigs &&
      !generatorConfig?.tableStructureConfigs[0]?.isMain
    ) {
      notification.error({
        message: t('提示'),
        description: t('表单设计未添加生成主表字段的组件，请先添加后再进行下一步。'),
      }); //提示消息
      return false;
    }
    //一个个组件遍历
    const message = validateComponent(formJson.list);

    if (message) {
      notification.error({
        message: t('提示'),
        description: message,
      }); //提示消息
      return false;
    }

    return true;
  };

  const validateComponent = (list: ComponentOptionModel[]) => {
    for (const component of list) {
      if (noHaveTableAndField.includes(component.type)) {
        //如果是不需要绑定字段的 默认跳过验证
        continue;
      }

      //如果是远程组件并且是 数据源  或者 数据字典 方式
      if (
        remoteComponents.includes(component.type) &&
        component.options!.datasourceType !== 'staticData'
      ) {
        if (component.options!.datasourceType === 'dic') {
          if (!component.options!.itemId) {
            return t(`{name}未选择数据字典`, { name: component.label });
          }
          if (!component.options!.dicOptions?.length && component.type === 'associate-popup') {
            return t(`{name}未进行联想配置`, { name: component.label });
          }

          if (!component.options!.dicOptions?.length && component.type === 'multiple-popup') {
            return t(`{name}未进行显示配置`, { name: component.label });
          }
        }
        if (component.options!.datasourceType === 'api') {
          if (!component.options!.apiConfig.apiId) {
            return t(`{name}未选择API`, { name: component.label });
          }
          if (!component.options!.apiConfig.outputParams && component.type === 'associate-popup') {
            return t(`{name}未进行联想配置`, { name: component.label });
          }

          if (!component.options!.apiConfig.outputParams && component.type === 'multiple-popup') {
            return t(`{name}未进行显示配置`, { name: component.label });
          }
        }

        if (component.options!.datasourceType === 'datasource') {
          if (!component.options!.sourceId) {
            return t(`{name}未选择数据源`, { name: component.label });
          }
          if (!component.options!.labelField) {
            return t(`{name}未选择数据源显示字段`, { name: component.label });
          }
          if (!component.options!.valueField) {
            return t(`{name}未选择数据源保存字段`, { name: component.label });
          }
        }
      }
      // TODO  这里继续写各组件自己特有的一些验证
      if (!component.bindTable) {
        return t(`{name}未绑定表`, { name: component.label });
      }

      if (!component.bindField) {
        return t(`{name}未绑定字段`, { name: component.label });
      }
    }
    return '';
  };

  defineExpose({ validateStep });
</script>
