text: const qs = require('qs')
  const Mock = require('mockjs')
  const config = require('../utils/config')
  
  const { apiPrefix, cookieName } = config
  
  let usersListData = Mock.mock({
    'data|80-100': [
      {
        id: '@id',
        name: '@name',
        nickName: '@last',
        phone: /^1[34578]\d{9}$/,
        'age|11-99': 1,
        address: '@county(true)',
        isMale: '@boolean',
        email: '@email',
        createTime: '@datetime',
        avatar () {
          return Mock.Random.image('100x100', Mock.Random.color(), '#757575', 'png', this.nickName.substr(0, 1))
        },
      },
    ],
  })
  
  
  let database = usersListData.data
  
  const EnumRoleType = {
    ADMIN: 'admin',
    DEFAULT: 'guest',
    DEVELOPER: 'developer',
  }
  
  const userPermission = {
    DEFAULT: {
      visit: ['1', '2', '21', '7', '5', '51', '52', '53'],
      role: EnumRoleType.DEFAULT,
    },
    ADMIN: {
      role: EnumRoleType.ADMIN,
    },
    DEVELOPER: {
      role: EnumRoleType.DEVELOPER,
    },
  }
  
  const adminUsers = [
    {
      id: 0,
      account: 'admin',
      password: 'admin',
      permissions: userPermission.ADMIN,
    }, {
      id: 1,
      account: 'guest',
      password: 'guest',
      permissions: userPermission.DEFAULT,
    }, {
      id: 2,
      account: '吴彦祖',
      password: '123456',
      permissions: userPermission.DEVELOPER,
    }, {
      id: 1019,
      account: '15726940632',
      captcha: '0404',
      permissions: userPermission.ADMIN,
    }, {
      id: 419,
      account: 'admin@fanfandata.com',
      password: '123456',
      permissions: userPermission.ADMIN,
      authority: ['admin'],
    },
  ]
  
  const queryArray = (array, key, keyAlias = 'key') => {
    if (!(array instanceof Array)) {
      return null
    }
    let data
  
    for (let item of array) {
      if (item[keyAlias] === key) {
        data = item
        break
      }
    }
  
    if (data) {
      return data
    }
    return null
  }
  
  const NOTFOUND = {
    message: 'Not Found',
    documentation_url: 'http://localhost:8000/request',
  }
  
  module.exports = {
  
    [`POST ${apiPrefix}/user/login`] (req, res) {
      const { account, password } = req.body
      const user = adminUsers.filter(item => item.account === account)
  
      if (user.length > 0 && user[0].password === password) {
        let data_ = {
          user_id: user[0].id,
          token: user[0].token,
        }
        res.json({ code: 0, data: data_ })
      } else {
        if (user.length === 0) {
          res.json({ code: -1, error_msg: '账号不存在，请确认' })
        }
        res.status(400).end()
      }
    },
  
    [`GET ${apiPrefix}/user/user_manage/captcha`] (req, res) {
      res.json({ code: 0, data: '0404' })
    },
  
    [`GET ${apiPrefix}/user/get_info`] (req, res) {
      const info = {
        per_role: '管理员',
        nonce: '83915241ee6165fb23d7215bc57f81582f2d7fe007eac3',
        account: 'fsr@qq.con',
        name: 'gqr',
        ts: '1513519365',
        authority: ['1-1', '1-2', '1', '2-1-1', '2-1', '2', '3-1-1', '3-1-2', '3-1-3', '3-1', '3'],
        brief: '',
        pre_role: '',
        breif: 'dhgf风格',
      }
      const cookie = req.headers.cookie || ''
      const cookies = qs.parse(cookie.replace(/\s/g, ''), { delimiter: ';' })
  
      if (!cookies[cookieName.token]) {
        res.status(200).send({ message: 'Not Login', code: -3 })
        return
      }
  
      res.json({ code: 0, data: { info } })
    },
  
    [`GET ${apiPrefix}/users`] (req, res) {
      const { query } = req
      let { pageSize, page, ...other } = query
      pageSize = pageSize || 10
      page = page || 1
  
      let newData = database
      for (let key in other) {
        if ({}.hasOwnProperty.call(other, key)) {
          newData = newData.filter((item) => {
            if ({}.hasOwnProperty.call(item, key)) {
              if (key === 'address') {
                return other[key].every(iitem => item[key].indexOf(iitem) > -1)
              } else if (key === 'createTime') {
                const start = new Date(other[key][0]).getTime()
                const end = new Date(other[key][1]).getTime()
                const now = new Date(item[key]).getTime()
  
                if (start && end) {
                  return now >= start && now <= end
                }
                return true
              }
              return String(item[key]).trim().indexOf(decodeURI(other[key]).trim()) > -1
            }
            return true
          })
        }
      }
  
      res.status(200).json({
        code: 0,
        data: {
          data: newData.slice((page - 1) * pageSize, page * pageSize),
          total: newData.length,
        },
      })
    },
  
    [`DELETE ${apiPrefix}/users`] (req, res) {
      const { ids } = req.body
      database = database.filter(item => !ids.some(_ => _ === item.id))
      res.status(204).end()
    },
  
  
    [`POST ${apiPrefix}/user`] (req, res) {
      const newData = req.body
      newData.createTime = Mock.mock('@now')
      newData.avatar = newData.avatar || Mock.Random.image('100x100', Mock.Random.color(), '#757575', 'png', newData.nickName.substr(0, 1))
      newData.id = Mock.mock('@id')
  
      database.unshift(newData)
  
      res.status(200).end()
    },
  
    [`GET ${apiPrefix}/user/:id`] (req, res) {
      const { id } = req.params
      const data = queryArray(database, id, 'id')
      if (data) {
        res.status(200).json(data)
      } else {
        res.status(404).json(NOTFOUND)
      }
    },
  
    [`DELETE ${apiPrefix}/user/:id`] (req, res) {
      const { id } = req.params
      const data = queryArray(database, id, 'id')
      if (data) {
        database = database.filter(item => item.id !== id)
        res.status(204).end()
      } else {
        res.status(404).json(NOTFOUND)
      }
    },
  
    [`PATCH ${apiPrefix}/user/:id`] (req, res) {
      const { id } = req.params
      const editItem = req.body
      let isExist = false
  
      database = database.map((item) => {
        if (item.id === id) {
          isExist = true
          return Object.assign({}, item, editItem)
        }
        return item
      })
  
      if (isExist) {
        res.status(201).end()
      } else {
        res.status(404).json(NOTFOUND)
      }
    },
  }
  