<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('表单生成代码配置') }}</span>
        <div class="btn-box">
          <a-button type="primary" @click="handleStepPrev" v-show="current !== 0">{{
            t('上一步')
          }}</a-button>
          <a-button type="primary" @click="handleStepNext" v-show="current < 3">{{
            t('下一步')
          }}</a-button>
          <a-button type="primary" @click="handleSave" v-show="current === 3">{{
            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-steps>
      </div>
    </template>
    <div class="step-container" v-if="isShow">
      <StructureConfigStep
        ref="structureConfigStepRef"
        v-show="current === 0"
        :isFormGenerator="true"
        :designType="designType"
      />
      <ViewDesignStep
        ref="viewDesignStepRef"
        v-show="current === 1"
        :isFormGenerator="true"
        :designType="designType"
      />
      <PreviewCodeStep
        ref="previewCodeStepRef"
        v-show="current === 2"
        :isFormGenerator="true"
        :designType="designType"
      />
      <MenuConfigStep ref="menuConfigStepRef" v-show="current === 3" />
    </div>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, reactive, provide, watch, Ref } from 'vue';
  import PreviewCodeStep from '/@/views/generator/dev/components/PreviewCodeStep.vue';
  import {
    StructureConfigStep,
    ViewDesignStep,
    MenuConfigStep,
  } from '/@/components/CreateCodeStep';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { GeneratorModel } from '/@/api/system/generator/model';
  import { FormProps } from '/@/components/Form';
  import { buildOption } from '/@/utils/helper/designHelper';
  import { buildCode } from '/@/utils/helper/generatorHelper';
  import { CustomFormConfig, GeneratorConfig } from '/@/model/generator/generatorConfig';
  import { TableInfo } from '/@/components/Designer';
  import { getFormTemplate } from '/@/api/form/design';
  import { dataFirstGeneratorCode, noFormGeneratorCode } from '/@/api/system/generator';
  import { useUserStore } from '/@/store/modules/user';
  import { FormTypeEnum } from '/@/enums/formtypeEnum';
  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';
  const { t } = useI18n();
  const userStore = useUserStore();
  const current = ref<number>(0);
  const isShow = ref(false);
  const structureConfigStepRef = ref();
  const viewDesignStepRef = ref();
  const previewCodeStepRef = ref();
  const menuConfigStepRef = ref();

  const tableInfo = ref<TableInfo[]>([]);
  const widgetForm = JSON.parse(JSON.stringify(antd.widgetForm));

  const emits = defineEmits(['success', 'register', 'close']);

  // const templateInfo = inject('getTemplateInfo');

  let generatorConfig = reactive<GeneratorConfig>({
    databaseId: '', //数据库id
    tableConfigs: [],
    tableStructureConfigs: [],
    formJson: {},
    formEventConfig: {},
    listConfig: {
      isAdvancedQuery: false, //是否配置高级搜索
      querySelectOption: '',
      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',
      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: {},
    outputConfig: {
      creator: userStore.getUserInfo.name,
      isMenu: true,
    },
  });
  let customFormConfig = reactive<CustomFormConfig>({
    name: '',
    category: '',
    formDesignType: 0,
    formType: FormTypeEnum.CUSTOM_FORM,
    formJson: generatorConfig,
    remark: '',
  });

  const designType = ref('');

  provide<GeneratorConfig>('generatorConfig', generatorConfig);
  provide<CustomFormConfig>('customFormConfig', customFormConfig);
  provide<Ref<TableInfo[]>>('tableInfo', tableInfo);
  provide('widgetForm', widgetForm);
  provide<Ref<number>>('current', current); //当前步骤

  watch(
    () => generatorConfig,
    () => {
      console.log(generatorConfig, 'generatorConfig:>>watch');
    },
    {
      deep: true,
    },
  );

  watch(
    () => customFormConfig,
    () => {
      console.log(customFormConfig, 'customFormConfig:>>watch');
    },
    {
      deep: true,
    },
  );

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({
      confirmLoading: false,
      defaultFullscreen: true,
      destroyOnClose: true,
      draggable: false,
      showOkBtn: false,
      showCancelBtn: false,
      footer: null,
      closable: false,
    });
    const res = await getFormTemplate(data.formId);
    const formJson = JSON.parse(res.formJson);
    switch (res.formDesignType) {
      case 0:
        designType.value = 'data';
        break;
      case 1:
        designType.value = 'code';
        break;
      case 2:
        designType.value = 'template';
        break;
      case 3:
        designType.value = 'notable';
        break;
    }

    generatorConfig.databaseId = formJson.databaseId;
    generatorConfig.formJson = formJson.formJson;
    generatorConfig.tableConfigs = formJson.tableConfigs;
    generatorConfig.tableStructureConfigs = formJson.tableStructureConfigs;
    generatorConfig.formEventConfig = formJson.formEventConfig;
    generatorConfig.outputConfig.dataAuthList = formJson.dataAuthList;
    generatorConfig.outputConfig.isDataAuth = formJson.isDataAuth;
    generatorConfig.outputConfig.isCommonFields = formJson.isCommonFields;
    generatorConfig.outputConfig.type = res.formDesignType;
    if (designType.value === 'notable') {
      generatorConfig.apiConfig = formJson.apiConfig;
    }

    isShow.value = true;
  });

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

  async function handleSave() {
    const isOk = await stepValidate[3]();
    if (
      generatorConfig.formJson?.hiddenComponent &&
      generatorConfig.formJson?.hiddenComponent.length
    ) {
      generatorConfig.formJson.list.push(...generatorConfig.formJson.hiddenComponent);
    }

    if (!isOk) {
      return;
    }
    const data = generatorConfig as GeneratorModel;
    data.frontCode = buildCode(
      generatorConfig,
      tableInfo.value,
      buildOption(generatorConfig.formJson) as FormProps,
      designType.value,
    );
    if (designType.value === 'notable') {
      await noFormGeneratorCode(data);
    } else {
      await dataFirstGeneratorCode(data);
    }
    closeModal();
    emits('success');
    emits('close');
  }

  const stepValidate = {
    //数据表配置 验证
    0: () => structureConfigStepRef.value.validateStep(),
    1: () => viewDesignStepRef.value.validateStep(),
    2: () => previewCodeStepRef.value.validateStep(),
    3: () => menuConfigStepRef.value.validateStep(),
  };
</script>
<style lang="less" scoped>
  .step-container {
    height: 100%;
  }
</style>
