<template>
  <BasicModal @register="registerModal" v-bind="$attrs" destroy-on-close 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 @click="handleStepPrev" v-show="current !== 0" class="!rounded">{{
            t('<上一步')
          }}</a-button>
          <a-button type="primary" @click="handleStepNext" v-show="current < 5" class="!rounded">
            {{ t('下一步>') }}
          </a-button>
          <a-button
            type="primary"
            @click="handleCodeGenerator"
            v-show="current === 5"
            class="!rounded w-82px"
          >
            {{ t('完成') }}
          </a-button>
          <a-button type="primary" @click="handleSaveDraft" v-show="current > 3" class="!rounded">{{
            t('保存草稿')
          }}</a-button>
          <a-button type="primary" danger @click="handleClose" class="!rounded w-82px">{{
            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-steps>
      </div>
    </template>
    <div class="step-container" v-if="showContainer">
      <TableConfigStep ref="tableConfigStepRef" v-if="current === 0" />
      <FormDesignStep ref="formDesignStepRef" v-if="current === 1" />
      <FormEventStep ref="formEventStepRef" v-show="current === 2" />
      <ViewDesignStep ref="viewDesignStep" :isUpdate="!!templateId" v-show="current === 3" />
      <PreviewCodeStep ref="previewCodeStep" v-show="current === 4" />
      <MenuConfigStep ref="menuConfigStep" v-show="current === 5" />
    </div>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, reactive, provide, Ref, defineAsyncComponent, computed } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { GeneratorConfig } from '/@/model/generator/generatorConfig';
  import { TableInfo } from '/@/components/Designer';
  import { FormEventStep } from '/@/components/CreateCodeStep';
  import { buildAppFormProps } from '/@/utils/helper/designHelper';
  import { buildAppCode } from '/@/utils/helper/generatorHelper';
  import { AppFuncModel } from '/@/api/system/generator/model';
  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 { AppFormProps } from '/@/model/generator/appFormConfig';
  import { addMobileFunc, editMobileFuncData, getMobileFuncInfo } from '/@/api/mobileDesign';
  import DesignLogo from '/@/components/ModalPanel/src/DesignLogo.vue';
  import { TreeStructureType } from '/@/enums/treeStructure';
  const { t } = useI18n();
  const TableConfigStep = defineAsyncComponent({
    loader: () => import('./TableConfigStep.vue'),
    loadingComponent: LoadingBox,
  });
  const FormDesignStep = defineAsyncComponent({
    loader: () => import('./FormDesignStep.vue'),
    loadingComponent: LoadingBox,
  });

  const ViewDesignStep = defineAsyncComponent({
    loader: () => import('./ViewDesignStep.vue'),
    loadingComponent: LoadingBox,
  });
  const MenuConfigStep = defineAsyncComponent({
    loader: () => import('./MenuConfigStep.vue'),
    loadingComponent: LoadingBox,
  });
  const PreviewCodeStep = defineAsyncComponent({
    loader: () => import('./PreviewCodeStep.vue'),
    loadingComponent: LoadingBox,
  });

  const userStore = useUserStore();
  const templateId = ref();
  const appMenuId = ref();
  const enabledMark = ref(1);
  const current = ref(0);
  const designType = ref('data');
  const mainTableName = computed(
    () => generatorConfig!.tableConfigs!.find((item) => item.isMain)!.tableName,
  );
  const tableConfigStepRef = ref();
  const formDesignStepRef = ref();
  const formEventStepRef = ref();
  const viewDesignStep = ref();
  const previewCodeStep = ref();
  const menuConfigStep = ref();
  const widgetForm = ref(JSON.parse(JSON.stringify(antd.widgetForm))); //FormDesignStep -> designer和StructureConfigStep页面使用
  const tableInfo = ref<TableInfo[]>([]);
  const showContainer = ref(true);
  const emit = defineEmits(['close', 'register', 'success']);
  let generatorConfig = reactive<GeneratorConfig>({
    databaseId: null, //数据库id
    listConfig: {
      isAdvancedQuery: false,
      objectId: '',
      querySelectOption: '',
      isLeftMenu: false,
      queryConfigs: [],
      leftMenuConfig: [
        {
          // isTree: false,
          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,
      isPage: true,
    },
    tableConfigs: [],
    formJson: {} as FormJson,
    menuConfig: {} as MenuConfig,
    outputConfig: {
      creator: userStore.getUserInfo.name,
      isMenu: true,
      type: 0,
      funcType: 1,
      formObj: {
        formId: '',
      },
      createCode: false,
    },
    formEventConfig: {} as FormEventColumnConfig,
    isDataAuth: false,
    dataAuthList: [],
    formId: '',
  });
  provide<GeneratorConfig>('generatorConfig', generatorConfig);
  provide<Ref<TableInfo[]>>('tableInfo', tableInfo);
  provide<Ref<number>>('current', current); //当前步骤
  provide<Ref<string>>('designType', designType);
  provide('widgetForm', widgetForm);
  provide<Ref<string>>('mainTableName', mainTableName);
  provide<Boolean>('fromMobile', true);

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    templateId.value = data.isUpdate ? data.id : '';
    appMenuId.value = data.isUpdate ? data.appMenuId : '';
    enabledMark.value = data.isUpdate ? data.enabledMark : 1;
    generatorConfig.outputConfig.funcType = 1;
    generatorConfig.outputConfig.formObj = undefined;
    generatorConfig.outputConfig.comment = '';
    generatorConfig.outputConfig.className = undefined;
    generatorConfig.outputConfig.outputArea = undefined;
    generatorConfig.databaseId = null;
    generatorConfig.isDataAuth = false;
    generatorConfig.dataAuthList = [];
    if (data.isUpdate) {
      showContainer.value = false;
      let res: any = {};
      let jsonContent: any = {};
      res = await getMobileFuncInfo(data.id);

      jsonContent = JSON.parse(res.jsonContent);
      jsonContent.formJson.list = jsonContent.formJson.list.filter(
        (x) => x.type !== 'hiddenComponent',
      );
      generatorConfig.databaseId = jsonContent.databaseId;
      generatorConfig.listConfig = jsonContent.listConfig;
      let filterBtn = [
        'batchdelete',
        'copyData',
        'flowRecord',
        'batchSetUserId',
        'import',
        'export',
        'print',
        'templateprint',
        'pushorder',
      ];
      generatorConfig.listConfig.buttonConfigs = jsonContent.listConfig.buttonConfigs.filter(
        (o) => {
          return !filterBtn.includes(o.code);
        },
      );
      generatorConfig.formJson = jsonContent.formJson;
      generatorConfig.formId = jsonContent.formId;
      generatorConfig.tableConfigs = jsonContent.tableConfigs;
      generatorConfig.menuConfig = jsonContent.menuConfig;
      generatorConfig.outputConfig = jsonContent.outputConfig;
      generatorConfig.formEventConfig =
        jsonContent.formEventConfig || ({} as FormEventColumnConfig);
      widgetForm.value = jsonContent.formJson;
      showContainer.value = true;
    }
    setModalProps({
      confirmLoading: false,
      canFullscreen: false,
      defaultFullscreen: true,
      maskClosable: false,
      destroyOnClose: true,
      draggable: false,
      showOkBtn: false,
      showCancelBtn: false,
      footer: null,
      closable: false,
    });
  });

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

  async function handleSaveDraft() {
    menuConfigStep.value.getFormData();
    await setParams(-1);
    handleClose();
    emit('success');
  }
  async function handleCodeGenerator() {
    const isOk = await stepValidate[5]();
    if (!isOk) {
      return;
    }
    await setParams(enabledMark.value);
    handleClose();
    emit('success');
  }
  async function setParams(enabledMark) {
    if (
      generatorConfig.formJson?.hiddenComponent &&
      generatorConfig.formJson?.hiddenComponent.length
    ) {
      generatorConfig.formJson.list.push(...generatorConfig.formJson.hiddenComponent);
    }

    let frontCode = buildAppCode(
      generatorConfig,
      buildAppFormProps(generatorConfig.formJson) as AppFormProps,
      designType.value,
    );

    const data: AppFuncModel = {
      codeSchemaId: generatorConfig.outputConfig.formObj!.formId,
      codes: frontCode,
      enabledMark: enabledMark,
      formType: generatorConfig.outputConfig.funcType!,
      funcDescribe: generatorConfig.outputConfig.comment,
      funcModule: generatorConfig.outputConfig.outputArea,
      jsonContent: JSON.stringify(generatorConfig),
      menuConfigs: {
        code: generatorConfig.menuConfig?.code,
        name: generatorConfig.menuConfig?.name,
        remark: generatorConfig.menuConfig?.remark,
        sortCode: generatorConfig.menuConfig?.sortCode,
        icon: generatorConfig.menuConfig?.icon,
        categoryId: generatorConfig.menuConfig?.parentId,
      },
      remark: generatorConfig.outputConfig.remarks,
    };
    if (data.formType === 1) {
      data.isGeneratorCode = generatorConfig!.outputConfig!.createCode ? 1 : 0;
    }
    if (templateId.value) {
      data.id = templateId.value;
      data.appMenuId = appMenuId.value;
      await editMobileFuncData(data);
    } else {
      await addMobileFunc(data);
    }
  }
  const handleClose = () => {
    closeModal();
    current.value = 0;
    emit('close');
  };

  const stepValidate = {
    //数据表配置 验证
    0: () => tableConfigStepRef.value.validateStep(),
    1: () => formDesignStepRef.value.validateStep(),
    2: () => formEventStepRef.value.validateStep(),
    3: () => viewDesignStep.value.validateStep(),
    4: () => previewCodeStep.value.validateStep(),
    5: () => menuConfigStep.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;
      line-height: 30px;
      animation: rotation 4s linear infinite;
      position: relative;

      &::before {
        border: 2px dashed #1890ff;
        content: '';
        width: 36px;
        height: 36px;
        display: block;
        border-radius: 50%;
        position: absolute;
        left: -4px;
        top: -4px;
      }

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

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

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