<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>{{ getTitle + 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="handleSubmit(1)" v-show="current === 1">
            {{ t('保存') }}
          </a-button>
          <a-button type="primary" @click="handleDraft()">{{ t('保存草稿') }}</a-button>
          <a-button type="primary" @click="handlePreview" 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">
      <ModalForm
        ref="formRef"
        v-model:value="state.formModel"
        v-show="current === 0"
        @get-form-json="handleGetJson"
      />
      <FormDesignStep ref="formDesignStepRef" v-if="current === 1" />
    </div>
    <PagePreview
      v-if="previewVisible"
      ref="previewRef"
      :formJson="widgetForm"
      @close="previewVisible = false"
    />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, reactive, provide, Ref, watch, h } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import PagePreview from './PagePreview.vue';
  import ModalForm from './Form.vue';
  import FormDesignStep from './FormDesignStep.vue';
  import DesignLogo from '/@/components/ModalPanel/src/DesignLogo.vue';
  import { addPageDesign, updatePageDesign } from '/@/api/system/pagedesign';
  import modal from 'ant-design-vue/lib/modal';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';

  const emit = defineEmits(['success', 'register', 'close']);
  const previewVisible = ref(false);
  const current = ref(0);
  const { notification } = useMessage();
  const formRef = ref();
  const isCopy = ref<boolean>(false);
  const widgetForm = ref([]);
  const widgetFormModel = ref({});
  const menuId = ref();
  const state = reactive({
    formModel: {},
    widgetForm: [],
    isUpdate: true,
    isView: false,
    isHistory: false,
    rowId: '',
  });
  provide<Ref<boolean>>('isCopy', isCopy);
  provide('widgetForm', widgetForm);
  provide('widgetFormModel', widgetFormModel);
  provide('previewVisible', previewVisible);
  watch(
    () => widgetForm.value,
    () => {},
    { deep: true },
  );
  const { t } = useI18n();
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    await handleInner(data);
  });

  const getTitle = computed(() =>
    state.isView ? '查看' : state.isUpdate ? '编辑' : isCopy.value ? '复制数据' : '新增',
  );

  async function handleInner(data) {
    state.isUpdate = !!data?.isUpdate;
    state.isView = !!data?.isView;
    isCopy.value = !!data?.isCopy;
    state.isHistory = !!data?.isHistory;
    menuId.value = data?.menuId;
    setModalProps({
      confirmLoading: false,
      canFullscreen: false,
      defaultFullscreen: true,
      destroyOnClose: true,
      draggable: false,
      showOkBtn: false,
      showCancelBtn: false,
      footer: null,
      closable: false,
    });

    if (state.isUpdate || state.isView || isCopy.value) {
      state.rowId = data.id;
      if (state.isView) {
        await formRef.value.setDisabledForm();
      }

      await formRef.value.setFormDataFromId(state.rowId, state.isHistory);
    } else {
      formRef.value.resetFields();
    }
  }
  function handleDraft() {
    if (menuId.value) {
      modal.confirm({
        title: '提示',
        icon: h(ExclamationCircleOutlined),
        content: '该设计已发布成菜单，再保存草稿会使菜单失效，是否修改？',
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          handleSubmit(0);
        },
        onCancel() {},
      });
    } else {
      handleSubmit(0);
    }
  }
  async function handleSubmit(isDraft) {
    try {
      setModalProps({ confirmLoading: true });

      if (!state.isUpdate || isCopy.value) {
        await addPageDesign({
          ...state.formModel,
          formJson: JSON.stringify(widgetForm.value),
          isDraft: isDraft,
        });
        //false 新增
        notification.success({
          message: 'Tip',
          description: isCopy.value ? '复制成功' : t('新增成功！'),
        }); //提示消息
      } else {
        let obj: any = {
          ...state.formModel,
          formJson: JSON.stringify(widgetForm.value),
          isDraft: isDraft,
        };
        if (!state.isHistory) {
          obj.id = state.rowId;
        }
        await updatePageDesign(obj);
        notification.success({
          message: 'Tip',
          description: t('修改成功！'),
        }); //提示消息
      }
      initData();
      closeModal();
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  function handleClose() {
    initData();
    closeModal();
    emit('close');
  }
  function initData() {
    current.value = 0;
    widgetForm.value = [];
    state.rowId = '';
    widgetFormModel.value = {};
  }
  //上一步
  function handleStepPrev() {
    current.value--;
  }
  //下一步
  async function handleStepNext() {
    if (current.value === 0) {
      const isOk = await formRef.value.validate();
      if (!isOk) {
        return;
      }
    }
    current.value++;
  }

  function handleGetJson(val) {
    widgetForm.value = val;
  }
  function handlePreview() {
    previewVisible.value = true;
  }
</script>
