<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 < 1">
            {{ t('下一步') }}
          </a-button>
          <a-button type="primary" @click="handleSave" v-show="current === 1">
            {{ 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-steps>
      </div>
    </template>
    <div class="step-container">
      <BasicConfigStep ref="basicConfigStepRef" v-show="current === 0" />
      <FormDesignStep ref="formDesignStepRef" v-show="current === 1" :saveFormTemplate="false" />
    </div>
    <LoadingBox v-if="spinning" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, reactive, provide, Ref, toRaw, watch } from 'vue';
  import { FormDesignStep } from '/@/components/CreateCodeStep';
  import BasicConfigStep from './BasicConfigStep.vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import {
    FormTemplateConfig,
    CustomFormJson,
    GeneratorConfig,
  } from '/@/model/generator/generatorConfig';
  import { TableInfo } from '/@/components/Designer';
  import { addFormTemplate, editFormTemplate, getFormTemplateInfo } from '/@/api/form/formTemplate';
  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';
  import html2canvas from 'html2canvas';
  import { dataURLtoBlob } from '/@/utils/file/base64Conver';
  import { uploadApi } from '/@/api/sys/upload';
  import { LoadingBox } from '/@/components/ModalPanel/index';

  const { t } = useI18n();
  const current = ref(0);
  const spinning = ref<boolean>(false);
  const basicConfigStepRef = ref();
  const formDesignStepRef = ref();
  const widgetForm = ref(JSON.parse(JSON.stringify(antd.widgetForm)));
  const isUpdate = ref<boolean>(false);
  const tableInfo = ref<TableInfo[]>([]);
  const templateId = ref<string>('');
  const beforeTableNames = ref<string[]>([]);
  const mainTableName = ref('table_' + random(10000, 99999));
  let generatorConfig = reactive<CustomFormJson>({
    databaseId: '', //数据库id
    formJson: {} as FormJson,
    tableStructureConfigs: [],
  });

  let formTemplateConfig = reactive<FormTemplateConfig>({
    name: '',
    code: '',
    formJson: generatorConfig,
    remark: '',
    backgroundUrl: '',
    sortCode: 0,
    source: 0,
  });

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

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

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

  async function getFormTemplateDetail() {
    const data = await getFormTemplateInfo(templateId.value);
    formTemplateConfig.name = data.name;
    formTemplateConfig.code = data.code;
    formTemplateConfig.backgroundUrl = data.backgroundUrl;
    formTemplateConfig.remark = data.remark;
    formTemplateConfig.sortCode = data.sortCode;

    formTemplateConfig.formJson = JSON.parse(data.formJson);

    const { formJson } = formTemplateConfig;
    generatorConfig.databaseId = formJson.databaseId;
    generatorConfig.tableStructureConfigs = formJson.tableStructureConfigs;

    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: formTemplateConfig?.name,
      code: formTemplateConfig?.code,
      sortCode: formTemplateConfig?.sortCode,
      remark: formTemplateConfig?.remark,
    });

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

  async function handleSave() {
    const isOk = await stepValidate[1]();
    if (!isOk) {
      return;
    }
    spinning.value = true;
    setTimeout(async () => {
      try {
        const element = formDesignStepRef.value.designFormRef.antdWidgetFormRef.widgetFormRef;
        let canvas = await html2canvas(element, {
          backgroundColor: '#f5f5f5',
          useCORS: true,
          windowHeight: document.body.scrollHeight,
        });
        const url = canvas.toDataURL();
        const blob = dataURLtoBlob(url);
        const data = await uploadApi({
          name: 'file',
          file: blob,
          filename: 'bg.png',
        });
        toRaw(formTemplateConfig).backgroundUrl = data.fileUrl;

        if (isUpdate.value) {
          await editFormTemplate({
            id: templateId.value,
            ...toRaw(formTemplateConfig),
          });
        } else {
          await addFormTemplate(toRaw(formTemplateConfig));
        }
        handleClose();
        emits('success');
        spinning.value = false;
      } catch (error) {
        spinning.value = false;
      }
    }, 100);
  }

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