<script lang="ts" setup>
import type { BasicOptionResult } from '#/api/model';

import { reactive, ref, unref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { message, Steps } from 'ant-design-vue';

import { QueryApi } from '#/api';

import StepBaseConfig from './step/baseConfig.vue';
import StepDetailConfig from './step/detailConfig.vue';

defineOptions({
  name: 'QueryEdit',
});
const emit = defineEmits(['success']);
const modelRef = ref<Record<string, any>>({});
const isUpdate = ref(true);
const stepBaseConfig = ref();
const stepDetailConfig = ref();

const state = reactive<{
  dbBaseOptions: BasicOptionResult[];
  stepIndex: number;
  stepItems: any[];
  stepStyle: Record<string, any>;
}>({
  stepIndex: 0,
  stepItems: [
    { title: '基本信息', description: '基本数据设置' },
    { title: '查询设置', description: '查询列表设置' },
  ],
  stepStyle: { marginBottom: '20px' },
  dbBaseOptions: [],
});

const [Modal, { close, getData, setState }] = useVbenModal({
  fullscreenButton: false,
  fullscreen: true,
  draggable: true,
  cancelText: '上一步',
  confirmText: '下一步',
  onCancel() {
    if (state.stepIndex === 0) {
      close();
    } else {
      state.stepIndex -= 1;
    }
    setState({
      confirmText: state.stepIndex === 0 ? '下一步' : '确定',
      cancelText: state.stepIndex === 0 ? '取消' : '上一步',
    });
  },
  onConfirm: async () => {
    setState({ confirmLoading: true });
    try {
      if (
        state.stepIndex === 0 &&
        (await stepBaseConfig.value.stepValidate())
      ) {
        const values = await stepBaseConfig.value.stepGetValues();
        Object.assign(modelRef.value, values);
        await stepDetailConfig.value.stepSetValues({ ...unref(modelRef) });
        state.stepIndex += 1;
        setState({
          confirmText: state.stepIndex === 0 ? '下一步' : '确定',
          cancelText: state.stepIndex === 0 ? '取消' : '上一步',
        });
      } else if (
        state.stepIndex === 1 &&
        (await stepDetailConfig.value.stepValidate())
      ) {
        const { tables, columns } =
          await stepDetailConfig.value.stepGetValues();

        const postParams = unref(modelRef);

        postParams.tables = tables;
        postParams.columns = columns;

        await (unref(isUpdate)
          ? QueryApi.editDetail(postParams as QueryApi.RecordItem)
          : QueryApi.addDetail(postParams as QueryApi.BasicRecordItem));
        message.success('操作成功');

        close();
        emit('success');
      }
    } catch (error: any) {
      message.error(error?.message || '操作失败');
    } finally {
      setState({ confirmLoading: false });
    }
  },
  onOpenChange: async (isOpen: boolean) => {
    if (isOpen) {
      setState({ loading: true });
      const data = getData<Record<string, any>>();
      isUpdate.value = !!data.isUpdate;
      modelRef.value = { ...data.baseData };
      setState({
        title: unref(isUpdate) ? '编辑查询' : '新增查询',
        cancelText: '取消',
        confirmText: '下一步',
      });

      state.stepIndex = 0;

      if (unref(isUpdate)) {
        const entity = await QueryApi.getDetail(data.baseData.id);
        modelRef.value = { ...entity };
        stepBaseConfig.value.stepSetValues(entity);
      }
      setState({ loading: false });
    }
  },
  title: '新增查询',
});
</script>
<template>
  <Modal class="w-[1000px]">
    <div>
      <Steps
        :current="state.stepIndex"
        :items="state.stepItems"
        :percent="60"
        :style="state.stepStyle"
      />
      <div>
        <StepBaseConfig v-show="state.stepIndex === 0" ref="stepBaseConfig" />
        <StepDetailConfig
          v-show="state.stepIndex === 1"
          ref="stepDetailConfig"
        />
      </div>
    </div>
  </Modal>
</template>
