<script setup lang="ts">
import studentManageApi from '@/api/studentManage'
import { status_disabled, status_enabled } from '@/api/studentManage'
import type { UserInfo } from '.'
import hud from '@/utils/hud'

const props = defineProps<{
  modelValue: boolean
  users: UserInfo[]
}>()
const emit = defineEmits(['update:modelValue', 'operation-success'])
defineOptions({ name: 'BatchOperation' })
const value = computed({
  get: () => props.modelValue,
  set: val => emit('update:modelValue', val),
})

// 重置密码
function resetPassword() {
  hud.confirmLoad({
    task: async () => {
      await studentManageApi.resetPassword(props.users.map(item => item.id))
    },
    option: '重置密码',
    dialog: `确定要重置${hud.highlight(props.users.length)}个同学的密码吗？`,
  })
  // 关闭弹窗
  emit('update:modelValue', false)
  emit('operation-success')
}

// 统一处理启用禁用
async function enableDisableAccount(status: number) {
  let color: any = 'green'
  let type = '启用'
  if (status === status_disabled) {
    color = undefined
    type = '禁用'
  }
  await hud.confirmLoad({
    task: async () => {
      await studentManageApi.changeStatusBatch(
        props.users.map(item => ({
          id: item.id,
          status,
        })),
      )
    },
    option: type + '账号',
    dialog: `确定要${hud.highlight(type, color)}【${hud.highlight(props.users.length)}】个同学的账号吗？`,
  })
  for (const user of props.users) {
    user.status = status
  }
  // 关闭弹窗
  emit('update:modelValue', false)
  emit('operation-success')
}

// 启用账号
function enableAccount() {
  enableDisableAccount(status_enabled)
}

// 禁用账号
function disableAccount() {
  enableDisableAccount(status_disabled)
}
</script>

<template>
  <mj-dialog v-model="value" :title="`批量操作(共${users?.length}人)`" hide-footer :width="800">
    <div class="basic-info-dialog">
      <div class="buttons">
        <mj-button type="danger" @click="resetPassword">重置密码</mj-button>
        <mj-button class="option" type="success" @click="enableAccount">启用</mj-button>
        <mj-button class="option" type="danger" @click="disableAccount">禁用</mj-button>
      </div>
    </div>
  </mj-dialog>
</template>

<style lang="scss" scoped>
@use './dialog.scss' as *;

.buttons {
  margin-top: 1.67vh;
}
</style>
