<script setup lang="ts">
import studentManageApi from '@/api/studentManage'
import type { Student, Class, ClassStudent, Group } from '@/api/studentManage'
import type { SetTargetData } from '../..'
import hud from '@/utils/hud'
import obj from '@/utils/obj'
import { storeToRefs } from 'pinia'
import { userStore } from '@/stores'

const props = defineProps<{
  modelValue: boolean
  schoolId: any
}>()

const emit = defineEmits(['update:modelValue', 'ok'])

defineOptions({ name: 'SetTarget' })
const { schoolMap } = storeToRefs(userStore())

const value = computed({
  get: () => props.modelValue,
  set: val => emit('update:modelValue', val),
})

// 个人的下拉框筛选
const personalFilterClass = ref('')
const personalFilterGroup = ref('')
// 组列表
const groupList = ref([] as Group[])
const groupMap = {} as Record<string, Group>

// 学员列表
const studentList = ref([] as Student[])
const checkedStudentIds = ref([] as any[])
const studentMap = {} as Record<string, Student>

// 所有的学员数据汇总(key是班级id)
const classStudentMap = {} as Record<string, ClassStudent>

// 班级列表
const classList = ref([] as Class[])
let classMap = {} as Record<string, Class>
const checkedClassIds = ref([] as any[])
// 做出选择后的数据
const data = {} as SetTargetData

// 类型
const target_type_class = 1
const target_type_personal = 2
const target_types = [
  {
    label: '班级',
    value: target_type_class,
  },
  {
    label: '个人',
    value: target_type_personal,
  },
]
const targetType = ref(target_types[0].value)
const targetText = ref('')

// 监听班级变化
watch(
  () => personalFilterClass.value,
  async classId => {
    // 加载学员数据
    let classStudent = classStudentMap[classId]
    if (!classStudent) {
      classStudent = await studentManageApi.getClassStudent(classId)
      classStudentMap[classId] = classStudent
    }
    // 设置组的数据
    const newGroupList = [
      {
        id: 'all_' + classId,
        name: '全部',
        label: '',
        students: classStudent.students.list,
      },
      ...classStudent.groups.list,
    ]
    for (const group of newGroupList) {
      groupMap[group.id] = group
      group.label = `${group.name}(${group.students.length})`
    }
    groupList.value = newGroupList
    if (newGroupList?.length) {
      personalFilterGroup.value = newGroupList[0].id
    } else {
      personalFilterGroup.value = undefined as any
    }
  },
)

// 监听组的变化
watch(
  () => personalFilterGroup.value,
  groupId => {
    // 切换学员列表
    const students = groupMap[groupId].students
    studentList.value = students
    for (const stu of students) {
      studentMap[stu.id] = stu
    }
  },
)

// 监听任务目标选择的变化
watch([() => checkedClassIds.value, () => checkedStudentIds.value, () => targetType.value], () => {
  if (targetType.value === target_type_class) {
    data.classes = checkedClassIds.value.map((id: any) => ({
      id,
      name: classMap[id].className,
    }))
    data.students = []
  } else {
    data.students = checkedStudentIds.value.map((id: any) => ({
      id,
      name: studentMap[id].name,
    }))
    data.classes = []
  }

  const selectedData = data.classes.length ? data.classes : data.students
  if (!selectedData.length) {
    targetText.value = ''
  } else {
    const threshold = 3
    const numColor = '#3894ff'
    const nameColor = '#45a464'
    const sep = hud.highlight(' / ', numColor)
    const objName = data.classes.length ? '个班级' : '名学员'
    if (selectedData.length <= threshold) {
      targetText.value = selectedData.map(cls => hud.highlight(cls.name, nameColor)).join(sep)
    } else {
      const names = []
      for (let i = 0; i < threshold; i++) {
        names.push(hud.highlight(selectedData[i].name, nameColor))
      }
      targetText.value =
        names.join(sep) + `...等共${hud.highlight(selectedData.length, numColor)}${objName}`
    }
  }
  emit('ok', data, targetText.value)
})

watch(
  () => schoolMap.value,
  () => {
    classList.value = [...schoolMap.value[props.schoolId].classList]
    classMap = obj.list2map(classList.value, 'classId')
  },
  {
    immediate: true,
  },
)
</script>

<template>
  <mj-dialog v-model="value" title="设置任务对象" :width="1280" hide-footer>
    <div class="set-target">
      <div class="mj-data-row">
        <div class="mj-data-item">
          <SelectTab v-model="targetType" :dataList="target_types" type="small" />
          <span class="target-text" v-html="targetText"></span>
        </div>
      </div>
      <div class="target-content">
        <div v-if="targetType === target_type_class" class="target-class">
          <mj-check-group
            v-model="checkedClassIds"
            :options="classList"
            value-key="classId"
            label-key="className"
          />
        </div>
        <div v-else class="target-personal">
          <div class="filter">
            <Select
              v-if="classList.length"
              v-model="personalFilterClass"
              :select-list="classList"
              value-key="classId"
              label-key="className"
            />
            <Select
              v-if="groupList.length"
              v-model="personalFilterGroup"
              width="350"
              :select-list="groupList"
              value-key="id"
            />
          </div>
          <mj-check-group
            v-model="checkedStudentIds"
            class="check-group"
            :options="studentList"
            value-key="id"
            label-key="name"
          />
        </div>
      </div>
    </div>
  </mj-dialog>
</template>

<style lang="scss" scoped>
.set-target {
  .target-text {
    margin-left: 32px;
  }

  .target-content {
    height: 45.83vh;
    margin-top: 2.67vh;

    :deep(.mj-check-group) {
      max-height: 41.67vh !important;
      overflow: scroll;
      @include hidden_scroll;
    }

    .target-personal {
      .filter {
        display: flex;
        align-items: center;
        gap: 32px;
      }

      .check-group {
        margin-top: 1.33vh;
      }
    }
  }
}
</style>
