<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" destroyOnClose :title="title" :width="800" @ok="handleSubmit" :showFooter="showFooter">
    <BasicForm @register="registerForm" />
    <!-- 消息接受人信息  -->
    <BasicTable class="table" @register="messageObjTable" style="display: block" />
  </BasicDrawer>
</template>

<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicDrawer, useDrawerInner, BasicForm, useForm, BasicTable, useTable } from '@jdlinker/ui';
  import { formSchema, messageObjColumns } from '../data';
  import { messageObjList, saveOrUpdate } from '../service';
  // Emits声明
  const emit = defineEmits(['register', 'success']);
  const isUpdate = ref(true);
  const showFooter = ref(true);
  const msgsettingId = ref('');

  //注册联系人table数据
  const [messageObjTable] = useTable({
    title: '联系人信息',
    api: messageObjList,
    columns: messageObjColumns,
    showIndexColumn: false,
    showTableSetting: false,
    useSearchForm: false,
    showActionColumn: false,
    pagination: false,
    canResize: false,
    bordered: true,
    locale: { emptyText: '暂无数据' },
    beforeFetch(params) {
      params.msgsettingId = msgsettingId.value;
    }
  });

  //表单配置
  const [registerForm, { setProps, resetFields, setFieldsValue, validate }] = useForm({
    //labelWidth: 150,
    schemas: formSchema,
    showActionButtonGroup: false,
    baseColProps: { span: 24 }
  });
  //表单赋值
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    //重置表单
    await resetFields();
    msgsettingId.value = data.record.id;
    showFooter.value = data.showFooter;
    setDrawerProps({ confirmLoading: false, showFooter: showFooter.value });
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      //表单赋值
      await setFieldsValue({
        ...data.record
      });
    }
    // 隐藏底部时禁用整个表单
    setProps({ disabled: !data?.showFooter });
  });
  //设置标题
  const title = computed(() => (!unref(isUpdate) ? '新增' : !unref(showFooter) ? '详情' : '编辑'));
  //表单提交事件
  async function handleSubmit() {
    try {
      let values = await validate();
      setDrawerProps({ confirmLoading: true });
      //提交表单
      await saveOrUpdate(values, isUpdate.value);
      //关闭弹窗
      closeDrawer();
      //刷新列表
      emit('success');
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>

<style lang="less" scoped>
  /** 时间和数字输入框样式 */
  :deep(.ant-input-number) {
    width: 100%;
  }

  :deep(.ant-calendar-picker) {
    width: 100%;
  }
</style>
