package com.ozs.da.utils;

import com.ozs.da.constant.StatusCode;
import com.ozs.da.entity.ReturnData;
import com.github.pagehelper.Page;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 许明
 * on 2019/3/5.
 * @version 2.0.0
 */
public class ReturnUtil {

    public static ReturnData createExceptionReturn(Exception e) {
        String ex = e.getMessage();
        ReturnData returnData = new ReturnData();
        returnData.setPage(0);
        returnData.setPageSize(0);
        returnData.setTotalPageCount(0);
        returnData.setTotalNumber(0);
        if (ex.contains("StatusCode:")) {
            return returnData.retStatus(ex.split(":")[1]);
        }
        return returnData.retStatus(StatusCode.FAILURE);
    }
    public static ReturnData createExceptionReturnNew(Exception e) {
        String ex = e.getMessage();
        ReturnData returnData = new ReturnData();
        if (ex.contains("StatusCode:")) {
            return returnData.retStatus(ex.split(":")[1]);
        }

        return returnData.retStatus(StatusCode.FAILURE);
    }

    public static void newStatusException(String statusCode) throws Exception {
        StringBuilder sb = new StringBuilder("StatusCode:");
        sb.append(statusCode);
        throw new Exception(sb.toString());
    }

    public static void returnOpt(HttpServletResponse response, String code) throws Exception {
        response.setContentType("application/json;utf-8");
        Map<String, String> ret = new HashMap<>();
        ret.put("msg", StatusCode.getMsg(code));
        ret.put("code", code);
        String json = JsonUtil.toJson(ret);
        response.getWriter().print(json);
        response.setStatus(200);
    }



    /**
     * 装配分页结果
     *
     * @param pageResult 分页结果
     * @param <T>        对象
     * @return 返回结果
     */
    public static <T> ReturnData<List<T>> assemblyReturnData(Page<T> pageResult) {
        ReturnData<List<T>> returnData = new ReturnData<>();
        //当前叶
        int page = pageResult.getPageNum();
        //页大小
        int pageSize = pageResult.getPageSize();
        //总条数
        long totalNumber = pageResult.getTotal();
        //总页数
        int totalPageCount = pageResult.getPages();
        //数据
        returnData.setTotalNumber((int) totalNumber);
        returnData.setPage(page);
        returnData.setTotalPageCount(totalPageCount);
        returnData.setPageSize(pageSize);
        returnData.setData(pageResult.getResult().isEmpty() ? null : pageResult.getResult());
        pageResult.close();
        return returnData;
    }

    public static <T> boolean isSkipToStartPage(Page<T> pageResult) {
        if (pageResult.getPageNum() > 1 && pageResult.getPageSize() > 10 && pageResult.getResult().isEmpty()) {
            pageResult.close();
            return true;
        }
        return false;
    }
}
