<script setup lang="ts">
import { type InstitutionModel } from '@/model/system.model';
import { branchMethod, editInstitutionMethod } 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<InstitutionModel>;

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

const model = ref<FormModel>({ ...props.data });

watchEffect(() => {
  if (props.data) {
    model.value = { ...props.data };
  }
});

const branch = ref<any[]>([]);
const { loading: branchLoading } = useRequest(branchMethod(0, 1, 1)).onSuccess(({ data }) => {
  const to = (data?: any[]): any[] => {
    return Array.isArray(data)
      ? data.map((item) => {
          return {
            ...item,
            value: item.id,
            key: item.id.toString(),
            children: to(item.children),
          };
        })
      : [];
  };
  branch.value = to(data);
});
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;
}
watch(
  () => model.value?.orgId,
  async (newVal, oldVal) => {
    // 只有当值真正改变时才执行（避免初始化时重复调用）
    if (newVal !== oldVal) {
      if (newVal) {
        await getInstitution(newVal);
      } else {
        // 清空组织时，清空上级机构列表和已选择的上级机构
        insArr.value = [];
        if (model.value) {
          model.value.parentId = undefined;
        }
      }
    }
  },
  { immediate: true, deep: true }
);
const { loading: submitting, send: submit } = useRequest(editInstitutionMethod, { immediate: false }).onSuccess(() => {
  emits('submit');
});

const formProps = reactive<VxeFormProps<FormModel>>({
  titleWidth: 120,
  titleAlign: 'right',
  titleColon: true,
  titleAsterisk: true,
  data: computed(() => model.value) as any,
  items: [
    {
      field: 'orgId',
      title: '组织名称',
      span: 24,
      itemRender: {
        name: 'VxeSelect',
        props: {
          // multiple: true,
          clearable: true,
          loading: computed(() => branchLoading.value),
          options: computed(() => branch.value),
          optionProps: {
            value: 'value',
            label: 'label',
          },
        },
        events: {
          change({ value }: any) {
            // 当组织选择改变时，直接调用接口获取上级机构
            if (value) {
              getInstitution(value);
            } else {
              // 清空组织时，清空上级机构列表和已选择的上级机构
              insArr.value = [];
              if (model.value) {
                model.value.parentId = undefined;
              }
            }
          },
        },
      },
    },
    { field: 'name', title: '机构名称', span: 24, itemRender: { name: 'VxeInput' } },
    {
      field: 'parentId',
      title: '上级机构',
      span: 24,
      itemRender: {
        name: 'VxeTreeSelect',
        props: {
          loading: computed(() => insLoading.value),
          options: computed(() => insArr.value),
          optionProps: { value: 'id', label: 'label' },
          clearable: true,
        },
      },
    },
    { field: 'action', align: 'center', span: 24, slots: { default: 'active' } },
  ],
  rules: {
    roleIds: [{ required: true, message: '请选择组织' }],
    nickName: [{ required: true, message: '请输入机构名称' }],
  },
});
const formEmits: VxeFormListeners<FormModel> = {
  submit({ data }) {
    submit(data);
  },
};
function cancel() {
  VxeUI.modal.close('institution-edit-modal');
}
</script>
<template>
  <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>
</template>
<style scoped lang="scss"></style>
