import dayjs from 'dayjs'
import { get, post, remove } from './request'
import type { PageResponse } from './request'
import type { TextBook } from './subject/subject'
import obj from '@/utils/obj'
import type { RequestConfig } from './only-last'

interface Personality {
  name: string
  resourceUrl: string
  personalInfoResourceUrl: string
  productCode: string
  remark: number
}

export type Group = {
  id: any
  name: any
  label: any
  students: Student[]
}

export interface Student {
  id: any
  account: string
  nickName: string
  name: string
  sex: number
  avatarUrl: string
  lastLoginTime: string
  className: string
  classId: string
  groupName: string
  groupId: string
  cumulativeTimeDuration: number
  currentName: string
  currentLevelNum: number
  currentExp: number
  currentExpStart: number
  currentExpEnd: number
  nextName: string
  nextLevelNum: number
  nextExp: number
  personInUsePersonalities: Personality[]
  englishSubjectExpLevelVo: any // null in JSON
  learnGradeId: string
  currency: string
  diamond: string
  status: number
}

export type Class = {
  classId: any
  className: any
}

export type School = {
  schoolId: any
  schoolName: any
  schoolCurrency: any
  classList: Class[]
}

export type ClassStudent = {
  students: {
    list: Student[]
    map: Record<string, Student>
  }
  groups: {
    list: Group[]
    map: Record<string, Group>
  }
}

const studentManageApi = {
  // 获取学生列表
  getClassStudent: async (classId: any, config?: RequestConfig): Promise<ClassStudent> => {
    const data = (
      (await get(
        '/schoolUser/list',
        {
          classId,
          size: -1,
        },
        config,
      )) as any
    )?.rows
    if (!data?.length) return undefined as any
    const classStudent = { students: {}, groups: {} } as ClassStudent
    // 学员
    classStudent.students.list = data
    classStudent.students.map = obj.list2map(data, 'id')
    // 分组
    const groupMap = {} as Record<string, Group>
    classStudent.groups.map = groupMap
    const groupList = [] as Group[]
    classStudent.groups.list = groupList
    const defaultGroup = {
      id: 0,
      name: '未分组',
      students: [] as Student[],
    } as Group
    for (const student of data) {
      if (student.groupId) {
        // 有分组
        let group = groupMap[student.groupId]
        if (!group) {
          group = {
            id: student.groupId,
            name: student.groupName,
            label: student.groupName,
            students: [],
          }
          groupMap[student.groupId] = group
          groupList.push(group)
        }
        group.students.push(student)
      } else {
        // 无分组
        defaultGroup.students.push(student)
      }
    }
    // 按照组名排序分组
    groupList.sort((a, b) => a.name.localeCompare(b.name))
    return classStudent
  },

  // 获取学校列表
  getSchoolList: async (): Promise<School[]> => {
    return await get('/schoolUser/schoolClassList')
  },

  // 获取班级列表
  getClassListBySchoolId: async (id: any): Promise<Class[]> => {
    return await get(`/schoolUser/classListBySchoolId/${id}`)
  },

  // 获取班级汇总数据
  getClassTotalLearnData: async (params: anyObj, config?: RequestConfig) => {
    return await get('/sysUser/queryClassTotalLearnData', params, config)
  },

  // 获取班级每日数据
  getClassTodayLearnData: async (params: anyObj, config?: RequestConfig) => {
    return await get('/sysUser/queryClassTodayLearnData', params, config)
  },

  // 获取综合排名
  getClassRankingData: async (params: anyObj, config?: RequestConfig) => {
    return await get('/sysUser/queryClassRankingData', params, config)
  },

  // 获取学科数据
  getSubjectStudyData: async (params: anyObj, config?: RequestConfig) => {
    const data = (await get('/sysUser/queryClassSubjectLearnData', params, config)) as any
    // learnTime转为整数
    data?.forEach((item: anyObj) => {
      item.learnTime = Number(item.learnTime)
    })
    return data
  },

  // 重置密码
  resetPassword: async (ids: any) => {
    if (!Array.isArray(ids)) {
      ids = [ids]
    }
    return await post('/sysUser/resetPwdFront', { ids })
  },

  // 教师查询教材列表
  getClassBookList: async (data: GetBookListApi, config?: RequestConfig): Promise<TextBook[]> => {
    return await get('/teacherTextBook/list', data, config)
  },

  // 教师删除教材
  removeClassBook: async (id: any) => {
    return await remove(`/teacherTextBook/${id}`)
  },

  // 教师添加教材
  addClassBook: async (data: AddBookApi) => {
    return await post('/teacherTextBook', data)
  },

  // 增加乐贝
  addCoin: async (data: CoinDiamondApi) => {
    processCoinDiamondApi(data, true)
    return await post('/reward/coin/reward', data)
  },

  // 减少乐贝
  subCoin: async (data: CoinDiamondApi) => {
    processCoinDiamondApi(data, false)
    return await post('/reward/coin/reduce', data)
  },

  // 批量操作乐贝
  coinBatch: async (data: CoinDiamondBatchApi) => {
    data = processedCoinDiamondBatchApi(data)
    return await post('/reward/coin/rewardBatch', data)
  },

  // 增加钻石
  addDiamond: async (data: CoinDiamondApi) => {
    processCoinDiamondApi(data, true)
    return await post('/reward/diamond/reward', data)
  },

  // 减少钻石
  subDiamond: async (data: CoinDiamondApi) => {
    processCoinDiamondApi(data, false)
    return await post('/reward/diamond/reduce', data)
  },

  // 批量操作钻石
  diamondBatch: async (data: CoinDiamondBatchApi) => {
    data = processedCoinDiamondBatchApi(data)
    return await post('/reward/diamond/rewardBatch', data)
  },

  // 修改学员状态
  changeStatus: async (data: ChangeStatusApi) => {
    return await post('/sysUser/changeStatusFront', data)
  },

  changeStatusBatch: async (data: ChangeStatusBatchApi) => {
    return await post('/sysUser/changeStatusFrontBatch', data)
  },

  // 获取乐币流水
  getCoinTransaction: async (
    data: GetCoinTransactionApi,
  ): Promise<PageResponse<CoinTransaction>> => {
    return await get('/org/school/transaction/list', data)
  },
}

