<template>
  <BasicModal @register="registerModal" v-bind="$attrs" wrapClassName="form-modal">
    <template #title>
      <div class="step-form-form">
        <a href="https://www.learun.cn/" target="_blank">
          <DesignLogo />
        </a>
        <span>{{ t('AI开发') }}</span>
        <div class="btn-box">
          <a-button @click="handleStepPrev" v-show="current !== 0">{{ t('上一步') }}</a-button>
          <a-button type="primary" @click="handleStepNext" v-show="current < 7">
            {{ t('下一步') }}
          </a-button>
          <a-button type="primary" @click="handleTableSql" v-show="current === 1">
            {{ t('生成表SQL') }}
          </a-button>
          <a-button
            type="primary"
            @click="handleCodeGenerator"
            v-show="current === 7 || current === 1"
          >
            {{ t('完成') }}
          </a-button>
          <a-button type="primary" danger @click="handleClose">{{ t('关闭') }}</a-button>
        </div>
      </div>
      <div class="step-box">
        <a-steps :current="current" size="mini">
          <a-step :title="t('基本信息')" />
          <a-step :title="t('结构配置')" />
          <a-step :title="t('表单设计')" />
          <a-step :title="t('表单事件')" />
          <a-step :title="t('界面设计')" />
          <a-step :title="t('表单信息配置')" />
          <a-step :title="t('代码预览')" />
          <a-step :title="t('菜单设置')" />
        </a-steps>
      </div>
    </template>
    <div class="step-container">
      <TableConfigStep ref="tableConfigStepRef" v-show="current === 0" :templateId="templateId" />
      <StructureConfigStep
        ref="structureConfigStepRef"
        :isUpdate="isUpdate"
        v-if="current === 1"
        @validate-table="handleStepNext"
        @cancel="handleCancel"
      />
      <FormDesignStep ref="formDesignStepRef" v-show="current === 2" />
      <FormEventStep ref="formEventStep" v-show="current === 3" origin="AI" />
      <ViewDesignStep
        ref="viewDesignStep"
        :isUpdate="isUpdate"
        origin="AI"
        v-show="current === 4"
      />
      <FuncConfigStep ref="funcConfigStep" :isUpdate="isUpdate" v-if="current === 5" />
      <PreviewCodeStep
        ref="previewCodeStep"
        v-show="current === 6 && generatorConfig.outputConfig.isSystemForm"
        origin="AI"
      />
      <div
        v-if="current === 6 && !generatorConfig.outputConfig.isSystemForm"
        class="flex items-center justify-center h-full text-[30px] text-[#ccc]"
      >
        自定义表单不生成代码
      </div>
      <MenuConfigStep ref="menuConfigStep" v-show="current === 7" origin="AI" />
    </div>
    <ruleCodeModal @register="registerSqlModal" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, reactive, provide, Ref, defineAsyncComponent } from 'vue';
  import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
  import { GeneratorConfig } from '/@/model/generator/generatorConfig';
  import { ColumnType, fieldTypeCompMap, TableInfo } from '/@/components/Designer';

  import { FormProps } from '/@/components/Form';
  import { buildOption } from '/@/utils/helper/designHelper';
  import { buildCode } from '/@/utils/helper/generatorHelper';
  import { useUserStore } from '/@/store/modules/user';
  import { LoadingBox } from '/@/components/ModalPanel/index';
  import { MenuConfig } from '/@/model/generator/menuConfig';
  import { FormJson } from '/@/model/generator/codeGenerator';
  import { FormEventColumnConfig } from '/@/model/generator/formEventConfig';
  import * as antd from '/@/components/Designer/src/types';
  import { useI18n } from '/@/hooks/web/useI18n';
  import DesignLogo from '/@/components/ModalPanel/src/DesignLogo.vue';
  import { TreeStructureType } from '/@/enums/treeStructure';
  import { cloneDeep } from 'lodash-es';
  import { addAiDbTable, addAiForm, getTableSql, getAIFormInfo } from '/@/api/aiCreateTable';
  import ruleCodeModal from './ruleCodeModal.vue';

  const { t } = useI18n();
  const TableConfigStep = defineAsyncComponent({
    loader: () => import('./TableConfigStep.vue'),
    loadingComponent: LoadingBox,
  });
  const StructureConfigStep = defineAsyncComponent({
    loader: () => import('./StructureConfigStep.vue'),
    loadingComponent: LoadingBox,
  });
  const FormDesignStep = defineAsyncComponent({
    loader: () => import('/@/components/CreateCodeStep/src/FormDesignStep.vue'),
    loadingComponent: LoadingBox,
  });
  const FormEventStep = defineAsyncComponent({
    loader: () => import('/@/components/CreateCodeStep/src/FormEventStep.vue'),
    loadingComponent: LoadingBox,
  });
  const ViewDesignStep = defineAsyncComponent({
    loader: () => import('/@/components/CreateCodeStep/src/ViewDesignStep.vue'),
    loadingComponent: LoadingBox,
  });
  const FuncConfigStep = defineAsyncComponent({
    loader: () => import('./FuncConfigStep.vue'),
    loadingComponent: LoadingBox,
  });
  const PreviewCodeStep = defineAsyncComponent({
    loader: () => import('../../dev/components/PreviewCodeStep.vue'),
    loadingComponent: LoadingBox,
  });
  const MenuConfigStep = defineAsyncComponent({
    loader: () => import('/@/components/CreateCodeStep/src/MenuConfigStep.vue'),
    loadingComponent: LoadingBox,
  });
  const userStore = useUserStore();
  const templateId = ref();
  const dataSchemaId = ref();
  const current = ref(0);
  const isClose = ref(false);
  const isUpdate = ref(false);
  const tableConfigStepRef = ref();
  const structureConfigStepRef = ref();
  const formDesignStepRef = ref();
  const formEventStep = ref();
  const viewDesignStep = ref();
  const previewCodeStep = ref();
  const menuConfigStep = ref();
  const funcConfigStep = ref();
  const widgetForm = ref(JSON.parse(JSON.stringify(antd.widgetForm))); //FormDesignStep -> designer和StructureConfigStep页面使用
  const tableInfo = ref<TableInfo[]>([]);

  const emit = defineEmits(['close', 'register', 'success']);
  let generatorConfig = reactive<GeneratorConfig>({
    AIInfo: {
      code: '',
      columName: '',
      databaseId: 'master',
      name: '',
      remark: '',
      tableName: '',
    },
    databaseId: null, //数据库id
    listConfig: {
      isLeftMenu: false,
      queryConfigs: [],
      isAdvancedQuery: false, //是否配置高级搜索
      leftMenuConfig: [
        {
          datasourceType: 'tree',
          listFieldName: undefined,
          apiConfig: {},
          dictionaryItemId: undefined,
          menuName: '',
          parentIcon: '',
          childIcon: '',
          staticData: [],
          treeConfig: {
            id: '',
            name: '',
            type: TreeStructureType.STATIC,
            config: [],
            configTip: '',
            isMultiple: false,
          },
        },
      ],
      columnConfigs: [],
      buttonConfigs: [],
      defaultOrder: true,
      listStyle: 'default',
      isPage: true,
      querySelectOption: '', //所有查询配置
      objectId: '', //系统表单formId,自定义表单releaseId的id值
    },
    tableConfigs: [],
    formJson: {} as FormJson,
    menuConfig: {} as MenuConfig,
    outputConfig: {
      creator: userStore.getUserInfo.name,
      isMenu: true,
      type: 0,
      isSystemForm: false,
    },
    formEventConfig: {} as FormEventColumnConfig,
    dataAuthList: [],
    tableStructureConfigs: [],
  });

  provide<GeneratorConfig>('generatorConfig', generatorConfig);
  provide<Ref<TableInfo[]>>('tableInfo', tableInfo);
  provide<Ref<number>>('current', current); //当前步骤
  provide<string>('designType', 'data');
  provide<string>('mainTableName', '');
  provide('widgetForm', widgetForm);

  let timer: any = null;

  const allComponents = [
    ...antd.basicComponents,
    ...antd.advanceComponents,
    ...antd.buttonComponents,
    ...antd.layoutComponents,
    ...antd.workFlowComponents,
    ...antd.infoComponents,
    ...antd.financeComponents,
  ];

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({
      confirmLoading: false,
      canFullscreen: false,
      defaultFullscreen: true,
      maskClosable: false,
      destroyOnClose: true,
      draggable: false,
      showOkBtn: false,
      showCancelBtn: false,
      footer: null,
      closable: false,
    });
    isUpdate.value = data.isUpdate || false;
    templateId.value = data.isUpdate ? data.id : '';
    if (data.isUpdate) {
      let res: any = await getAIFormInfo(data.id);

      if (res) {
        const {
          databaseId,
          tableName,
          code,
          columName,
          name,
          remark,
          outputConfig,
          formJson,
          formEventConfig,
          listConfig,
          menuConfig,
        } = res;
        generatorConfig.databaseId = databaseId;
        generatorConfig.AIInfo = {
          databaseId,
          tableName,
          code,
          columName,
          name,
          remark,
        };

        if (formJson.list) {
          generatorConfig.formJson = formJson;
          generatorConfig.formJson.list = generatorConfig.formJson.list?.filter(
            (x) => x.type !== 'hiddenComponent',
          );

          widgetForm.value = generatorConfig.formJson;
        }

        generatorConfig.listConfig = listConfig;

        generatorConfig.menuConfig = menuConfig;
        generatorConfig.outputConfig = outputConfig;
        if (outputConfig.isSystemForm === null) generatorConfig.outputConfig.isSystemForm = true;
        generatorConfig.formEventConfig = formEventConfig || ({} as FormEventColumnConfig);
      }
    }
  });

  //上一步
  function handleStepPrev() {
    current.value--;
  }
  //下一步
  async function handleStepNext() {
    const isOk = await stepValidate[current.value]();
    if (!isOk) {
      return;
    }
    if (isClose.value) {
      await addAiDbTable({
        id: templateId.value,
        ...generatorConfig.AIInfo,
        aiTableStructureConfig: {
          tableStructureConfigs: generatorConfig.tableStructureConfigs || [],
          tableConfigs: generatorConfig.tableConfigs || [],
        },
      });
      handleClose();
      emit('success');
      isClose.value = false;
      return;
    }
    if (current.value === 1) {
      let formJson: FormJson = {
        list: [],
        config: {
          formType: 'modal',
          size: 'default',
          layout: 'vertical',
          labelAlign: 'right',
          labelCol: {
            span: 3,
            offset: 0,
          },
          formWidth: 900,
        },
        hiddenComponent: [],
      };
      generatorConfig.tableStructureConfigs?.forEach((o) => {
        if (o.isMain) {
          //主表
          let list = buildCompnent(o.tableFieldConfigs, o.tableName);
          formJson.list = formJson.list.concat(list);
        } else if (!o.isMain && o.isSubForm) {
          //子表
          let obj: any = allComponents.find((a) => {
            return a.type == 'form';
          });
          let form = cloneDeep(obj);
          form.label = o.tableComment;
          form.typeName = o.tableComment;
          form.key = o.key;
          form.model = 'form_' + o.key;
          form.bindTable = o.tableName;
          form.children = buildCompnent(o.tableFieldConfigs, o.tableName);
          let suntable = generatorConfig.tableStructureConfigs?.find((s) => {
            return s.parentKey == o.key;
          });
          if (suntable) {
            // 次表
            let sunobj: any = allComponents.find((a) => {
              return a.type == 'sun-form';
            });
            let sunform = cloneDeep(sunobj);
            sunform.label = suntable.tableComment;
            sunform.key = suntable.key;
            sunform.bindTable = suntable.tableName;
            sunform.parentTable = o.tableName;
            sunform.children = buildCompnent(suntable.tableFieldConfigs, suntable.tableName);
            form.children.push(sunform);
          }
          formJson.list.push(form);
        }
      });
      generatorConfig.formJson = formJson;
      widgetForm.value = formJson;
    }

    current.value++;
  }
  function buildCompnent(tableFieldConfigs, tableName) {
    const list: any = [];
    tableFieldConfigs.forEach((f) => {
      if (
        !(
          (f.fieldType == ColumnType.KEY && f.fieldLength < 19) ||
          (f.fieldType == ColumnType.LONGTEXT && f.fieldLength < 200)
        )
      ) {
        let obj: any = allComponents.find((a) => {
          return a.type == fieldTypeCompMap[f.fieldType];
        });
        if (obj) {
          let form = cloneDeep(obj);
          form.label = f.fieldComment;
          form.options.placeholder = t(
            ([4, 5, 6, 8].includes(f.fieldType) ? '请选择' : '请输入') + f.fieldComment,
          );
          form.key = f.key;
          form.model = fieldTypeCompMap[f.fieldType] + '_' + f.key;
          form.bindField = f.fieldName;
          form.bindTable = tableName;
          list.push(form);
        }
      }
    });
    return list;
  }

  function handleCancel() {
    isClose.value = false;
  }
  async function handleCodeGenerator() {
    if (current.value == 1) {
      isClose.value = true;
      const isOk = await stepValidate[1]();
      if (!isOk) {
        return;
      }

      await addAiDbTable({
        ...generatorConfig.AIInfo,
        aiTableStructureConfig: {
          tableStructureConfigs: generatorConfig.tableStructureConfigs || [],
          tableConfigs: generatorConfig.tableConfigs || [],
        },
      });
    } else {
      const isOk = await stepValidate[7]();
      if (
        generatorConfig.formJson?.hiddenComponent &&
        generatorConfig.formJson?.hiddenComponent.length
      ) {
        generatorConfig.formJson.list.push(...generatorConfig.formJson.hiddenComponent);
      }

      if (!isOk) {
        return;
      }
      const data: any = { ...generatorConfig, ...generatorConfig.AIInfo };
      if (generatorConfig.outputConfig.isSystemForm) {
        data.frontCode = buildCode(
          generatorConfig,
          tableInfo.value,
          buildOption(generatorConfig.formJson) as FormProps,
        );
      }

      if (templateId.value) data.aiTableId = templateId.value;
      if (dataSchemaId.value) data.id = dataSchemaId.value;
      delete data.AIInfo;
      await addAiForm(data);
    }
    handleClose();
    emit('success');
  }

  const handleClose = () => {
    current.value = 0;
    generatorConfig.AIInfo = {
      code: '',
      columName: '',
      databaseId: 'master',
      name: '',
      remark: '',
      tableName: '',
    };
    generatorConfig.outputConfig = {
      creator: userStore.getUserInfo.name,
      isMenu: true,
      type: 0,
      isSystemForm: false,
    };
    generatorConfig.menuConfig = {};
    closeModal();
    emit('close');
    clearInterval(timer);
    timer = null;
  };
  const [registerSqlModal, { openModal }] = useModal();
  async function handleTableSql() {
    let res = await getTableSql({
      databaseId: generatorConfig.AIInfo.databaseId,
      tableStructureConfigs: generatorConfig.tableStructureConfigs,
    });

    openModal(true, res);
  }
  const stepValidate = {
    //数据表配置 验证
    0: () => tableConfigStepRef.value.validateStep(),
    1: () => structureConfigStepRef.value.validateStep(),
    2: () => formDesignStepRef.value.validateStep(),
    3: () => formEventStep.value.validateStep(),
    4: () => viewDesignStep.value.validateStep(),
    5: () => funcConfigStep.value.validateStep(),
    6: () => {
      return generatorConfig.outputConfig.isSystemForm
        ? previewCodeStep.value.validateStep()
        : true;
    },
    7: () => menuConfigStep.value.validateStep(),
  };
</script>
<style lang="less" scoped></style>
