import { Request, Response } from 'express';
import { md5 } from 'js-md5';

import { AdminAPI } from '../src/constants/api';

const waitTime = (time: number = 100) => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

const { ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION } = process.env;

/**
 * 当前用户的权限，如果为空代表没登录
 * current user access， if is '', user need login
 * 如果是 pro 的预览，默认是有权限的
 */
let access = ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION === 'site' ? 'admin' : '';

const getAccess = () => {
  return access;
};

export default {
  [`POST ${AdminAPI.USER}`]: (req: Request, res: Response) => {
    if (!getAccess()) {
      res.status(401).send({
        data: {
          isLogin: false,
        },
        errorCode: '401',
        errorMessage: '请先登录！',
        success: true,
      });
      return;
    }
    res.send({
      id: '1',
      userId: '00000001',
      userName: '小叶',
      created: Date.now().toString(),
      updated: Date.now().toString(),
    });
  },
  [`POST ${AdminAPI.LOGIN}`]: async (req: Request, res: Response) => {
    const { pwd, userName, type } = req.body;
    await waitTime(2000);
    if (pwd === md5('boluo') && userName === 'admin') {
      res.json({
        token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9',
        expires: 3600,
      });
      access = 'admin';
      return;
    }
    if (pwd === md5('user') && userName === 'user') {
      res.json({
        token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9',
        expires: 3600,
      });
      access = 'user';
      return;
    }

    res.send({
      status: 'error',
      type,
      currentAuthority: 'guest',
    });
    access = 'guest';
  },
  [`POST ${AdminAPI.OUT_LOGIN}`]: (req: Request, res: Response) => {
    access = '';
    res.send({ data: {}, success: true });
  },
};