function processCoinDiamondApi(data: CoinDiamondApi, add: boolean) {
  const amount = Number(data.amount)
  if (isNaN(amount) || amount <= 0) {
    throw '请输入正确的数量'
  }
  if (!data.bizDate) {
    data.bizDate = dayjs().format('YYYY-MM-DD HH:mm:ss')
  }
  if (!data.reason) {
    data.reason = add ? '手动奖励' : '手动扣除'
  }
}

function processedCoinDiamondBatchApi(data: CoinDiamondBatchApi) {
  const arr = [] as CoinDiamondBatchApi
  for (const item of data) {
    try {
      processCoinDiamondApi(item, item.operation === operation_add)
      arr.push(item)
    } catch (e) {}
  }
  if (arr.length === 0) {
    throw '没有需要操作的数据'
  }
  return arr
}

type GetBookListApi = {
  classId: any
  subjectId: any
}

type AddBookApi = {
  classId: any
  textBookId: any
}

export const type_coin = 1
export const type_diamond = 2
export type CoinDiamondApi = {
  reason?: string
  amount: any
  userId: any
  bizDate?: string
  remark?: string
  typeId?: any
}

export const operation_add = 1
export const operation_sub = 2
export type CoinDiamondBatchApi = (CoinDiamondApi & {
  operation: any
})[]

type ChangeStatusApi = {
  id?: any
  classId?: any
  status: any
}

type ChangeStatusBatchApi = {
  id: any
  status: any
}[]

// 获取乐币流水
type GetCoinTransactionApi = {
  schoolId: any
  typeCode: any
  keyword?: any
  current: any
  size: any
}

export type CoinTransaction = {
  id: any
  schoolId: any
  schoolName: string
  operation: any
  typeCode: any
  amount: any
  userId: any
  transactionId: string
  bizDate: string
  remark: string
  record: any
}

export const status_enabled = 0
export const status_disabled = 1

export default studentManageApi
