<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>{{ title }}</span>
        <div class="btn-box">
          <a-button
            type="primary"
            class="!rounded"
            @click="handleStepPrev"
            v-show="current === 1"
            >{{ t('<上一步') }}</a-button
          >
          <a-button
            type="primary"
            class="!rounded"
            @click="handleStepNext"
            v-show="current === 0"
            >{{ t('下一步>') }}</a-button
          >
          <a-button
            type="primary"
            class="!rounded w-82px"
            @click="handleSave"
            v-show="current === 1"
            >{{ t('完成') }}</a-button
          >
          <a-button type="primary" class="!rounded w-82px" 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-steps>
      </div>
    </template>

    <div class="step-container">
      <BasicConfigStep ref="basicConfigStepRef" v-show="current === 0" />
      <ViewDesignStep ref="viewDesignStepRef" v-show="current === 1" :isUpdate="isUpdate" />
    </div>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, reactive, provide, Ref, toRaw, defineAsyncComponent } from 'vue';
  import BasicConfigStep from './BasicConfigStep.vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { FormReleaseConfig, GeneratorConfig } from '/@/model/generator/generatorConfig';
  import { FieldInfo, TableInfo } from '/@/components/Designer';
  import { getFormTemplate } from '/@/api/form/design';
  import { getDatabaselinkMultiTableColumns } from '/@/api/system/databaselink';
  import { addFormRelease, getFormRelease, updateFormRelease } from '/@/api/form/release';
  import { JavaTypeConvertTsType } from '/@/utils/helper/designHelper';
  import { FormDesignTypeEnum } from '/@/enums/formtypeEnum';
  import { cloneDeep } from 'lodash-es';
  import { useI18n } from '/@/hooks/web/useI18n';
  import DesignLogo from '/@/components/ModalPanel/src/DesignLogo.vue';
  import { TreeStructureType } from '/@/enums/treeStructure';
  import { LoadingBox } from '/@/components/ModalPanel/index';
  import * as antd from '/@/components/Designer/src/types';
  const ViewDesignStep = defineAsyncComponent({
    loader: () => import('/@/components/CreateCodeStep/src/ViewDesignStep.vue'),
    loadingComponent: LoadingBox,
  });
  const { t } = useI18n();
  const current = ref(0);
  const isFormEdit = ref<boolean>(false);
  const widgetForm = ref(JSON.parse(JSON.stringify(antd.widgetForm)));
  const emit = defineEmits(['success', 'register', 'close']);

  const formIdCache = ref(``);

  const basicConfigStepRef = ref();
  const viewDesignStepRef = ref();

  const tableInfo = ref<TableInfo[]>([]);

  const isUpdate = ref<boolean>(false);
  const releaseId = ref<string>('');
  const menuId = ref<string>('');
  const designType = ref<string>('');
  const title = ref<string>('');

  let generatorConfig = reactive<GeneratorConfig>({
    listConfig: {
      listTitle: '',
      isLeftMenu: false,
      queryConfigs: [],
      leftMenuConfig: [
        {
          datasourceType: 'tree',
          listFieldName: undefined,
          apiConfig: {},
          dictionaryItemId: undefined,
          menuName: '',
          parentIcon: '',
          childIcon: '',
          staticData: [],
          treeConfig: {
            id: '',
            name: '',
            type: TreeStructureType.STATIC,
            configTip: '',
            config: [],
            isMultiple: false,
          },
        },
      ],
      columnConfigs: [],
      buttonConfigs: [],
      defaultOrder: true,
      listStyle: 'default',
      orderBy: '',
      isPage: true,
      pageSize: 10,
      apiConfig: {
        method: '',
        path: '',
        apiId: '',
        apiParams: [
          {
            key: '1',
            title: 'Query Params',
            tableInfo: [],
          },
          {
            key: '2',
            title: 'Header',
            tableInfo: [],
          },
          {
            key: '3',
            title: 'Body',
            tableInfo: [],
          },
        ],
      },
    },
    menuConfig: {},
  });

  let formReleaseConfig = reactive<FormReleaseConfig>({
    formId: '',
    listConfig: {},
    menuConfig: generatorConfig.menuConfig,
  });

  provide<GeneratorConfig>('generatorConfig', generatorConfig);
  provide<FormReleaseConfig>('formReleaseConfig', formReleaseConfig);
  provide<Ref<TableInfo[]>>('tableInfo', tableInfo);
  provide<Ref<number>>('current', current); //当前步骤
  provide<Ref<string>>('designType', designType);
  provide<boolean>('isCustomForm', true); //是自定义表单
  provide('widgetForm', widgetForm);
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    isFormEdit.value = !!data.isUpdate;
    isUpdate.value = !!data.isUpdate;
    releaseId.value = data.id;
    title.value = data.title;
    setModalProps({
      confirmLoading: false,
      canFullscreen: false,
      defaultFullscreen: true,
      draggable: false,
      destroyOnClose: true,
      maskClosable: false,
      footer: null,
      closable: false,
    });
    if (isUpdate.value) {
      const res = await getFormRelease(releaseId.value);
      const configJson = JSON.parse(res.configJson);
      const menuConfig = {
        ...configJson.menuConfig,
        formId: res.formId,
        systemId: configJson.menuConfig.systemId.toString(),
      };
      menuId.value = res.menuId;
      if (!Array.isArray(configJson.listConfig.leftMenuConfig)) {
        configJson.listConfig.leftMenuConfig = [configJson.listConfig.leftMenuConfig];
      }
      generatorConfig.listConfig = cloneDeep(configJson.listConfig);
      //基础信息赋值
      basicConfigStepRef.value.setFieldsValue(menuConfig);
    }
  });

  async function getReleseInfo() {
    if (formReleaseConfig.formId && formIdCache.value !== formReleaseConfig.formId) {
      formIdCache.value = formReleaseConfig.formId;
      const res = await getFormTemplate(formReleaseConfig.formId);
      const formJson = JSON.parse(res.formJson);
      const selectTableName = formJson.tableConfigs?.map((item) => item.tableName);

      switch (res.formDesignType) {
        case FormDesignTypeEnum.DATA_FIRST:
          designType.value = 'data';
          break;
        case FormDesignTypeEnum.CODE_FIRST:
          designType.value = 'code';
          break;
        case FormDesignTypeEnum.SIMPLE_TEMPLATE:
          designType.value = 'template';
        case FormDesignTypeEnum.NO_TABLE:
          designType.value = 'notable';
          break;
      }

      generatorConfig.formJson = formJson.formJson;
      if (!isUpdate.value) {
        generatorConfig.listConfig.listStyle = formJson.listPageMode;
      }
      generatorConfig.tableStructureConfigs = formJson.tableStructureConfigs;
      if (designType.value === 'notable') generatorConfig.apiConfig = formJson.apiConfig;
      generatorConfig.tableStructureConfigs = formJson.tableStructureConfigs;
      widgetForm.value = formJson.formJson;
      if (designType.value !== 'data') return;
      try {
        const result = await getDatabaselinkMultiTableColumns({
          id: formJson.databaseId,
          tableNames: selectTableName.join(','),
        });
        for (const key in result) {
          const columnInfo = result[key];
          //如果已经写入过的表格 不再添加
          if (!tableInfo?.value.find((x) => x.name === key)) {
            const fields = columnInfo.map((field) => {
              const filedInfo: FieldInfo = {
                name: field.column,
                length: field.dataLength,
                type: JavaTypeConvertTsType(field.dataType),
                isPk: field.primaryKey,
                isNullable: field.nullable,
              };
              return filedInfo;
            });

            tableInfo?.value.push({
              name: key,
              isMain: formJson!.tableConfigs!.find((x) => x.tableName === key)?.isMain as boolean,
              fields: fields,
            });
          }
        }
      } catch (error) {}
    }
  }

  function handleClose() {
    emit('close');
  }

  //上一步
  function handleStepPrev() {
    current.value--;
  }
  //下一步
  async function handleStepNext() {
    const isOk = await stepValidate[current.value]();
    if (!isOk) {
      return;
    }
    if (current.value === 0) {
      await getReleseInfo();
    }
    current.value++;
  }

  async function handleSave() {
    const isOk = await stepValidate[1]();
    if (!isOk) {
      return;
    }
    formReleaseConfig.listConfig = generatorConfig.listConfig;
    const params = {
      ...toRaw(formReleaseConfig),
      id: releaseId.value,
      menuId: menuId.value,
    };
    if (isUpdate.value) {
      await updateFormRelease(params);
    } else {
      await addFormRelease(toRaw(formReleaseConfig));
    }
    closeModal();
    emit('success', isFormEdit.value);
    emit('close');
  }

  const stepValidate = {
    //数据表配置 验证
    0: () => basicConfigStepRef.value.validateStep(),
    1: () => viewDesignStepRef.value.validateStep(),
  };
</script>
<style lang="less" scoped>
  :deep(.ant-steps) {
    width: 410px !important;
  }
</style>
