<script setup lang="ts">
import type {
  MjEditFormProps,
  MjFormEventProps,
  MjFormProps,
  MjGridProps,
} from '#/components/mj/mj-table'
import type { MapAndOptions } from '#/store/sys-dict'

import { useUserStore } from '@vben/stores'

import { groupService } from '#/api/service/org/group'
import {
  mj_form_button_group,
  mj_form_input,
  mj_form_select,
  mj_form_text,
} from '#/components/mj/mj-table'
import { useSysDictStore } from '#/store/sys-dict'
import hud from '#/utils/hud'
import obj from '#/utils/obj'

import {
  useSearchClass,
  useSearchSchoolClass,
  useSearchUser,
} from '../hooks/search'
import StudentList from './student-list.vue'

const gridRef = ref()
const { userInfo } = storeToRefs(useUserStore())

// 组员身份
const membersData = ref({} as MapAndOptions)

const sysDictStore = useSysDictStore()
const { getSysDict } = sysDictStore

// 添加组员的表单
const userRender = useSearchUser({
  getData: () => gridRef.value.getEditFormData(),
  props: {
    cmpProps: { schoolPersonType: 0, fixedSchoolPersonType: true },
  },
})

const schoolClassRender = useSearchSchoolClass({
  prepare: { gridRef },
})
const schoolRender = schoolClassRender.schoolRender
let classRender = schoolClassRender.classRender
if (userInfo.value.isOnlyStaff) {
  classRender = useSearchClass({
    prepare: { gridRef },
  })
}

const addMemberForm = reactive({
  titleWidth: 90,
  rules: {
    groupName: [
      {
        required: true,
        message: '请选择小组',
      },
    ],
    userId: [
      {
        message: '请选择学员',
        required: true,
      },
    ],
    userTypeCode: [
      {
        message: '请选择身份',
        required: true,
      },
    ],
  },
  items: [
    {
      field: 'groupName',
      title: '小组',
      span: 24,
      itemRender: {
        name: mj_form_input,
        props: { disabled: true },
      },
    },
    {
      field: 'userId',
      title: '学员',
      span: 24,
      itemRender: userRender,
    },
    {
      field: 'userTypeCode',
      title: '身份',
      span: 24,
      itemRender: {
        name: mj_form_select,
        options: computed(() => membersData.value.options),
      },
    },
    {
      align: 'center',
      span: 24,
      itemRender: {
        name: mj_form_button_group,
        options: [{ type: 'submit', content: '提交', status: 'primary' }],
      },
    },
  ],
  data: {},
} as MjFormProps)

const addMemberEvents = {
  submit({ data }: { data: any }) {
    hud.load({
      task: async () => {
        await groupService.addUsers({
          groupId: data.groupId,
          userIds: [
            {
              userId: data.userId,
              userTypeCode: data.userTypeCode,
            },
          ],
        })
        showAddMember.value = false
        refresh()
      },
      option: '添加',
      hideSuccess: false,
    })
  },
} as MjFormEventProps

// 表单
const editForm = {
  form: {
    items: obj.joinObjs<any>(
      {
        required: true,
        field: 'name',
        title: '名称',
        span: 24,
        itemRender: {
          name: mj_form_input,
        },
      },
      userInfo.value.isOnlyStaff || {
        required: true,
        field: 'schoolName',
        title: '学校',
        span: 24,
        itemRender: {
          name: mj_form_text,
          props: {
            linkedRender: schoolRender,
          },
        },
      },
      {
        required: true,
        field: 'className',
        title: '班级',
        span: 24,
        itemRender: {
          name: mj_form_text,
          props: {
            linkedRender: classRender,
          },
        },
      },
    ),
    data: {},
  },
  addFields: ['classId', 'name'],
  updateFields: ['id', 'name'],
} as MjEditFormProps

// 搜索表单
const searchForm = {
  items: obj.joinObjs(
    userInfo.value.isOnlyStaff || {
      title: '学校',
      field: 'schoolId',
      span: 6,
      itemRender: schoolRender,
    },
    {
      title: '班级',
      field: 'classId',
      span: 6,
      itemRender: classRender,
    },
  ),
} as MjFormProps

// 表格
const grid = {
  columns: obj.joinObjs<any>(
    { type: 'seq' },
    { type: 'expand', width: 80, slots: { content: 'studentList' } },
    {
      field: 'name',
      title: '名称',
    },
    userInfo.value.isOnlyStaff || { field: 'schoolName', title: '学校' },
    { field: 'className', title: '班级' },
    {
      title: '操作',
      slots: {
        default: 'operation',
      },
    },
  ),
  beforeLoadData(params) {
    if (userInfo.value.isSpStaff) {
      // 如果是服务商人员
      params.providerId = userInfo.value.providerId
    } else if (userInfo.value.isStaff) {
      // 如果是学校人员
      params.schoolId = userInfo.value.schoolId
    }
    return params
  },
} as MjGridProps

// 添加组员
const currentGroup = ref({} as any)
const showAddMember = ref(false)
function addMember(group: any) {
  currentGroup.value = group
  showAddMember.value = true
}
watch(
  () => showAddMember.value,
  (val) => {
    if (!val) return
    addMemberForm.data.groupName = currentGroup.value.name
    addMemberForm.data.groupId = currentGroup.value.id
  },
)

function refresh() {
  gridRef.value.reload()
}

onMounted(async () => {
  membersData.value = await getSysDict('group_user_type')
})
</script>

<template>
  <div class="group-mgr g-container">
    <mj-table
      ref="gridRef"
      :search-form="searchForm"
      :edit-form="editForm"
      :grid="grid"
      :service="groupService"
    >
      <template #studentList="{ row }">
        <StudentList
          :members="membersData.options"
          :list="row.groupUserList"
          @refresh="refresh"
        />
      </template>
      <template #operation="{ row }">
        <el-button @click.stop="addMember(row)">添加组员</el-button>
      </template>
    </mj-table>
    <mj-modal
      v-model="showAddMember"
      :options="{
        title: '添加组员',
      }"
    >
      <VxeForm v-bind="addMemberForm" v-on="addMemberEvents" />
    </mj-modal>
  </div>
</template>

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