<script lang="ts" setup>
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { formSchema } 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 handleCreatePanel = async () => {
    await method.validate();
    try {
      const value = method.getFieldsValue() as AddDataBoardParams;
      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;
      const value = method.getFieldsValue() as UpdateDataBoardParams;
      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
  :maskClosable="false"
    v-bind="$attrs"
    :destroyOnClose="true"
    :title="isEdit ? '编辑看板' : '创建看板'"
    @register="registerModal"
    @ok="handleGetValue"
    :okButtonProps="{ loading }"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<style scoped></style>
