package com.pangu.common.core.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pangu.common.core.domain.AjaxResult;
import com.pangu.common.core.page.TableDataInfo;
import com.pangu.common.utils.ServletUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 基础控制器
 * @author pangu
 */
public class BaseController {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 设置分页参数
     */
    protected void startPage() {
        Integer pageNum = ServletUtils.getParameterToInt("pageNum", 1);
        Integer pageSize = ServletUtils.getParameterToInt("pageSize", 10);
        PageHelper.startPage(pageNum, pageSize);
    }

    /**
     * 响应分页数据
     */
    protected TableDataInfo getDataTable(List<?> list) {
        TableDataInfo data = new TableDataInfo();
        data.setCode(200);
        data.setMsg("查询成功");
        data.setRows(list);
        data.setTotal(new PageInfo<>(list).getTotal());
        return data;
    }

    /**
     * 返回成功
     */
    protected AjaxResult success() {
        return AjaxResult.success();
    }

    protected AjaxResult success(String msg) {
        return AjaxResult.success(msg);
    }

    protected AjaxResult success(Object data) {
        return AjaxResult.success(data);
    }

    /**
     * 返回失败
     */
    protected AjaxResult error() {
        return AjaxResult.error();
    }

    protected AjaxResult error(String msg) {
        return AjaxResult.error(msg);
    }

    /**
     * 响应返回结果
     */
    protected AjaxResult toAjax(int rows) {
        return rows > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    protected AjaxResult toAjax(boolean result) {
        return result ? success() : error();
    }
}
