/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package com.huijy.web.controller.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huijy.common.constant.HttpStatus;
import com.huijy.common.core.page.PageDomain;
import com.huijy.common.core.page.TableDataInfo;
import com.huijy.common.core.page.TableSupport;
import com.huijy.common.exception.ServiceException;
import com.huijy.common.exception.base.BaseException;
import com.huijy.common.utils.ip.IpUtils;
import com.huijy.common.utils.sql.SqlUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * Controller公共组件
 *
 * @author Mark sunlightcs@gmail.com
 */
public abstract class ApiAbstractController {
	protected Logger logger = LoggerFactory.getLogger(getClass());
	/**
	 * 得到request对象
	 */
	@Autowired
	protected HttpServletRequest request;

	public  <T> T getClassRequest(Class<T> clazz){

		StringBuilder sb = new StringBuilder();
		try (BufferedReader reader = request.getReader()) {
			char[] buff = new char[1024];
			int len;
			while ((len = reader.read(buff)) != -1) {
				sb.append(buff, 0, len);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			return JSON.parseObject(sb.toString(),clazz);
		} catch (Exception e) {
			throw new ServiceException("获取参数失败");
		}

	}


	public JSONObject getJsonRequest() {
		JSONObject result = null;
		StringBuilder sb = new StringBuilder();
		try (BufferedReader reader = request.getReader()) {
			char[] buff = new char[1024];
			int len;
			while ((len = reader.read(buff)) != -1) {
				sb.append(buff, 0, len);
			}
			result = JSONObject.parseObject(sb.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}

		return result;
	}


	public String getXmlStrRequest() throws IOException {

			request.setCharacterEncoding("UTF-8");

			InputStream in = request.getInputStream();
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = in.read(buffer)) != -1) {
				out.write(buffer, 0, len);
			}
			out.close();
			in.close();
			//xml数据
			String reponseXml = new String(out.toByteArray(), "utf-8");
			return  reponseXml;

	}

	/**
	 * 获取请求方IP
	 *
	 * @return 客户端Ip
	 */
	public String getClientIp() {
		String ip = IpUtils.getIpAddr(request);
		if (StringUtils.isBlank(ip)){
			ip = "8.8.8.8";
		}
		return ip;
	}

	/**
	 * 设置请求分页数据
	 */
	protected void startPage()
	{
		PageDomain pageDomain = TableSupport.buildPageRequest();
		Integer pageNum = pageDomain.getPageNum();
		Integer pageSize = pageDomain.getPageSize();
		if (com.huijy.common.utils.StringUtils.isNotNull(pageNum) && com.huijy.common.utils.StringUtils.isNotNull(pageSize))
		{
			String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
			PageHelper.startPage(pageNum, pageSize, orderBy);
		}
	}

	/**
	 * 设置请求排序数据
	 */
	protected void startOrderBy()
	{
		PageDomain pageDomain = TableSupport.buildPageRequest();
		if (com.huijy.common.utils.StringUtils.isNotEmpty(pageDomain.getOrderBy()))
		{
			String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
			PageHelper.orderBy(orderBy);
		}
	}

	/**
	 * 响应请求分页数据
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	protected TableDataInfo getDataTable(List<?> list)
	{
		TableDataInfo rspData = new TableDataInfo();
		rspData.setCode(HttpStatus.SUCCESS);
		rspData.setMsg("查询成功");
		rspData.setRows(list);
		rspData.setTotal(new PageInfo(list).getTotal());
		rspData.setPages(new PageInfo(list).getPages());
		return rspData;
	}

}
