<template>
  <BasicDrawer
    v-bind="$attrs"
    destroyOnClose
    @register="registerDrawer"
    :title="getTitle"
    :width="width"
    @ok="handleSubmit"
    :showFooter="true"
  >
    <BasicForm @register="registerForm" layout="vertical" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicForm, useForm } from '/@/components/Form';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { dataFormSchema } from './data';

  import {
    infraStorageconfigAdd,
    infraStorageconfigEdit,
    infraStorageconfigDetail,
  } from '/@/api/infra/infraStorageConfigApi';

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

  const getTitle = computed(() => (!unref(isUpdate) ? '新增存储配置' : '编辑存储配置'));
  const width = '45%';
  const isUpdate = ref(false);
  const rowId = ref();

  const { createMessage } = useMessage();
  const [registerForm, { setFieldsValue, resetFields, validate, updateSchema }] = useForm({
    labelWidth: 100,
    schemas: dataFormSchema,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
  });
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async data => {
    await resetFields();
    setDrawerProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      updateSchema([
        {
          field: 'master',
          componentProps: {
            disabled: true,
          },
        },
      ]);
      const resData = await infraStorageconfigDetail(data.record.id);
      rowId.value = resData.id;
      resData.type = String(resData.type);
      await setFieldsValue({
        ...resData,
      });
    }
  });

  // 提交按钮事件
  async function handleSubmit() {
    try {
      const values = await validate();
      const keys = Object.keys(values);
      const configs = {};
      keys.forEach(item => {
        if (item.indexOf('config.') != -1) {
          const realKey = item.substring(item.indexOf('.') + 1, item.length);
          configs[realKey] = values[String(item)];
        }
      });
      values.config = configs;
      setDrawerProps({ confirmLoading: true });
      !unref(isUpdate)
        ? await infraStorageconfigAdd({ ...values })
        : await infraStorageconfigEdit({ ...values, id: rowId.value });
      !unref(isUpdate) ? createMessage.success('新增成功！') : createMessage.success('编辑成功！');
      closeDrawer();
      emit('success', {
        isUpdate: unref(isUpdate),
        values: { ...values, id: rowId.value },
      });
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
<style lang="less" scoped>
  ::v-deep(.ant-divider-plain.ant-divider-with-text) {
    font-size: 17px !important;
  }
</style>
