<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 type="primary" @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">
          <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" :isUpdate="isUpdate" />
      <FormDesignStep ref="formDesignStepRef" v-show="current === 1" />
      <FormEventStep ref="formEventStepRef" v-show="current === 2" />
    </div>
  </BasicModal>
  <DraftModal v-if="isShowDraft" @change-draft="changeDraft" />
</template>
<script lang="ts" setup>
  import { ref, reactive, provide, watch, Ref, toRaw } from 'vue';
  import BasicConfigStep from '../BasicConfigStep.vue';
  import { FormDesignStep, FormEventStep } from '/@/components/CreateCodeStep';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { CustomFormConfig, GeneratorConfig } from '/@/model/generator/generatorConfig';
  import { TableInfo } from '/@/components/Designer';
  import {
    addDataFirstFormTemplate,
    updateDataFirstFormTemplate,
    getFormTemplate,
    saveDraftFormTemplate,
  } from '/@/api/form/design';
  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 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 tableInfo = ref<TableInfo[]>([]);
  const widgetForm = ref(JSON.parse(JSON.stringify(antd.widgetForm)));
  const isUpdate = ref<boolean>(false);
  const formId = ref<string>('');
  const emits = defineEmits(['success', 'register', 'close']);
  const isDraft = ref(false);
  const isShowDraft = ref(false);

  let generatorConfig = reactive<GeneratorConfig>({
    databaseId: '', //数据库id
    tableConfigs: [],
    formJson: {},
    formEventConfig: {},
    isDataAuth: false,
    dataAuthList: [],
  });
  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<string>('designType', 'data');
  provide('widgetForm', widgetForm);
  provide<Ref<number>>('current', current); //当前步骤
  provide<boolean>('isCustomForm', true); //是自定义表单

  watch(
    () => generatorConfig,
    (val) => {
      customFormConfig.formJson = val;
    },
    {
      deep: true,
    },
  );

  const [registerModal, { setModalProps, closeModal }] = useModalInner((data) => {
    isUpdate.value = !!data.isUpdate;
    formId.value = data.id;
    isDraft.value = !!data.isDraft;
    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.tableConfigs = formJson.tableConfigs;
    generatorConfig.formEventConfig = formJson.formEventConfig!;

    if (formJson.formJson.list) {
      generatorConfig.formJson = formJson.formJson;
      generatorConfig.formJson.list = generatorConfig.formJson.list?.filter(
        (x) => x.type !== 'hiddenComponent',
      );
      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,
    });
  }

  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;
    }
    if (
      generatorConfig.formJson?.hiddenComponent &&
      generatorConfig.formJson?.hiddenComponent.length
    ) {
      generatorConfig.formJson.list.push(...generatorConfig.formJson.hiddenComponent);
    }
    if (isUpdate.value) {
      await updateDataFirstFormTemplate({ id: formId.value, ...toRaw(customFormConfig) });
    } else {
      await addDataFirstFormTemplate(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(),
  };
</script>
<style lang="less" scoped></style>
