<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('弹窗设计') }}</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="handleCodeGenerator" v-show="current === 2">
            {{ 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">
      <TableConfigStep ref="tableConfigStepRef" v-if="current === 0" />
      <FormDesignStep ref="formDesignStepRef" v-show="current === 1" />
      <OutParamsStep ref="menuConfigStep" v-if="current === 2" />
    </div>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, reactive, provide, Ref, defineAsyncComponent } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { GeneratorConfig, ModalConfig } from '/@/model/generator/generatorConfig';
  import { TableInfo } from '/@/components/Designer';

  import { LoadingBox } from '/@/components/ModalPanel/index';

  import { FormJson } from '/@/model/generator/codeGenerator';

  import * as antd from '/@/components/Designer/src/types';
  import { useI18n } from '/@/hooks/web/useI18n';
  import DesignLogo from '/@/components/ModalPanel/src/DesignLogo.vue';

  import { random } from 'lodash-es';

  import { addModalManage, getModalManage, updateModalManage } from '/@/api/dataconfig/modalmanage';

  const { t } = useI18n();
  const TableConfigStep = defineAsyncComponent({
    loader: () => import('./TableConfigStep.vue'),
    loadingComponent: LoadingBox,
  });
  const FormDesignStep = defineAsyncComponent({
    loader: () => import('/@/components/CreateCodeStep/src/FormDesignStep.vue'),
    loadingComponent: LoadingBox,
  });
  const OutParamsStep = defineAsyncComponent({
    loader: () => import('./OutParamsStep.vue'),
    loadingComponent: LoadingBox,
  });
  provide<boolean>('isCustomForm', true);
  const templateId = ref();

  const current = ref(0);

  const isUpdate = ref(false);
  const tableConfigStepRef = ref();

  const formDesignStepRef = ref();

  const menuConfigStep = ref();

  const widgetForm = ref(JSON.parse(JSON.stringify(antd.widgetForm))); //FormDesignStep -> designer和StructureConfigStep页面使用
  const tableInfo = ref<TableInfo[]>([]);

  const emit = defineEmits(['close', 'register', 'success']);
  let generatorConfig = reactive<ModalConfig>({
    name: '',
    code: '',
    category: '',
    formJson: {} as FormJson,
    state: '',
    remark: '',
    innerParams: [],
    outParams: [],
  });
  const mainTableName = ref('table_' + random(10000, 99999));
  provide<GeneratorConfig>('generatorConfig', generatorConfig);
  provide<Ref<TableInfo[]>>('tableInfo', tableInfo);
  provide<Ref<number>>('current', current); //当前步骤
  provide<string>('designType', 'code');
  provide('widgetForm', widgetForm);
  provide<Ref<string>>('mainTableName', mainTableName);

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({
      confirmLoading: false,
      canFullscreen: false,
      defaultFullscreen: true,
      maskClosable: false,
      destroyOnClose: true,
      draggable: false,
      showOkBtn: false,
      showCancelBtn: false,
      footer: null,
      closable: false,
    });
    isUpdate.value = data.isUpdate || false;
    templateId.value = data.isUpdate ? data.id : '';
    if (data.isUpdate) {
      let res: any = await getModalManage(data.id);

      if (res) {
        const { code, category, name, remark, state, configJson } = res;

        generatorConfig.code = code;
        generatorConfig.name = name;
        generatorConfig.remark = remark;
        generatorConfig.category = category;
        generatorConfig.state = state;
        let json = JSON.parse(configJson);

        let formJson = json.formJson;
        formJson.list = formJson?.list?.filter((x) => x.type !== 'hiddenComponent') || [];
        generatorConfig.formJson = formJson;
        generatorConfig.innerParams = json.innerParams;
        generatorConfig.outParams = json.outParams;
        widgetForm.value = formJson;
      }
    }
  });

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

  async function handleCodeGenerator() {
    const isOk = await stepValidate[2]();
    if (
      generatorConfig.formJson?.hiddenComponent &&
      generatorConfig.formJson?.hiddenComponent.length
    ) {
      generatorConfig.formJson.list.push(...generatorConfig.formJson.hiddenComponent);
    }

    if (!isOk) {
      return;
    }
    let data = {
      name: generatorConfig.name,
      code: generatorConfig.code,
      category: generatorConfig.category,
      configJson: {
        formJson: generatorConfig.formJson,
        innerParams: generatorConfig.innerParams,
        outParams: generatorConfig.outParams,
      },
      state: generatorConfig.state,
      remark: generatorConfig.remark,
    };
    if (templateId.value) {
      data.id = templateId.value;
      await updateModalManage(data);
    } else {
      await addModalManage(data);
    }

    handleClose();
    emit('success');
  }

  const handleClose = () => {
    current.value = 0;
    generatorConfig.name = '';

    generatorConfig.code = '';
    generatorConfig.category = '';

    generatorConfig.state = '';
    generatorConfig.remark = '';

    generatorConfig.outParams = [];
    generatorConfig.innerParams = [];
    generatorConfig.formJson = {} as FormJson;
    widgetForm.value = JSON.parse(JSON.stringify(antd.widgetForm));
    closeModal();
    emit('close');
  };

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