import request from '@/service/request';
import { baseUrl, env } from '@/config/env';

export class BaseService {
	constructor() {
		const crud = {
			page: 'list',
			list: 'list',
			info: 'detail',
			add: 'add',
			delete: 'delete',
			update: 'update'
		};

		if (!this.permission) {
			this.permission = {};
		}

		for (let i in crud) {
			if (this.namespace) {
				this.permission[i] = this.namespace.replace(/\//g, ':') + ':' + crud[i];
			} else {
				this.permission[i] = crud[i];
			}
		}
	}

	request(options = {}) {
		if (!options.params) {
			options.params = {};
		}

		let path = '';

		if (env.NODE_ENV == 'development') {
			path = this.proxy || baseUrl;
		} else {
			if (this.proxy) {
				path = this.url;
			} else {
				path = baseUrl;
			}
		}

		if (this.namespace) {
			path += '/' + this.namespace;
		}

		console.log('path', path);
		console.log('options.url', options.url);

		options.url = path + options.url;
		// options.params.t = Date.parse(new Date());

		console.log(`[${options.method || 'GET'}]`, options.url);
		return request(options);
	}

	list(params) {
		return this.request({
			url: '/list',
			params: {
				...params
			}
		});
	}

	page(params) {
		return this.request({
			url: '/list',
			params: {
				...params
			}
		});
	}

	info(params) {
		return this.request({
			url: '/detail',
			params: {
				...params
			}
		});
	}

	update(params) {
		console.log('this', this);
		return this.request({
			url: '/update',
			method: 'POST',
			data: {
				...params
			}
		});
	}

	delete(params) {
		return this.request({
			url: '/delete',
			method: 'POST',
			data: {
				...params
			}
		});
	}

	add(params) {
		return this.request({
			url: '/add',
			method: 'POST',
			data: {
				...params
			}
		});
	}
}
