package com.ozs.mdm.service.util;



import com.ozs.mdm.constant.StatusCode;
import com.ozs.mdm.util.R;
import com.github.pagehelper.Page;

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

/**
 * @author 宋显哲
 * @version 1.0.0 创建于 2018/1/31
 **/
public class ReturnUtil {

    public static R createExceptionReturn(Exception e) {
        String ex = e.getMessage();
        R r = new R();
        r.setPage(0);
        r.setPageSize(0);
        r.setTotalPageCount(0);
        r.setTotalNumber(0);
        if (ex.contains("StatusCode:")) {
            return r.retStatus(ex.split(":")[1]);
        }
        return r.retStatus(StatusCode.FAILURE);
    }
    public static R createExceptionReturnNew(Exception e) {
        String ex = e.getMessage();
        R r = new R();
        if (ex.contains("StatusCode:")) {
            return r.retStatus(ex.split(":")[1]);
        }
        return r.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> R<List<T>> assemblyReturnData(Page<T> pageResult) {
        R<List<T>> r = new R<>();
        //当前叶
        int page = pageResult.getPageNum();
        //页大小
        int pageSize = pageResult.getPageSize();
        //总条数
        long totalNumber = pageResult.getTotal();
        //总页数
        int totalPageCount = pageResult.getPages();
        //数据
        r.setTotalNumber((int) totalNumber);
        r.setPage(page);
        r.setTotalPageCount(totalPageCount);
        r.setPageSize(pageSize);
        r.setData(pageResult.getResult().isEmpty() ? null : pageResult.getResult());
        pageResult.close();
        return r;
    }
}
