PanelDetailModal.vue 2.87 KB
<script lang="ts" setup>
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { formSchema, PlatformType } from '../config/panelDetail';
  import { addDataBoard, updateDataBoard } from '/@/api/dataBoard';
  import { AddDataBoardParams } from '/@/api/dataBoard/model';
  import { useMessage } from '/@/hooks/web/useMessage';
  import type { DataBoardRecord, UpdateDataBoardParams } from '/@/api/dataBoard/model';
  import { ref, unref } from 'vue';

  const emit = defineEmits(['change', 'register']);

  const isEdit = ref(false);
  const recordId = ref<Nullable<string>>(null);
  const loading = ref(false);

  const [registerModal, { changeLoading, closeModal }] = useModalInner(
    (record: DataBoardRecord & { isEdit: boolean }) => {
      method.setFieldsValue(record);
      recordId.value = record.id;
      isEdit.value = record.isEdit;
    }
  );

  const [registerForm, method] = useForm({
    showActionButtonGroup: false,
    schemas: formSchema,
    labelWidth: 80,
  });

  const { createMessage } = useMessage();

  const handleSubmitValue = (value: Recordable) => {
    if (!Reflect.get(value, 'accessCredentials')) {
      Reflect.deleteProperty(value, 'accessCredentials');
    }
    if (value.platform === PlatformType.PC) {
      Reflect.deleteProperty(value, 'phoneModel');
    }
    return value as any;
  };

  const handleCreatePanel = async () => {
    await method.validate();
    try {
      let value = method.getFieldsValue() as AddDataBoardParams;
      value = handleSubmitValue(value);
      loading.value = true;
      changeLoading(true);
      await addDataBoard(value);
      createMessage.success('创建成功');
      closeModal();
      emit('change');
    } catch (error) {
      createMessage.error('创建失败');
    } finally {
      changeLoading(false);
      loading.value = false;
    }
  };

  const handleEditPanel = async () => {
    await method.validate();
    try {
      loading.value = true;
      let value = method.getFieldsValue() as UpdateDataBoardParams;
      value = handleSubmitValue(value);
      value.id = unref(recordId) as string;
      changeLoading(true);
      await updateDataBoard(value);
      createMessage.success('编辑成功');
      closeModal();
      emit('change');
    } catch (error) {
      createMessage.error('编辑失败');
    } finally {
      changeLoading(false);
      loading.value = false;
    }
  };

  const handleGetValue = () => {
    unref(isEdit) ? handleEditPanel() : handleCreatePanel();
    isEdit.value = false;
  };
</script>

<template>
  <BasicModal
    v-bind="$attrs"
    :destroyOnClose="true"
    :title="isEdit ? '编辑看板' : '创建看板'"
    @register="registerModal"
    @ok="handleGetValue"
    :okButtonProps="{ loading }"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<style scoped></style>