<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 < 2">
            {{ t('下一步') }}
          </a-button>
          <a-button type="primary" @click="handleSave" v-show="current === 2">
            {{ 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-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" />
    </div>
  </BasicModal>
  <DraftModal v-if="isShowDraft" @change-draft="changeDraft" />
  <TableNameModal @register="registerTableName" @success="handleEditSuccess" />
</template>
<script lang="ts" setup>
  import { ref, reactive, provide, Ref, toRaw, watch, onMounted } from 'vue';
  import { FormDesignStep, FormEventStep, TableNameModal } from '/@/components/CreateCodeStep';
  import BasicConfigStep from '../BasicConfigStep.vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { GeneratorConfig, CustomFormConfig } from '/@/model/generator/generatorConfig';
  import { TableInfo, upperFieldDb } from '/@/components/Designer';
  import { validateTableName, getMasterInfo } from '/@/api/system/generator';
  import {
    addCodeFirstFormTemplate,
    updateCodeFirstFormTemplate,
    getFormTemplate,
    saveDraftFormTemplate,
  } from '/@/api/form/design';
  import { FormTypeEnum } from '/@/enums/formtypeEnum';
  import * as antd from '/@/components/Designer/src/types';
  import { random } from 'lodash-es';
  import { noHaveTableAndField } from '/@/components/Designer';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useModal } from '/@/components/Modal';
  import DesignLogo from '/@/components/ModalPanel/src/DesignLogo.vue';
  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 widgetForm = ref(JSON.parse(JSON.stringify(antd.widgetForm))); //FormDesignStep -> designer和StructureConfigStep页面使用
  const mainTableName = ref('table_' + random(10000, 99999));

  const tableInfo = ref<TableInfo[]>([]);
  const isUpdate = ref<boolean>(false);
  const formId = ref<string>('');
  const beforeTableNames = ref<string[]>([]);
  const isFieldUpper = ref<boolean>(false);
  const isDraft = ref(false);
  const isShowDraft = ref(false);
  let generatorConfig = reactive<GeneratorConfig>({
    databaseId: 'master',
    formJson: {},
    tableStructureConfigs: [],
    formEventConfig: {},
    isDataAuth: false,
    dataAuthList: [],
  });

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

  const [registerTableName, { openModal, closeModal: closeTableNameModal }] = useModal();

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

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

  onMounted(async () => {
    const res = await getMasterInfo();
    isFieldUpper.value = upperFieldDb.includes(res?.dbType || '');
    mainTableName.value = isFieldUpper.value
      ? mainTableName.value.toUpperCase()
      : mainTableName.value;
  });

  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!;

    beforeTableNames.value = generatorConfig.tableStructureConfigs?.map((x) => x.tableName) || [];

    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,
    });
  }

  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() {
    const isOk = await stepValidate[current.value]();
    if (!isOk) {
      return;
    }
    current.value++;
  }
  async function handleSave() {
    const isOk = await stepValidate[2]();

    if (!isOk) {
      return;
    }
    const tableNames: string[] = generatorConfig.tableStructureConfigs!.map((x) => x.tableName);

    const testTableNames = tableNames.filter((x) => {
      return !beforeTableNames.value.includes(x);
    });

    if (!isUpdate.value || (isUpdate.value && testTableNames.length)) {
      const names = isUpdate.value ? testTableNames.toString() : tableNames.toString();
      validateName(names);
    } else {
      submitTemplate();
    }
  }

  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 validateName = (tableNames) => {
    const params = {
      id: 'master',
      tableNames,
    };
    validateTableName(params, 'none')
      .then(() => {
        submitTemplate();
      })
      .catch((err) => {
        if (!err) return;
        const info = err.message.split('[')[1];
        const existTableName = info.substring(0, info.length - 1).split(',');
        const newTableName: string[] = [];
        generatorConfig?.tableStructureConfigs!.map((table) => {
          const tableName = 'table_' + random(10000, 99999);
          if (existTableName.includes(table.tableName)) {
            table.tableName = tableName;
          }
          newTableName.push(tableName);
          generatorConfig.formJson.list.map((component) => {
            editTableName(component, existTableName, tableName);
          });
        });
        validateName(newTableName.toString());
      });
  };
  const editTableName = (component, existTableName, tableName) => {
    if (existTableName.includes(component.bindTable)) {
      component.bindTable = tableName;
      if (component.children || component.layout || component.list) {
        editTableName(component.children, existTableName, tableName);
      }
    }
  };

  const submitTemplate = async () => {
    if (
      generatorConfig.formJson?.hiddenComponent &&
      generatorConfig.formJson?.hiddenComponent.length
    ) {
      generatorConfig.formJson.list.push(...generatorConfig.formJson.hiddenComponent);
    }
    if (isUpdate.value) {
      openModal();
    } else {
      await addCodeFirstFormTemplate(toRaw(customFormConfig));
      emits('success');
    }
  };

  async function handleEditSuccess() {
    await updateCodeFirstFormTemplate({ id: formId.value, ...toRaw(customFormConfig) });
    closeTableNameModal();
    emits('success');
  }

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