<script setup lang="ts">
import studentManageApi from '@/api/studentManage'
import type { Class } from '@/api/studentManage'
import { status_disabled } from '@/api/studentManage'
import dayjs from 'dayjs'
import type { UserInfo } from '.'
import UserDetail from './user-detail.vue'
import BatchOperation from './batch-operation.vue'
import BatchSend from './batch-send.vue'
import router from '@/router'
import { only_last_id_value } from '..'
import hud from '@/utils/hud'
import MjTable from '@/components/mj/mj-table'
import type { MjGridEventProps, MjGridProps } from '@/components/mj/mj-table'
import { only_last_id } from '@/api/only-last'
import { getGradeByClassName } from '@/api/subject/config'

const props = defineProps<{
  cls: Class
  schoolId: any
}>()

defineOptions({ name: 'BasicInfo' })

const table = ref()

// 对话框
const userDetailVisible = ref(false)
// 批量操作
const batchOperationVisible = ref(false)
const batchOperationBtnText = computed(() => {
  const len = selectedUsers.value.length
  const text = '批量操作'
  return len ? `${text}(${len})` : text
})
const batchSendVisible = ref(false)
const batchSendBtnText = computed(() => {
  const len = selectedUsers.value.length
  const text = '批量奖惩'
  return len ? `${text}(${len})` : text
})
const batchBtnDisabled = computed(() => {
  return selectedUsers.value.length < 1
})
// 选中的用户
const selectedUsers = ref([] as UserInfo[])
const user = ref({} as UserInfo)

// 行的样式
const tableRowClassName = ({ row }: { row: UserInfo; rowIndex: number }) => {
  return Number(row.status) === status_disabled ? 'row-disabled' : ''
}

function onMore(item: UserInfo) {
  user.value = item
  userDetailVisible.value = true
}

const gridRef = ref()

watch(
  () => props.cls,
  () => gridRef.value?.reload(),
)

// 设置教材
function setBook() {
  const className = props.cls.className
  const gradeId = getGradeByClassName(className)
  if (!gradeId) {
    hud.error('无法获取年级信息')
    return
  }
  router.push({
    path: '/student-mgr/set-book',
    query: {
      classId: props.cls.classId,
      className,
      gradeId,
    },
  })
}

// 设置任务
function setTask() {
  router.push({
    path: '/student-mgr/set-task',
    query: {
      schoolId: props.schoolId,
    },
  })
}

// 显示批量操作
function showBatchOperation() {
  batchOperationVisible.value = true
}
// 显示批量奖惩
function showBatchSend() {
  batchSendVisible.value = true
}
// 取消选中
function uncheckAll() {
  table.value.clearSelection()
}

function selectChange(items: any[], item: any) {
  selectedUsers.value = items
}

const grid = {
  pagerConfig: {
    pageSize: 1000,
    autoHidden: true,
  },
  rowClassName: tableRowClassName,
  columns: [
    {
      title: '形象',
      slots: {
        default: 'look',
      },
      // width: percentWidth(0.25),
    },
    {
      field: 'name',
      title: '姓名',
    },
    {
      field: 'account',
      title: '账号',
      formatter({ cellValue }) {
        return cellValue ? cellValue.substring(0, 4) + '**' : ''
      },
      sortable: true,
    },
    {
      field: 'currency',
      title: '乐贝',
      sortable: true,
      // 如果格式化成字符串了，就无法正确排序
      // formatter: 'money',
    },
    {
      field: 'diamond',
      title: '钻石',
      sortable: true,
      // formatter: 'money',
    },
    {
      field: 'aggregateLoginNum',
      title: '累计签到(天)',
      sortable: true,
    },
  ],
  async loadData() {
    if (!props.cls.classId) return
    const data = (
      await studentManageApi.getClassStudent(props.cls.classId, {
        [only_last_id]: only_last_id_value,
      })
    ).students.list
    data.forEach((i: anyObj) => {
      // 调整为数字（为了排序）
      i.currency = Number(i.currency) || 0
      i.diamond = Number(i.diamond) || 0
      i.aggregateLoginNum = Number(i.aggregateLoginNum) || 0
      // 调整时间
      i.lastLoginTimeStr = i.lastLoginTime
        ? dayjs(i.lastLoginTime).format('YYYY-MM-DD')
        : '从未登录过'
      i.cumulativeTimeDurationStr = `${i.cumulativeTimeDuration}天`
    })
    return {
      rows: data,
      totalRows: data.length,
    }
  },
} as MjGridProps

