<script lang="ts" setup>
/**
 * 小程序工作台功能入口新增/编辑弹窗
 * theme_color 为虚拟字段：回显时从存库 theme JSON 解析主色，提交时组装回 {bg,color}
 */
import { ref } from 'vue';

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

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

import { useVbenForm } from '#/adapter/form';

import { createWxWorkbenchEntry, updateWxWorkbenchEntry } from '../api';
import { buildThemeByColor, parseThemeColor } from '../config/constants';
import { modalFormProps } from '../config/form';

const isUpdate = ref(false);
const gridApi = ref();
const [Form, formApi] = useVbenForm(modalFormProps);
const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    const e = await formApi.validate();
    if (!e.valid) return;
    const values: Record<string, any> = await formApi.getValues();
    // 虚拟字段 theme_color → 完整主题对象；未选时不覆盖已有主题
    const theme = buildThemeByColor(values.theme_color || '');
    if (theme) {
      values.theme = theme;
    }
    delete values.theme_color;
    modalApi.setState({ confirmLoading: true });
    try {
      const api = isUpdate.value ? updateWxWorkbenchEntry : createWxWorkbenchEntry;
      await api(values);
      message.success('保存成功');
      gridApi.value?.query?.();
      modalApi.close();
    } finally {
      modalApi.setState({ confirmLoading: false });
    }
  },
  onOpenChange(isOpen: boolean) {
    gridApi.value = isOpen ? modalApi.getData()?.gridApi : null;
    if (!isOpen) {
      formApi.resetForm();
      return;
    }
    const { values, update } = modalApi.getData<Record<string, any>>() || {};
    isUpdate.value = !!update;
    // 编辑时锁定 code：小程序端按编码映射行为（角标/表单预填/弹窗），改码会导致行为失效
    formApi.updateSchema([
      {
        fieldName: 'code',
        componentProps: { disabled: !!update },
      },
    ]);
    if (values && update) {
      formApi.setValues({
        ...values,
        theme_color: parseThemeColor(values.theme),
      });
    } else {
      formApi.resetForm();
      formApi.setValues({ sort: 0, status: 1, icon: 'grid-fill', description: '', path: '' });
    }
  },
});
</script>
<template>
  <Modal :title="`${isUpdate ? '编辑' : '新增'}功能入口`" class="w-[560px]">
    <Form />
  </Modal>
</template>
