<template>
  <div :key="'addForm_' + $route.name">
    <a-spin :spinning="isLoading">
      <page-title :title="title" />
      <a-page-header>
        <template #extra>
          <!--      todo 隐藏取消-->
          <a-button @click="navigateBack">返回</a-button>
          <a-button type="primary" @click="submit" :disabled="!nsFormElRef?.validateResult">
            保存</a-button
          >
        </template>
      </a-page-header>
      <div class="add-form">
        <ns-form ref="nsFormElRef" v-bind="getBindValue">
          <template #[item]="data" v-for="item in Object.keys($slots)">
            <slot :name="item" v-bind="data || {}"></slot>
          </template>
        </ns-form>
      </div>
    </a-spin>
  </div>
</template>

<script lang="ts">
  import { computed, defineComponent, ref } from 'vue';
  import { http } from '/nerv-lib/util/http';
  import { NsMessage } from '/nerv-lib/component/message';
  import { formProps } from '/nerv-lib/component/form/form/props';
  import { PropTypes } from '/nerv-lib/util/type';
  import { useNavigate } from '/nerv-lib/use/use-navigate';
  import { useApi, HttpRequestConfig } from '/nerv-lib/use/use-api';
  import { useRoute } from 'vue-router';

  export default defineComponent({
    name: 'NsViewAddForm',
    props: {
      ...formProps,
      api: PropTypes.string | PropTypes.object,
      title: PropTypes.string,
    },
    setup(props, { attrs }) {
      const nsFormElRef = ref();
      const isLoading = ref(false);
      const { navigateBack } = useNavigate();
      const { httpRequest } = useApi();
      const route = useRoute();

      function submit() {
        nsFormElRef.value
          .triggerSubmit()
          .then((data: Recordable) => {
            isLoading.value = true;
            const { api } = props;
            const { params } = route;
            const requestConfig: HttpRequestConfig = { method: 'POST' };
            httpRequest({ api, params: data, pathParams: params, requestConfig })
              .then(() => {
                isLoading.value = false;
                NsMessage.success('操作成功', 1, () => {
                  navigateBack();
                });
              })
              .catch(() => {
                isLoading.value = false;
              });
          })
          .catch(() => ({}));
      }
      const getBindValue = computed(() => ({
        ...attrs,
        ...props,
      }));
      return { nsFormElRef, submit, getBindValue, isLoading, navigateBack };
    },
  });
</script>
<style lang="less" scoped>
  .ant-page-header {
    padding: 0 24px;
    margin-bottom: 15px;
  }

  :deep(.ant-page-header-heading-extra) {
    margin-right: auto !important;
    margin-left: 0;
  }

  .add-form {
    padding: 0 24px;
  }
  :deep(
      .ant-table-thead
        > tr
        > th:not(:last-child):not(.ant-table-selection-column):not(
          .ant-table-row-expand-icon-cell
        ):not([colspan])::before
    ) {
    display: none;
  }
</style>
