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

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

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

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

import { QueryApi, TableApi } from '#/api';

import StepBaseConfig from './step/baseConfig.vue';
import StepButtonConfig from './step/buttonConfig.vue';
import StepColumnConfig from './step/columnConfig.vue';
import StepSearchConfig from './step/searchConfig.vue';

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

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

const columns = ref<QueryApi.Column[]>([]);
provide('page-columns', columns);

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 === state.stepItems.length - 1 ? '确定' : '下一步',
      cancelText: state.stepIndex === 0 ? '取消' : '上一步',
    });
  },
  onConfirm: async () => {
    setState({ confirmLoading: true });
    try {
      if (
        state.stepIndex === 0 &&
        (await stepBaseConfig.value.stepValidate())
      ) {
        const values = await stepBaseConfig.value.stepGetValues();
        columns.value = await QueryApi.getColumns(values.databaseQueryCode);
        Object.assign(modelRef.value, values);
        await stepSearchConfig.value.stepSetValues({ ...unref(modelRef) });
        state.stepIndex += 1;
        setState({
          confirmText:
            state.stepIndex === state.stepItems.length - 1 ? '确定' : '下一步',
          cancelText: state.stepIndex === 0 ? '取消' : '上一步',
        });
      } else if (
        state.stepIndex === 1 &&
        (await stepSearchConfig.value.stepValidate())
      ) {
        await stepColumnConfig.value.stepSetValues({ ...unref(modelRef) });
        state.stepIndex += 1;
        setState({
          confirmText:
            state.stepIndex === state.stepItems.length - 1 ? '确定' : '下一步',
          cancelText: state.stepIndex === 0 ? '取消' : '上一步',
        });
      } else if (
        state.stepIndex === 2 &&
        (await stepColumnConfig.value.stepValidate())
      ) {
        await stepButtonConfig.value.stepSetValues({ ...unref(modelRef) });
        state.stepIndex += 1;
        setState({
          confirmText:
            state.stepIndex === state.stepItems.length - 1 ? '确定' : '下一步',
          cancelText: state.stepIndex === 0 ? '取消' : '上一步',
        });
      } else if (
        state.stepIndex === 3 &&
        (await stepButtonConfig.value.stepValidate())
      ) {
        const searchConfig = await stepSearchConfig.value.stepGetValues();
        const columnConfig = await stepColumnConfig.value.stepGetValues();
        const buttomConfig = await stepButtonConfig.value.stepGetValues();

        const postParams = unref(modelRef);

        postParams.config = {
          search: searchConfig,
          columns: columnConfig,
          buttons: buttomConfig,
        };

        await (unref(isUpdate)
          ? TableApi.editDetail(postParams as TableApi.RecordItem)
          : TableApi.addDetail(postParams as TableApi.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 TableApi.getDetail(data.baseData.id);
        modelRef.value = { ...entity };
        stepBaseConfig.value.stepSetValues(entity);
      }
      setState({ loading: false });
    }
  },
  title: '新增页面',
});
</script>
<template>
  <Modal class="w-[1000px]">
    <div class="h-full">
      <Steps
        :current="state.stepIndex"
        :items="state.stepItems"
        :percent="60"
        :style="state.stepStyle"
      />
      <div style="height: calc(100% - 82px)">
        <StepBaseConfig v-show="state.stepIndex === 0" ref="stepBaseConfig" />
        <StepSearchConfig
          v-show="state.stepIndex === 1"
          ref="stepSearchConfig"
        />
        <StepColumnConfig
          v-show="state.stepIndex === 2"
          ref="stepColumnConfig"
        />
        <StepButtonConfig
          v-show="state.stepIndex === 3"
          ref="stepButtonConfig"
        />
      </div>
    </div>
  </Modal>
</template>
