<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>•</span>
        <span>{{ t('表单生成代码配置') }}</span>
        <a-steps :current="current">
          <a-step :title="t('基本信息')" />
          <a-step :title="t('界面设计')" />
          <a-step :title="t('代码预览')" />
          <a-step :title="t('菜单设置')" />
        </a-steps>
        <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>
    </template>
    <div class="step-container">
      <StructureConfigStep
        ref="structureConfigStepRef"
        v-show="current === 0"
        :isFormGenerator="true"
      />
      <ViewDesignStep ref="viewDesignStepRef" v-show="current === 1" :isFormGenerator="true" />
      <PreviewCodeStep ref="previewCodeStepRef" v-show="current === 2" :isFormGenerator="true" />
      <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 } 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';
  const { t } = useI18n();
  const userStore = useUserStore();
  const current = ref(0);

  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 isGetInfo = ref<boolean>(false);

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

  let generatorConfig = reactive<GeneratorConfig>({
    databaseId: '', //数据库id
    tableConfigs: [],
    tableStructureConfigs: [],
    formJson: {},
    formEventConfig: {},
    listConfig: {
      isLeftMenu: false,
      queryConfigs: [],
      leftMenuConfig: {
        datasourceType: 'static',
        listFieldName: undefined,
        apiConfig: {},
        dictionaryItemId: undefined,
        menuName: '',
        parentIcon: '',
        childIcon: '',
        staticData: [],
      },
      columnConfigs: [],
      buttonConfigs: [],
      defaultOrder: true,
      isPage: true,
    },
    menuConfig: {},
    outputConfig: {
      creator: userStore.getUserInfo.name,
      isMenu: true,
    },
  });
  let customFormConfig = reactive<CustomFormConfig>({
    name: '',
    category: '',
    formDesignType: 0,
    formType: FormTypeEnum.CUSTOM_FORM,
    formJson: generatorConfig,
    remark: '',
  });

  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);
    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;
    isGetInfo.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,
    );

    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>
  @keyframes rotation {
    from {
      transform: rotate(0deg);
    }

    to {
      transform: rotate(360deg);
    }
  }
  @keyframes rotationReverse {
    from {
      transform: rotate(0deg);
    }

    to {
      transform: rotate(-360deg);
    }
  }

  :deep(.ant-steps-item-process) {
    .ant-steps-item-icon {
      border: 2px solid #fff;
      outline: 2px dashed #1890ff !important;
      line-height: 30px;
      animation: rotation 4s linear infinite;

      .ant-steps-icon {
        display: inline-block;
        animation: rotationReverse 4s linear infinite;
      }
    }
  }

  .step-form-content {
    padding: 24px;
    background-color: @component-background;
  }

  .step-form-form {
    display: flex;
    align-items: center;
    font-weight: 400;

    a {
      margin-left: -16px;
    }

    span {
      font-size: 16px;
      margin: 0 20px 0 -5px;
      white-space: nowrap;
    }

    :deep(.ant-steps) {
      width: calc(100% - 750px);
    }

    :deep(.ant-steps-item-container) {
      padding: 2px 0 2px 2px;
    }

    .btn-box {
      position: absolute;
      right: 10px;

      :deep(.ant-btn) {
        margin-right: 10px;
      }
    }
  }

  .step-container {
    height: 100%;
  }

  .step1 {
    padding: 14px;
    box-sizing: border-box;
  }
</style>
