text: const qs = require('qs');
  const Mock = require('mockjs');
  const config = require('../utils/config');
  const { apiPrefix } = config;
  
  const dataForTest = require('../utils/data-for-test');
  
  
  import countries from '../utils/countries'
  
  // const countrys_arr = [
  //     {
  //       name: 'Russia',
  //       cities: ['Челябинск', 'Волгоград', 'Краснодар', 'Питер', 'Москва', 'новгород', 'Уфа', 'Киров', 'Тюмень', 'павлодар']
  //     },
  // 	{
  // 		name: 'USA',
  // 		cities: ['Texas', 'California', 'WC', 'NY', 'Michigan', 'LA', 'Yota', 'Sprigfield', 'Nano', 'Dollar']
  // 	},
  // ];
  
  let countryForIteration = null;
  let getCountry = () => {
  	countryForIteration = Mock.Random.natural(0, Array.from(countries).length -1);
      return countryForIteration
  }
  
  let usersListData = Mock.mock({
    'data|40-50': [
      {
        id: '@id',
        name: '@name',
        nickName: '@last',
        phone: /^1[34578]\d{9}$/,
        'age|11-99': 1,
        //address: '@county(true)',
       // address: null,
        isMale: '@boolean',
        email: '@email',
        createTime: '@datetime',
        avatar () {
          return Mock.Random.image('100x100', Mock.Random.color(), '#757575', 'png', this.nickName.substr(0, 1))
        },
      },
    ],
  })
  
  //dataForTest
  
  const reformatData = (function () {
  	for (let key in usersListData.data) {
  		if (usersListData.data[key]) {
  			usersListData.data[key] = dataForTest[Mock.Random.natural(0, dataForTest.length -1)];
  			usersListData.data[key].country !== '' ?
  			  usersListData.data[key].address = usersListData.data[key].country + "\u00A0" + usersListData.data[key].city
              : usersListData.data[key].address = 'нет данных';
  		}
  	}
  }());
  
  // const addAdress = (function () {
  // 	for (let key in usersListData.data) {
  // 	  if (usersListData.data[key]) {
  // 	    if (countries[getCountry()]) {
  // 		    usersListData.data[key].address = countries[getCountry()].name;
  // 		    if (countries[countryForIteration].children[Mock.Random.natural(0, countries[countryForIteration].children.length - 1)]) {
  // 			    usersListData.data[key].address += "\u00A0" + countries[countryForIteration].children[Mock.Random.natural(0, countries[countryForIteration].children.length - 1)].name
  //             }
  //         }
  //       }
  // 	}
  // }());
  
  
  
  
  let database = usersListData.data
  
  const userPermission = {
    DEFAULT: [
      'dashboard', 'chart',
    ],
    ADMIN: [
      'dashboard', 'users', 'UIElement', 'UIElementIconfont', 'chart',
    ],
    DEVELOPER: ['dashboard', 'users', 'UIElement', 'UIElementIconfont', 'chart'],
  }
  
  const adminUsers = [
    {
      id: 0,
      username: 'admin',
      password: 'admin',
      permissions: userPermission.ADMIN,
    }, {
      id: 1,
      username: 'guest',
      password: 'guest',
      permissions: userPermission.DEFAULT,
    }, {
      id: 2,
      username: '吴彦祖',
      password: '123456',
      permissions: userPermission.DEVELOPER,
    },
  ]
  
  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 { username, password } = req.body
      const user = adminUsers.filter((item) => item.username === username)
  
      if (user.length > 0 && user[0].password === password) {
        const now = new Date()
        now.setDate(now.getDate() + 1)
        res.cookie('token', JSON.stringify({ id: user[0].id, deadline: now.getTime() }), {
          maxAge: 900000,
          httpOnly: true,
        })
        res.json({ success: true, message: 'Ok' })
      } else {
        res.status(400).end()
      }
    },
  
    [`GET ${apiPrefix}/user/logout`] (req, res) {
      res.clearCookie('token')
      res.status(200).end()
    },
  
    [`GET ${apiPrefix}/user`] (req, res) {
      const cookie = req.headers.cookie || ''
      const cookies = qs.parse(cookie.replace(/\s/g, ''), { delimiter: ';' })
      const response = {}
      const user = {}
      if (!cookies.token) {
        res.status(200).send({ message: 'Not Login' })
        return
      }
      const token = JSON.parse(cookies.token)
      if (token) {
        response.success = token.deadline > new Date().getTime()
      }
      if (response.success) {
        const userItem = adminUsers.filter(_ => _.id === token.id)
        if (userItem.length > 0) {
          user.permissions = userItem[0].permissions
          user.username = userItem[0].username
          user.id = userItem[0].id
        }
      }
      response.user = user
      res.json(response)
    },
  
    [`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') {
                if (other[key] !== 'нет данных') {
  	              return other[key].every(iitem => item[key].indexOf(iitem) > -1)
                } else {
                    //return ['нет данных']
                    return ['нет данных'].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({
        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 ? newData.nickName.substr(0, 1) : null ) ;
      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)
      }
    },
  }
  