const gridEvents = {
  cellClick: ({ row }: any) => {
    onMore(row)
  },
} as MjGridEventProps

// 显示乐贝明细
function showCoinDetail() {
  router.push('/student-mgr/coin-detail')
}
</script>

<template>
  <div class="stu-mgr-content basic-info">
    <div class="student-toolbar">
      <div class="left-items">
        <mj-button
          class="status-button"
          type="primary"
          thin-font
          :disabled="batchBtnDisabled"
          @click="showBatchOperation"
          >{{ batchOperationBtnText }}</mj-button
        >
        <mj-button
          class="status-button"
          type="primary"
          thin-font
          :disabled="batchBtnDisabled"
          @click="showBatchSend"
          >{{ batchSendBtnText }}</mj-button
        >
        <mj-button class="status-button" thin-font type="primary" @click="setBook"
          >教材设置</mj-button
        >
        <mj-button class="status-button" thin-font type="primary" @click="setTask"
          >任务设置</mj-button
        >
      </div>
      <div class="right-items">
        <mj-button class="status-button" thin-font type="warn" icon="coin" @click="showCoinDetail"
          >乐贝明细</mj-button
        >
      </div>
    </div>
    <div class="box">
      <mj-table
        ref="gridRef"
        class="coin-table"
        :grid="grid"
        :grid-events="gridEvents"
        hide-remove
        hide-search
        hide-toolbar
        hide-pager
        selectable
        @select-change="selectChange"
      >
        <template #look="{ row }">
          <user-figure
            :personal-list="row.personInUsePersonalities"
            :sex="row.sex"
            :nickname="row.nickName"
          />
        </template>
      </mj-table>
      <user-detail v-model="userDetailVisible" :user="user" />
      <batch-operation
        v-model="batchOperationVisible"
        :users="selectedUsers"
        @operation-success="uncheckAll"
      />
      <batch-send v-model="batchSendVisible" :users="selectedUsers" @send-success="uncheckAll" />
    </div>
  </div>
</template>

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

.basic-info {
  :deep(.vxe-grid--table-container) {
    border-top-left-radius: 0 !important;
    border-top-right-radius: 0 !important;

    .row-disabled {
      .vxe-cell--label {
        color: rgba(212, 84, 78, 0.45);
      }
    }
  }

  .box {
    height: 76.83vh;
    // border-bottom-left-radius: $raduis;
    // border-bottom-right-radius: $raduis;
    // overflow: hidden;

    // .el-scrollbar {
    //   max-height: calc(100% - 74px);
    // }
  }

  :deep(.batch-button) {
    width: 280px;
  }

  .title {
    width: 100%;
    display: table;
    margin-bottom: $space-1_h;
    &-item {
      display: table-cell;
      width: 25%;
      text-align: center;
      &:first-child {
        width: 340px;
      }
    }
  }
  .user {
    display: flex;
    align-items: center;
    justify-content: center;
    padding-left: 2rem;
    height: 100%;
    gap: 10px;
    .sex {
      margin: 0 $space-2;
    }
    .nickname {
      width: 286px;
      height: 7vh;
      display: flex;
      background-repeat: no-repeat;
      background-size: 100% 100%;
      padding: 0 12px;
      position: relative;
      @include single_ellipsis;
      margin-top: -1.67vh;

      .x-line-font {
        position: absolute;
        bottom: 1.17vh;
        left: 50%;
        transform: translateX(-50%);
        font-size: 1.83vh;
      }
    }
  }
}
</style>
