<script lang="ts" setup>
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicForm, useForm } from '/@/components/Form';
  import { formDetailSchema } from './config.data';
  import type { DrawerParams } from './config.data';
  import { ref, computed, unref } from 'vue';
  import { createOrUpdateStreamingMediaRecord } from '/@/api/camera/cameraManager';
  import { StreamingMediaModel } from '/@/api/camera/model/cameraModel';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { PlayProtocol } from '../manage/config.data';

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

  const createFlag = ref(false);

  const getDrawerTitle = computed(() => `${unref(createFlag) ? '新增' : '编辑'}流媒体配置`);

  let id: Nullable<string> = null;

  const [register, { getFieldsValue, setFieldsValue, resetFields, validate }] = useForm({
    schemas: formDetailSchema,
    labelWidth: 90,
    showActionButtonGroup: false,
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner((data: DrawerParams) => {
    createFlag.value = data.createFlag;
    if (!unref(createFlag)) {
      id = data.record!.id;
      setFieldsValue(data.record);
    } else {
      setFieldsValue({ ssl: PlayProtocol.HTTP });
      resetFields();
    }
  });

  const handleSubmit = async () => {
    await validate();
    let value = getFieldsValue() as StreamingMediaModel;
    let message = '修改成功';
    if (unref(createFlag)) message = '添加成功';
    else value = { ...value, id: id! };
    try {
      setDrawerProps({
        confirmLoading: true,
      });
      await createOrUpdateStreamingMediaRecord(value);
      const { createMessage } = useMessage();
      createMessage.success(message);
      emit('success');
      closeDrawer();
    } catch (e) {
    } finally {
      setDrawerProps({
        confirmLoading: false,
      });
    }
  };
</script>

<template>
  <BasicDrawer
    @register="registerDrawer"
    v-bind="$attrs"
    showFooter
    :title="getDrawerTitle"
    width="30%"
    @ok="handleSubmit"
  >
    <BasicForm @register="register" />
  </BasicDrawer>
</template>
