<script setup lang="ts">
import { type OrganizationModel } from '@/model/system.model';
import { branchMethod } from '@/request/api/system.api';
import { setPatientBelongMethod } from '@/request/api/system.api';
import { useRequest } from 'alova/client';
import { type VxeFormListeners, type VxeFormProps } from 'vxe-pc-ui';
import { VxeUI } from 'vxe-pc-ui';
type FormModel = Partial<OrganizationModel>;

const props = defineProps<{ data: OrganizationModel }>();
const emits = defineEmits<{
  submit: [data?: OrganizationModel];
}>();

const { loading: submitting, send: submit } = useRequest(setPatientBelongMethod, { immediate: false }).onSuccess(({ data }) => {
  emits('submit');
});
const insArr = ref<any[]>([]);
const insLoading = ref(false);
async function getInstitution(orgId: string | number) {
  insLoading.value = true;
  const res = await branchMethod(1, 0, Number(orgId));
  if (res && res.length > 0) {
    insArr.value = res;
  }
  insLoading.value = false;
}
const formProps = reactive<VxeFormProps<FormModel>>({
  titleWidth: 120,
  titleAlign: 'right',
  titleColon: true,
  titleAsterisk: true,
  data: { ...props.data },
  items: [
    {
      field: 'insId',
      title: '机构',
      span: 24,
      itemRender: {
        name: 'VxeTreeSelect',
        props: {
          loading: computed(() => insLoading.value),
          options: computed(() => insArr.value),
          optionProps: { value: 'id' },
          align: 'right',
        },
      },
      className: 'form-item-center',
    },
    { align: 'center', span: 24, slots: { default: 'active' }, className: 'form-buttons-bottom' },
  ],
  rules: {
    // deptId: [{ required: true, message: '请选择机构' }],
  },
});
const formEmits: VxeFormListeners<FormModel> = {
  submit({ data }) {
    submit(data);
  },
};
function cancel() {
  VxeUI.modal.close('patient-belong-modal');
}

onBeforeMount(() => {
  if (props.data?.id) {
    formProps.data = { ...props.data };
    getInstitution(props.data?.id);
  }
});
</script>
<template>
  <div class="form-container">
    <div class="flex flex-col items-center justify-center">
      <div class="text-center mb-8 mt-6 title">当患者没有绑定机构时，默认归属于哪一个机构？</div>
      <div class="text-center mb-12 color-black">请选择</div>
    </div>
    <vxe-form v-bind="formProps" v-on="formEmits" :loading="submitting">
      <template #active>
        <vxe-button type="submit" status="primary" content="提交" :loading="submitting"></vxe-button>
        <vxe-button content="取消" :disabled="submitting" @click="cancel()"></vxe-button>
      </template>
    </vxe-form>
  </div>
</template>
<style scoped lang="scss">
.form-container {
  display: flex;
  flex-direction: column;
  min-height: 100%;
}

.title {
  color: #ab4343;
  font-size: 16px;
}

:deep(.form-item-center) {
  display: flex;
  justify-content: center;

  .vxe-form--item-content {
    width: 300px;
  }
}

:deep(.form-buttons-bottom) {
  margin-top: auto;
  padding-top: 150px;
}
</style>
