<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>
        <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" 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">
      <FormDesignStep ref="formDesignStepRef" v-show="current === 0" />
      <StructureConfigStep
        ref="structureConfigStepRef"
        v-show="current === 1"
        :isUpdate="isUpdate"
        :beforeTableNames="beforeTableNames"
        @validate-table="handleStepNext"
      />
      <ViewDesignStep ref="viewDesignStepRef" :isUpdate="isUpdate" v-show="current === 2" />
      <MenuConfigStep ref="menuConfigStepRef" v-show="current === 3" />
    </div>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, reactive, provide, Ref, toRaw } from 'vue';
  import MenuConfigStep from './MenuConfigStep.vue';
  import FormDesignStep from './FormDesignStep.vue';
  import StructureConfigStep from './StructureConfigStep.vue';
  import ViewDesignStep from './ViewDesignStep.vue';

  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { QuestionnaireConfig } from '/@/model/generator/generatorConfig';
  import { TableInfo } from '/@/components/Designer';
  import {
    addQuestionnaire,
    updateQuestionnaire,
    getQuestionnaireInfo,
  } from '../../../../api/questionnaire/design';
  import { noHaveTableAndField } from '/@/components/Designer';
  import * as antd from '/@/components/Designer/src/types';
  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';
  const { t } = useI18n();
  const current = ref(0);

  const menuConfigStepRef = ref();
  const formDesignStepRef = ref();
  const structureConfigStepRef = ref();
  const viewDesignStepRef = ref();

  const widgetForm = ref(JSON.parse(JSON.stringify(antd.widgetForm)));
  const isUpdate = ref<boolean>(false);
  const tableInfo = ref<TableInfo[]>([]);
  const formId = ref<string>('');
  const beforeTableNames = ref<string[]>([]);
  const mainTableName = ref('table_' + random(10000, 99999));
  let generatorConfig = reactive<QuestionnaireConfig>({
    databaseId: '', //数据库id
    category: '',
    className: '',
    name: '',
    outputArea: '',
    remark: '',
    formJson: {} as FormJson,
    tableStructureConfigs: [],
    isCommonFields: false,
    menuConfig: {},
    columnConfigs: [],
  });

  provide<QuestionnaireConfig>('generatorConfig', generatorConfig as QuestionnaireConfig);
  provide<Ref<TableInfo[]>>('tableInfo', tableInfo);
  provide<Ref<number>>('current', current); //当前步骤
  provide('widgetForm', widgetForm);
  provide<Ref<string>>('mainTableName', mainTableName);
  provide<Ref<boolean>>('isFieldUpper', ref(false));
  provide<string>('designType', 'code');

  const emits = defineEmits(['success', 'register', 'close']);

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({
      confirmLoading: false,
      canFullscreen: false,
      defaultFullscreen: true,
      destroyOnClose: true,
      draggable: false,
      showOkBtn: false,
      showCancelBtn: false,
      footer: null,
      closable: false,
    });
    isUpdate.value = !!data.isUpdate;
    formId.value = data.id;
    if (formId.value) {
      getFormTemplateInfo();
    }
  });

  async function getFormTemplateInfo() {
    const data = await getQuestionnaireInfo(formId.value);

    const info = JSON.parse(data.content) as QuestionnaireConfig;
    generatorConfig.databaseId = info.databaseId;
    generatorConfig.isCommonFields = info.isCommonFields;
    generatorConfig.tableStructureConfigs = info.tableStructureConfigs;
    generatorConfig.formJson = info.formJson;
    generatorConfig.formJson.list = info.formJson.list;
    generatorConfig.remark = info.remark;
    generatorConfig.name = info.name;
    generatorConfig.category = info.category;
    generatorConfig.className = info.className;
    generatorConfig.outputArea = info.outputArea;
    generatorConfig.comment = info.comment;
    generatorConfig.menuConfig = info.menuConfig;
    generatorConfig.columnConfigs = info.columnConfigs;

    getMainTableFirst(generatorConfig.formJson.list);
    widgetForm.value = generatorConfig.formJson;

    structureConfigStepRef.value.setFieldsValue({
      name: generatorConfig?.name,
      category: generatorConfig?.category,
      className: generatorConfig?.className,
      comment: generatorConfig?.comment,
      outputArea: generatorConfig?.outputArea,
      isCommonFields: generatorConfig?.isCommonFields,
      remark: generatorConfig?.remark,
    });

    menuConfigStepRef.value.setFieldsValue({
      ...generatorConfig.menuConfig,
    });

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

  function getMainTableFirst(list) {
    list.some((x) => {
      if (!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 === 3) {
      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;
    }
    if (isUpdate.value) {
      await updateQuestionnaire({ id: formId.value, ...toRaw(generatorConfig) });
    } else {
      await addQuestionnaire(toRaw(generatorConfig));
    }
    closeModal();
    emits('success');
    emits('close');
  }

  const stepValidate = {
    //数据表配置 验证
    0: () => formDesignStepRef.value.validateStep(),
    1: () => structureConfigStepRef.value.validateStep(),
    2: () => viewDesignStepRef.value.validateStep(),
    3: () => menuConfigStepRef.value.validateStep(),
  };
</script>
