import Mock from "mockjs";

let List = [];
const count = 200;
const phonePrefix = ['155', '138', '166', '150', '188'];

for (let i = 0; i < count; i++) {
    let index = Math.floor(Math.random() * phonePrefix.length);
    let phone = phonePrefix[index] + Mock.mock(/\d{8}/);
    List.push(
        Mock.mock({
            id: Mock.Random.guid(),
            "messageTitle": "@cword(4)",
            phoneNumber: phone,
            "publishTime": "@date('yy-MM-dd hh:mm:ss')",
            content: "@cword(150)"
        })
    )
}

function paramObj(url) {
    const search = url.split('?')[1];
    if (!search) {
        return {}
    }
    return JSON.parse(
        '{"' +
        decodeURIComponent(search)
            .replace(/"/g, '\\"')
            .replace(/&/g, '","')
            .replace(/=/g, '":"') +
        '"}'
    )
}

export default {
    getMessageList: config => {
        const { name, page = 1, limit = 10 } = paramObj(config.url);
        const mockList = List.filter(user => {
            if (name && user.name.indexOf(name) === -1 && user.addr.indexOf(name) === -1) return false;
            return true;
        })
        const pageList = mockList.filter((item, index) => index < limit * page && index >= limit * (page - 1));
        return {
            code: 200,
            count: mockList.length,
            list: pageList
        }
    },
    searchMessageList: config => {
        const { name } = paramObj(config.url);
        const searchList = List.filter(user => {
            return user.messageTitle === name;
        })
        return {
            code: 200,
            count: searchList.length,
            list: searchList
        }
    },
    detailMessage: config => {
        const { id } = paramObj(config.url);
        const detail = List.filter(user => {
            return user.id === id;
        })
        return {
            code: 200,
            data: detail
        }
    },
    deleteMessage: config => {
        const { id } = JSON.parse(config.body);
        if (!id) {
            return {
                code: -999,
                message: '参数不正确'
            }
        } else {
            List = List.filter(u => u.id !== id)
            return {
                code: 200,
                message: '删除成功'
            }
        }
    },
}