<template>
  <ns-modal
    ref="modalRef"
    centered
    v-bind="extraModalConfig"
    destroyOnClose
    v-model:visible="visible"
    :title="title"
    :okButtonProps="buttonProps"
    @ok="handleOk">
    <ns-form ref="formRef" :schemas="schemas" :model="formData" formLayout="vertical" />
  </ns-modal>
</template>

<script lang="ts" setup>
  import { computed, ref, toRefs, watch } from 'vue';
  import { HttpRequestConfig, NsMessage, useApi } from '/nerv-lib/saas';
  import { useRoute } from 'vue-router';
  type Props = {
    title?: string;
    schemas: Array<any>;
    api: string | object | Function;
    data?: object;
    extraModalConfig?: object;
    success?: Function;
  };
  const route = useRoute();
  const { httpRequest } = useApi();

  const props = withDefaults(defineProps<Props>(), {
    title: '新增',
  });
  const { schemas } = toRefs(props);
  const formData = ref();
  watch(
    () => props?.data,
    (val) => {
      formData.value = val;
    },
    {
      immediate: true,
      deep: true,
    },
  );
  const modalRef = ref();
  const formRef = ref();
  const visible = ref(false);
  const validateResult = computed(() => {
    return !formRef.value?.validateResult;
  });
  const toggle = () => {
    visible.value = !visible.value;
  };

  const setLoading = (loading = true) => {
    buttonProps.value.loading = loading;
  };

  const handleOk = () => {
    setLoading(true);
    formRef.value
      .triggerSubmit()
      .then((data: any) => {
        const { api, success } = props;
        const requestConfig: HttpRequestConfig = { method: 'POST' };
        const { params } = route;

        httpRequest({ api, params: data, pathParams: params, requestConfig })
          .then((res) => {
            NsMessage.success('操作成功', 1, () => {
              toggle();
              success && success(res);
            });
          })
          .finally(() => {
            setLoading(false);
          });
      })
      .catch(() => {});
  };

  const buttonProps = ref({
    disabled: validateResult,
    loading: false,
  });

  defineExpose({
    toggle,
  });
</script>
<style lang="less"></style>
