package com.fs.app.controller;


import com.fs.app.utils.JwtUtils;
import com.fs.common.constant.HttpStatus;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.page.PageDomain;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.core.page.TableSupport;
import com.fs.common.core.redis.RedisCache;
import com.fs.common.exception.CustomException;
import com.fs.common.utils.ServletUtils;
import com.fs.common.utils.StringUtils;
import com.fs.common.utils.sql.SqlUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;


public class AppBaseController {
	@Autowired
	JwtUtils jwtUtils;
	@Autowired
	RedisCache redisCache;

	public String getUserId()
	{
		String headValue =  ServletUtils.getRequest().getHeader("APPToken");
		if (StringUtils.isNotEmpty(headValue)){
			Claims claims=jwtUtils.getClaimByToken(headValue);
			if(claims!=null){
				String userId = claims.getSubject().toString();
				return userId;
			}
			else{
				return "";
			}
		}
		return "";
	}
	public Long getCompanyUserId( )
	{
		Long companyUesrId=redisCache.getCacheObject("company-user-token:"+ ServletUtils.getRequest().getHeader("companyUserToken"));
		if(companyUesrId== null){
			throw  new CustomException("未登录",403);
		}
		return companyUesrId;
	}

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

	/**
	 * 响应请求分页数据
	 */
	@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());
		return rspData;
	}

	/**
	 * 响应返回结果
	 *
	 * @param rows 影响行数
	 * @return 操作结果
	 */
	protected AjaxResult toAjax(int rows)
	{
		return rows > 0 ? AjaxResult.success() : AjaxResult.error();
	}

	/**
	 * 响应返回结果
	 *
	 * @param result 结果
	 * @return 操作结果
	 */
	protected AjaxResult toAjax(boolean result)
	{
		return result ? success() : error();
	}

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

	/**
	 * 返回失败消息
	 */
	public AjaxResult error()
	{
		return AjaxResult.error();
	}

}
