<script setup lang="ts">
import { studentShareService } from '#/api/service/org/student-share'
import hud from '#/utils/hud'

import { useSearchSchool } from '../hooks/search'

defineOptions({ name: 'ShareStudent' })
const props = withDefaults(
  defineProps<{
    modelValue?: boolean
    students: any
  }>(),
  {
    modelValue: false,
  },
)
const emits = defineEmits(['update:modelValue', 'success'])
const show = computed({
  get() {
    return props.modelValue
  },
  async set(newVal) {
    emits('update:modelValue', newVal)

    if (newVal) {
      formRef.value?.setData({})
    }
  },
})

// 共享学员用的学校
const shareSchoolRender = useSearchSchool({
  // 显示所有的学校
  props: {
    cmpProps: { showAll: true },
  },
})

const title = computed(() => {
  if (props.students?.length === 1) {
    return `共享学员【${props.students[0].name}】`
  }
  return `共享${props.students?.length}位学员`
})

const formRef = ref()
const form = {
  titleWidth: 120,
  items: [
    {
      required: true,
      span: 24,
      field: 'schoolId',
      title: '目标学校',
      itemRender: shareSchoolRender,
    },
  ],
} as any

// 编辑表单事件
const submit = () => {
  hud.load({
    task: async () => {
      const data = formRef.value?.getData()
      await studentShareService.share({
        dstSchoolId: data.schoolId,
        items: props.students.map((item: any) => ({
          studentId: item.id,
          srcSchoolId: item.schoolId,
        })),
      })
      emits('update:modelValue', false)
      emits('success')
    },
    option: '共享',
    hideSuccess: false,
  })
}
</script>

<template>
  <mj-modal
    v-model="show"
    :options="{
      title,
    }"
  >
    <mj-form ref="formRef" :options="form" @submit="submit" />
  </mj-modal>
</template>

<style lang="scss" scoped></style>
