/**
 * 学生管理Mock数据
 * @author pangu
 */
import Mock from 'mockjs'

// 学校树数据（学校>年级>班级）
const schoolTree = [
  {
    id: 1,
    label: '武汉市第一小学',
    type: 'school',
    children: [
      {
        id: 11,
        label: '一年级',
        type: 'grade',
        children: [
          { id: 111, label: '1班', type: 'class' },
          { id: 112, label: '2班', type: 'class' },
          { id: 113, label: '3班', type: 'class' }
        ]
      },
      {
        id: 12,
        label: '二年级',
        type: 'grade',
        children: [
          { id: 121, label: '1班', type: 'class' },
          { id: 122, label: '2班', type: 'class' }
        ]
      },
      {
        id: 13,
        label: '三年级',
        type: 'grade',
        children: [
          { id: 131, label: '1班', type: 'class' },
          { id: 132, label: '2班', type: 'class' }
        ]
      }
    ]
  },
  {
    id: 2,
    label: '武汉市第二中学',
    type: 'school',
    children: [
      {
        id: 21,
        label: '七年级',
        type: 'grade',
        children: [
          { id: 211, label: '1班', type: 'class' },
          { id: 212, label: '2班', type: 'class' }
        ]
      },
      {
        id: 22,
        label: '八年级',
        type: 'grade',
        children: [
          { id: 221, label: '1班', type: 'class' },
          { id: 222, label: '2班', type: 'class' }
        ]
      }
    ]
  },
  {
    id: 3,
    label: '黄冈中学',
    type: 'school',
    children: [
      {
        id: 31,
        label: '高一',
        type: 'grade',
        children: [
          { id: 311, label: '1班', type: 'class' },
          { id: 312, label: '2班', type: 'class' }
        ]
      },
      {
        id: 32,
        label: '高二',
        type: 'grade',
        children: [
          { id: 321, label: '1班', type: 'class' }
        ]
      }
    ]
  }
]

// 学生列表数据
const students = []
const genderList = ['0', '1', '2'] // 未知、男、女
const subjectList = ['语文', '数学', '英语', '物理', '化学', '生物']

for (let i = 1; i <= 50; i++) {
  students.push(Mock.mock({
    id: i,
    name: '@cname',
    studentNo: 'S2026' + String(i).padStart(4, '0'),
    'gender|1': genderList,
    birthday: '@date("yyyy-MM")',
    region: '湖北省武汉市武昌区',
    schoolId: '@pick([1, 2, 3])',
    schoolName: '@pick(["武汉市第一小学", "武汉市第二中学", "黄冈中学"])',
    gradeName: '@pick(["一年级", "二年级", "三年级", "七年级", "八年级", "高一", "高二"])',
    className: '@pick(["1班", "2班", "3班"])',
    'subject|1': subjectList,
    userId: '@integer(1, 100)',
    userNickname: '@cname',
    userPhone: /1[3-9]\d{9}/,
    createTime: '@datetime("yyyy-MM-dd HH:mm:ss")'
  }))
}

// 获取学校树
Mock.mock(/\/api\/student\/schoolTree/, 'get', () => {
  return {
    code: 200,
    data: schoolTree
  }
})

// 解析URL参数
function getUrlParams(url) {
  const params = {}
  const queryString = url.split('?')[1]
  if (queryString) {
    queryString.split('&').forEach(param => {
      const [key, value] = param.split('=')
      params[decodeURIComponent(key)] = decodeURIComponent(value || '')
    })
  }
  return params
}

// 学生分页列表
Mock.mock(/\/api\/student\/list/, 'get', (options) => {
  const params = getUrlParams(options.url)
  const pageNum = parseInt(params.pageNum) || 1
  const pageSize = parseInt(params.pageSize) || 10
  const name = params.name || ''
  const studentNo = params.studentNo || ''
  const gender = params.gender || ''
  const userPhone = params.userPhone || ''
  const subject = params.subject || ''
  const schoolId = params.schoolId || ''
  const gradeId = params.gradeId || ''
  const classId = params.classId || ''

  // 过滤
  let filtered = students.filter(item => {
    if (name && !item.name.includes(name)) return false
    if (studentNo && !item.studentNo.includes(studentNo)) return false
    if (gender && item.gender !== gender) return false
    if (userPhone && !item.userPhone.includes(userPhone)) return false
    if (subject && item.subject !== subject) return false
    // 树过滤可以更精细，这里简单处理
    if (schoolId && String(item.schoolId) !== schoolId) return false
    return true
  })

  const total = filtered.length
  const start = (pageNum - 1) * pageSize
  const rows = filtered.slice(start, start + pageSize)

  return {
    code: 200,
    total,
    rows
  }
})

// 获取学生详情
Mock.mock(/\/api\/student\/\d+/, 'get', (options) => {
  const id = parseInt(options.url.match(/\/api\/student\/(\d+)/)[1])
  const student = students.find(s => s.id === id)
  return {
    code: 200,
    data: student || null
  }
})

// 新增学生
Mock.mock('/api/student', 'post', () => {
  return { code: 200, msg: '新增成功' }
})

// 修改学生
Mock.mock(/\/api\/student/, 'put', () => {
  return { code: 200, msg: '修改成功' }
})

// 删除学生
Mock.mock(/\/api\/student\/\d+/, 'delete', () => {
  return { code: 200, msg: '删除成功' }
})

// 批量导入
Mock.mock('/api/student/import', 'post', () => {
  return {
    code: 200,
    msg: '导入成功',
    data: {
      successCount: 10,
      failCount: 2,
      failList: [
        { row: 3, reason: '学号重复' },
        { row: 7, reason: '学校不存在' }
      ]
    }
  }
})

// 下载模板
Mock.mock('/api/student/template', 'get', () => {
  return { code: 200, msg: '请使用真实下载接口' }
})

// 学科列表
Mock.mock('/api/student/subjects', 'get', () => {
  return {
    code: 200,
    data: subjectList.map((name, index) => ({ id: index + 1, name }))
  }
})
