import { IncomingMessage } from 'http'
import Mock from 'mockjs'
import qs from 'qs'
import { MockMethod } from 'vite-plugin-mock'
import { Response, Request } from '../_util'

const parseFormParams = (req: IncomingMessage): Promise<Recordable> => {
    return new Promise((resolve) => {
        let body = ''
        req.on('data', function (chunk) {
            body += chunk
        })
        req.on('end', function () {
            resolve(qs.parse(body) as any)
            return
        })
    })
}

export function createFakeUserList() {
    return [
        {
            userId: '1',
            account: 'admin',
            realName: 'Basic Admin',
            avatar: 'https://q1.qlogo.cn/g?b=qq&nk=190848757&s=640',
            desc: 'manager',
            password: '123456',
            token: 'fakeToken1',
            homePath: '/dashboard/workbench',
            roles: [
                {
                    name: 'Super Admin',
                    uid: 'super',
                    id: '1',
                },
            ],
        },
        {
            userId: '2',
            account: 'test',
            password: '123456',
            realName: 'test user',
            avatar: 'https://q1.qlogo.cn/g?b=qq&nk=339449197&s=640',
            desc: 'tester',
            token: 'fakeToken2',
            homePath: '/dashboard/workbench',
            roles: [
                {
                    name: 'Tester',
                    uid: 'test',
                    id: '2',
                },
            ],
        },
    ]
}

const fakeCodeList: any = {
    '1': ['1000', '3000', '5000'],

    '2': ['2000', '4000', '6000'],
}
export default [
    // mock user login
    {
        url: '/basic-api/auth/login',
        timeout: 200,
        method: 'post',
        // response: ({ query }) => {
        //     const { account, password } = query
        //     console.log(JSON.stringify(query))
        //     const checkUser = createFakeUserList().find(
        //         (item) => item.account === account && password === item.password,
        //     )
        //     if (!checkUser) {
        //         return Response.no('Incorrect account or password！')
        //     }
        //     const { userId, account: _account, token, realName, desc, roles } = checkUser
        //     return Response.ok({
        //         roles,
        //         userId,
        //         account: _account,
        //         token,
        //         realName,
        //         desc,
        //     })
        // },
        rawResponse: async (req, res) => {
            const { account, password } = await parseFormParams(req)
            const checkUser = createFakeUserList().find(
                (item) => item.account === account && password === item.password,
            )
            if (!checkUser) {
                return Response.no('Incorrect account or password！')
            }
            const { userId, account: _account, token, realName, desc, roles } = checkUser
            const response = Response.ok({
                roles,
                userId,
                account: _account,
                token,
                realName,
                desc,
            })

            res.setHeader('Content-Type', 'application/json')
            res.statusCode = 200
            res.end(JSON.stringify(Mock.mock(response)))
        },
    },
    {
        url: '/basic-api/user/getUserInfo',
        method: 'get',
        response: (request: Request) => {
            const token = Request.getRequestToken(request)
            if (!token) return Response.no('Invalid token')
            const checkUser = createFakeUserList().find((item) => item.token === token)
            if (!checkUser) {
                return Response.no('The corresponding user information was not obtained!')
            }
            return Response.ok(checkUser)
        },
    },
    {
        url: '/basic-api/user/getPermCode',
        timeout: 200,
        method: 'get',
        response: (request: Request) => {
            const token = Request.getRequestToken(request)
            if (!token) return Response.no('Invalid token')
            const checkUser = createFakeUserList().find((item) => item.token === token)
            if (!checkUser) {
                return Response.no('Invalid token!')
            }
            const codeList = fakeCodeList[checkUser.userId]

            return Response.ok(codeList)
        },
    },
    {
        url: '/basic-api/auth/logout',
        timeout: 200,
        method: 'get',
        response: (request: Request) => {
            const token = Request.getRequestToken(request)
            if (!token) return Response.no('Invalid token')
            const checkUser = createFakeUserList().find((item) => item.token === token)
            if (!checkUser) {
                return Response.no('Invalid token!')
            }
            return Response.ok(undefined, { message: 'Token has been destroyed' })
        },
    },
    {
        url: '/basic-api/auth/testRetry',
        statusCode: 405,
        method: 'get',
        response: () => {
            return Response.no('Error!')
        },
    },
] as MockMethod[]
