/**
 * 用户相关Mock接口
 * @author pangu
 */
import Mock from 'mockjs'

// 存储验证码，模拟服务端session
const captchaStore = {}

/**
 * 生成验证码图片（简单的SVG）
 */
const generateCaptcha = () => {
  const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789'
  let code = ''
  for (let i = 0; i < 4; i++) {
    code += chars.charAt(Math.floor(Math.random() * chars.length))
  }

  // 生成简单的SVG验证码
  const colors = ['#f56c6c', '#409eff', '#67c23a', '#e6a23c', '#909399']
  const randomColor = () => colors[Math.floor(Math.random() * colors.length)]

  const svg = `
    <svg xmlns="http://www.w3.org/2000/svg" width="100" height="40">
      <rect width="100%" height="100%" fill="#f5f5f5"/>
      ${code.split('').map((char, i) => `
        <text x="${15 + i * 22}" y="${28 + Math.random() * 8 - 4}" 
              fill="${randomColor()}" 
              font-size="${18 + Math.random() * 6}"
              transform="rotate(${Math.random() * 20 - 10}, ${15 + i * 22}, 25)">
          ${char}
        </text>
      `).join('')}
      ${Array.from({ length: 3 }).map(() => `
        <line x1="${Math.random() * 100}" y1="${Math.random() * 40}" 
              x2="${Math.random() * 100}" y2="${Math.random() * 40}"
              stroke="${randomColor()}" stroke-width="1"/>
      `).join('')}
    </svg>
  `.trim()

  // 转为base64
  const base64 = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svg)))

  return { code, img: base64 }
}

// 获取验证码
Mock.mock(/\/api\/captchaImage/, 'get', () => {
  const uuid = Mock.Random.guid()
  const captcha = generateCaptcha()

  // 存储验证码
  captchaStore[uuid] = captcha.code.toLowerCase()

  // 5分钟后过期
  setTimeout(() => {
    delete captchaStore[uuid]
  }, 5 * 60 * 1000)

  return {
    code: 200,
    msg: '操作成功',
    img: captcha.img,
    uuid: uuid
  }
})

// 登录
Mock.mock('/api/login', 'post', (options) => {
  const body = JSON.parse(options.body)
  const { username, password, code, uuid } = body

  // 验证码校验（开发环境可以用1234绕过）
  const storedCode = captchaStore[uuid]
  if (code !== '1234' && (!storedCode || storedCode !== code.toLowerCase())) {
    return { code: 500, msg: '验证码错误' }
  }

  // 删除已使用的验证码
  delete captchaStore[uuid]

  // 账号密码校验
  if (username === 'admin' && password === 'admin123') {
    return {
      code: 200,
      msg: '登录成功',
      token: Mock.Random.guid()
    }
  }

  return { code: 500, msg: '用户名或密码错误' }
})

// 获取用户信息
Mock.mock(/\/api\/getInfo/, 'get', () => {
  return {
    code: 200,
    msg: '操作成功',
    data: {
      userId: 1,
      userName: 'admin',
      nickName: '超级管理员',
      avatar: '',
      roles: ['admin'],
      permissions: ['*:*:*']
    }
  }
})

// 退出登录
Mock.mock('/api/logout', 'post', () => {
  return {
    code: 200,
    msg: '退出成功'
  }
})

// 首页统计数据
Mock.mock(/\/api\/dashboard\/stats/, 'get', () => {
  return {
    code: 200,
    msg: '操作成功',
    data: {
      schoolCount: Mock.Random.integer(50, 200),
      memberCount: Mock.Random.integer(10000, 50000),
      studentCount: Mock.Random.integer(50000, 200000),
      appCount: Mock.Random.integer(5, 20)
    }
  }
})
