<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('表单设计') }} - {{ t('无表表单') }}</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 < 3">
            {{ t('下一步') }}
          </a-button>
          <a-button type="primary" @click="handleSave" v-show="current === 3">
            {{ t('保存') }}
          </a-button>
          <a-button type="primary" @click="handleDraft">{{ 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">
      <BasicConfigStep ref="basicConfigStepRef" v-show="current === 0" />
      <FormDesignStep ref="formDesignStepRef" v-show="current === 1" />
      <FormEventStep ref="formEventStepRef" v-show="current === 2" />
      <StructureConfigStep
        ref="structureConfigStepRef"
        v-show="current === 3"
        :isUpdate="isUpdate"
        :beforeTableNames="beforeTableNames"
        @validate-table="handleSave"
      />
    </div>
  </BasicModal>
  <DraftModal v-if="isShowDraft" @change-draft="changeDraft" />
</template>
<script lang="ts" setup>
  import { ref, reactive, provide, Ref, toRaw, watch } from 'vue';
  import { FormDesignStep, FormEventStep, StructureConfigStep } from '/@/components/CreateCodeStep';
  import BasicConfigStep from '../BasicConfigStep.vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import {
    CustomFormConfig,
    CustomFormJson,
    GeneratorConfig,
  } from '/@/model/generator/generatorConfig';
  import { TableInfo } from '/@/components/Designer';
  import {
    addNoTableFormTemplate,
    updateNoTableFormTemplate,
    getFormTemplate,
    saveDraftFormTemplate,
  } from '/@/api/form/design';
  import { noHaveTableAndField } from '/@/components/Designer';
  import * as antd from '/@/components/Designer/src/types';
  import { FormTypeEnum } from '/@/enums/formtypeEnum';
  import DesignLogo from '/@/components/ModalPanel/src/DesignLogo.vue';
  import { random } from 'lodash-es';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { FormJson } from '/@/model/generator/codeGenerator';
  import { FormEventColumnConfig } from '/@/model/generator/formEventConfig';
  import { changeCompsApiConfig, changeEventApiConfig, getMainTable } from '/@/utils/event/design';
  import DraftModal from './DraftModal.vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  const { notification } = useMessage();
  const { t } = useI18n();
  const current = ref(0);

  const basicConfigStepRef = ref();
  const formDesignStepRef = ref();
  const formEventStepRef = ref();
  const structureConfigStepRef = ref();
  const widgetForm = ref(JSON.parse(JSON.stringify(antd.widgetForm))); //FormDesignStep -> designer和StructureConfigStep页面使用
  const isUpdate = ref<boolean>(false);
  const tableInfo = ref<TableInfo[]>([]);
  const formId = ref<string>('');
  const beforeTableNames = ref<string[]>([]);
  const mainTableName = ref('table_' + random(10000, 99999));
  const isDraft = ref(false);
  const isShowDraft = ref(false);
  const interfaceInfo = [
    {
      key: '1',
      title: 'Query Params',
      tableInfo: [],
    },
    {
      key: '2',
      title: 'Header',
      tableInfo: [],
    },
    {
      key: '3',
      title: 'Body',
      tableInfo: [],
    },
  ];
  let generatorConfig = reactive<CustomFormJson>({
    formJson: {} as FormJson,
    tableStructureConfigs: [],
    formEventConfig: {} as FormEventColumnConfig,
    apiConfig: [
      {
        title: '新增',
        value: 'add',
        method: '',
        path: '',
        apiId: '',
        apiParams: interfaceInfo,
      },
      {
        title: '编辑',
        value: 'edit',
        method: '',
        path: '',
        apiId: '',
        apiParams: interfaceInfo,
      },
      {
        title: '删除',
        value: 'delete',
        method: '',
        path: '',
        apiId: '',
        apiParams: interfaceInfo,
      },
      {
        title: '查看',
        value: 'view',
        method: '',
        path: '',
        apiId: '',
        apiParams: interfaceInfo,
        outputConfig: [],
      },
    ],
  });

  let customFormConfig = reactive<CustomFormConfig>({
    name: '',
    category: '',
    formDesignType: 3,
    formType: FormTypeEnum.CUSTOM_FORM,
    formJson: generatorConfig,
    remark: '',
    isChange: false,
  });

  provide<GeneratorConfig>('generatorConfig', generatorConfig as GeneratorConfig);
  provide<CustomFormConfig>('customFormConfig', customFormConfig);
  provide<Ref<TableInfo[]>>('tableInfo', tableInfo);
  provide<Ref<number>>('current', current); //当前步骤
  provide<string>('designType', 'notable');
  provide('widgetForm', widgetForm);
  provide<Ref<string>>('mainTableName', mainTableName);
  provide<boolean>('isCustomForm', true); //是自定义表单
  provide<Ref<boolean>>('isFieldUpper', ref(false));

  watch(
    () => generatorConfig,
    (val) => {
      customFormConfig.formJson = val;
    },
    {
      deep: true,
    },
  );
  const emits = defineEmits(['success', 'register', 'close']);

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    isUpdate.value = !!data.isUpdate;
    formId.value = data.id;
    isDraft.value = !!data.isDraft;

    customFormConfig.isChange = isUpdate.value;
    if (formId.value) {
      getFormTemplateInfo();
    }
    setModalProps({
      confirmLoading: false,
      canFullscreen: false,
      defaultFullscreen: true,
      destroyOnClose: true,
      draggable: false,
      showOkBtn: false,
      showCancelBtn: false,
      footer: null,
      closable: false,
    });
  });

  async function getFormTemplateInfo() {
    const data = await getFormTemplate(formId.value);
    customFormConfig.name = data.name;
    customFormConfig.category = data.category;
    customFormConfig.formDesignType = data.formDesignType;
    customFormConfig.formJson = JSON.parse(data.formJson);
    customFormConfig.remark = data.remark;

    const { formJson } = customFormConfig;

    generatorConfig.databaseId = formJson.databaseId;
    generatorConfig.isDataAuth = formJson.isDataAuth;
    generatorConfig.dataAuthList = formJson.dataAuthList;
    generatorConfig.isCommonFields = formJson.isCommonFields;
    generatorConfig.tableStructureConfigs = formJson.tableStructureConfigs;
    generatorConfig.formEventConfig = formJson.formEventConfig!;

    if (formJson.apiConfig) {
      generatorConfig.apiConfig = formJson.apiConfig!;
    }
    if (formJson.formJson.list) {
      generatorConfig.formJson = formJson.formJson;
      generatorConfig.formJson.list = generatorConfig.formJson.list?.filter(
        (x) => x.type !== 'hiddenComponent',
      );
      if (generatorConfig.formJson.list?.length) {
        getMainTableFirst(generatorConfig.formJson.list);
      }
      widgetForm.value = generatorConfig.formJson;
    }
    basicConfigStepRef.value.setFieldsValue({
      name: customFormConfig?.name,
      category: customFormConfig?.category,
      remark: customFormConfig?.remark,
      databaseId: generatorConfig.databaseId,
      isDataAuth: generatorConfig.isDataAuth,
      dataAuthList: generatorConfig.dataAuthList,
      isCommonFields: generatorConfig.isCommonFields,
    });

    beforeTableNames.value = generatorConfig.tableStructureConfigs!.map((x) => x.tableName);
  }

  function getMainTableFirst(list) {
    list.some((x) => {
      if (['tab', 'grid', 'card'].includes(x.type)) {
        for (const child of x.layout!) {
          return getMainTableFirst(child.list);
        }
      } else if (x.type === 'table-layout') {
        for (const child of x.layout!) {
          for (const el of child.list!) {
            return getMainTableFirst(el.children);
          }
        }
      } else if (
        x.type !== 'form' &&
        x.type !== 'one-for-one' &&
        !noHaveTableAndField.includes(x.type)
      ) {
        mainTableName.value = x.bindTable;
        return true;
      }
    });
  }

  function handleClose() {
    closeModal();
    emits('close');
  }

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

  async function handleSave() {
    const isOk = await stepValidate[3]();
    if (!isOk) {
      return;
    }

    let tableFieldConfigs = getMainTable(generatorConfig.tableStructureConfigs);
    changeCompsApiConfig(generatorConfig!.formJson.list, 'code', tableFieldConfigs);
    changeEventApiConfig(generatorConfig!.formEventConfig, 'code', tableFieldConfigs);

    if (
      generatorConfig.formJson?.hiddenComponent &&
      generatorConfig.formJson?.hiddenComponent.length
    ) {
      generatorConfig.formJson.list.push(...generatorConfig.formJson.hiddenComponent);
    }
    if (isUpdate.value) {
      await updateNoTableFormTemplate({ id: formId.value, ...toRaw(customFormConfig) });
    } else {
      await addNoTableFormTemplate(toRaw(customFormConfig));
    }
    emits('success');
  }

  async function handleDraft() {
    if (
      generatorConfig.formJson?.hiddenComponent &&
      generatorConfig.formJson?.hiddenComponent.length
    ) {
      generatorConfig.formJson.list.push(...generatorConfig.formJson.hiddenComponent);
    }
    if (!isDraft.value && isUpdate.value) {
      isShowDraft.value = true;
    } else {
      const params: any = toRaw(customFormConfig);
      if (isUpdate.value) {
        params.id = formId.value;
      }
      let res = await saveDraftFormTemplate(params);
      if (res) {
        formId.value = res?.formId;
        isDraft.value = res?.status === 0;
        isUpdate.value = true;
      }
      notification.success({
        message: t('提示'),
        description: t(`保存${res ? '成功' : '失败'}`),
      });
      if (res) emits('success');
    }
  }

  async function changeDraft(type) {
    switch (type) {
      case 'cancel':
        isShowDraft.value = false;
        break;
      case 'add':
        await saveDraftFormTemplate(toRaw(customFormConfig));
        closeModal();
        emits('success');
        emits('close');
        break;
      case 'edit':
        await saveDraftFormTemplate({
          id: formId.value,
          ...toRaw(customFormConfig),
        });
        closeModal();
        emits('success');
        emits('close');
        break;
    }
  }

  const stepValidate = {
    //数据表配置 验证
    0: () => basicConfigStepRef.value.validateStep(),
    1: () => formDesignStepRef.value.validateStep(),
    2: () => formEventStepRef.value.validateStep(),
    3: () => structureConfigStepRef.value.validateStep(),
  };
</script>
<style lang="less" scoped></style>
