package com.yeejoin.amos.fas.business.controller;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.TransactionSystemException;
import org.typroject.tyboot.core.foundation.context.RequestContext;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.component.feign.config.InnerInvokException;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.fas.core.common.request.CommonRequest;
import com.yeejoin.amos.fas.core.enums.QueryOperatorEnum;
import com.yeejoin.amos.fas.core.util.DaoCriteria;
import com.yeejoin.amos.fas.core.util.StringUtil;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;



/**
 * 基础控制器
 * 
 * @author 
 *
 */
@Deprecated
public abstract class AbstractBaseController extends BaseController {
	
	@Autowired
	protected HttpServletRequest request;
	
	/**
	 * 成功返回状态
	 */
	protected static final String SUCCESS = "SUCCESS";

	/**
	 * 失败返回状态
	 */
	protected static final String FAILED = "FAILED";

	/**
	 * 默认页大小
	 */
	protected static final int DEFAULT_PAGE_SIZE = 10;
	
	 @Autowired
	    private RedisTemplate<String, String> redisTemplate;
	  

	protected String getToken() {
        String authToken = request.getHeader("token");
        if (authToken == null) {
            authToken = request.getHeader("X-Access-Token");
        }
        return authToken;
    }
    
    protected String getProduct() {
        String authToken = request.getHeader("product");
        if (authToken == null) {
            authToken = request.getParameter("product");
        }
        return authToken;
    }

    
    protected String getAppKey() {
        String authToken = request.getHeader("appKey");
        if (authToken == null) {
            authToken = request.getParameter("appKey");
        }
        return authToken;
    }
    
    protected String getChannelType() {
        String channelType = request.getHeader("channelType");
        if (channelType == null) {
        	channelType = request.getParameter("channelType");
        }
        return channelType;
    }
    
    //redi缓存选择的用户信息
    private String buildKey(String userId, String token) {
        //return "region_" + userId + "_" + token.substring(0, token.indexOf('_', 1));
        return "region_" + userId + "_" + token;

    }

    protected void saveSelectedOrgInfo(ReginParams reginParams) {
        redisTemplate.opsForValue().set(buildKey(getUserId(), getToken()), JSONObject.toJSONString(reginParams));
    }

    protected ReginParams getSelectedOrgInfo() {
        return JSON.parseObject(redisTemplate.opsForValue().get(buildKey(getUserId(), getToken())), ReginParams.class);
    }
	
	/**
	 * 
	 * <pre>
	 * 判断当前用户角色级别：true:主管/false:装备管理员
	 * </pre>
	 *
	 * @return
	 */
//	protected boolean isDirector()
//	{
//		if(getUserInfo() == null){
//			return false;
//		}
//		return getUserInfo().getRole().getRoleType() != 3;
//	}
	/**
	 * 获取用户角色id
	 * @return
	 */
	/*protected String getRoleId()
	{
		if(getUserInfo() == null){
			return "";
		}
		return getUserInfo().getRole().getRoleType().toString();
	}*/
	
	/**
	 * 当前登录用户信息
	 */
	 protected AgencyUserModel getUserInfo() {
	    	AgencyUserModel userModel=null;
	    	if(getToken()!=null){
	    	RequestContext.setToken(getToken());
	    	RequestContext.setProduct(getProduct());
	    	RequestContext.setAppKey(getAppKey());
	    	FeignClientResult feignClientResult;
			try {
				feignClientResult = Privilege.agencyUserClient.getme();
		    	 userModel = (AgencyUserModel) feignClientResult.getResult();

			} catch (InnerInvokException e) {
				e.printStackTrace();
			}
			
	    	}
	        return userModel;

	       // return CurrentAuthentication.getAuthenticatedUserThreadLocal();
	    }
	
	protected String getUserId() 
	{
		String userId = null;
		if (getUserInfo() != null)
		{
			userId = getUserInfo().getUserId();
		}
		return userId;
	}
	
	 protected String getCompanyId(ReginParams reginParams) {
	        if (reginParams == null) {
	            return null;
	        }
	        if (reginParams.getCompany() != null) {
	            return reginParams.getCompany().getSequenceNbr().toString();
	        }
	        return null;
	    }
	
	/**
	 * 获取当前用户所属公司名称
	 * @return
	 */
	 protected String getCurrentCompanyNameOfUser() {
			if (getUserInfo() == null) {
				return "";
			}
	return getSelectedOrgInfo().getCompany().getCompanyName();
		}
	
	
	/**
	 * 获取请求的cookies
	 * @return
	 */
	protected HashMap<String,String> getCookInfoMap(){
		HashMap<String,String> map = new HashMap<String,String>();
		Cookie[] cookies = request.getCookies();
		if(cookies!=null){
			for(Cookie ck:cookies){
				map.put(ck.getName(), ck.getValue());
			}
		}
		return map;
	}
	/**
	 * 获取公司orgcode
	 * @return
	 */

	
	 protected String getCompanyName(ReginParams reginParams) {
	        if (reginParams == null) {
	            return null;
	        }
	        if (reginParams.getCompany() != null) {
	            return reginParams.getCompany().getCompanyName();
	        }
	        return null;
	    }
	 protected String getDepartmentId(ReginParams reginParams) {
	        if (reginParams == null) {
	            return null;
	        }
	        if (reginParams.getDepartment() != null) {
	            return reginParams.getDepartment().getSequenceNbr().toString();
	        }
	        return null;
	    }
	
	  protected String getOrgCode(ReginParams reginParams) {
	        if (reginParams == null) {
	            return null;
	        }
//	        if (reginParams.getDepartment() != null) {
//	            return reginParams.getDepartment().getDeptOrgCode();
//	        }
	        if (reginParams.getCompany() != null) {
	            return reginParams.getCompany().getOrgCode();
	        }
	        
	        
	        return null;
	    }

	/**
	 * 生成查询条件
	 * @param queryRequests 前端查询条件
	 * @param flag 是否过滤机构标志 true过滤  false不过滤
	 * @return
	 */
	public List<DaoCriteria> buildDaoCriterias(List<CommonRequest> queryRequests) {
		List<DaoCriteria> daoCriterias = new ArrayList<DaoCriteria>();
		if(queryRequests != null && !queryRequests.isEmpty()){
			for (CommonRequest query : queryRequests) {
				DaoCriteria criteria = new DaoCriteria();
				if(StringUtil.isNotEmpty(query.getValue())){
					criteria.setPropertyName(query.getName());
					String column = criteria.getPropertyName();
					if (!(query.getValue() instanceof Collection<?>) 
							&& column.substring(column.length()-2,column.length()).toUpperCase().equals("ID")) {
						criteria.setValue(Long.valueOf(query.getValue().toString()));
					} else {
						criteria.setValue(query.getValue());
					}
					
					String operator = query.getType();
					if (!StringUtil.isNotEmpty(operator)) {
						criteria.setOperator(QueryOperatorEnum.EQUAL.getName());
					}else if(operator.equals(QueryOperatorEnum.LIKE.getName())){
						setLikeCriteria(criteria,query);
					}else if(operator.equals(QueryOperatorEnum.BIGGER_EQUAL.getName())){
						criteria.setOperator(QueryOperatorEnum.getEnum(operator).getName());
					}else if(operator.equals(QueryOperatorEnum.LESS_EQUAL.getName())){
						criteria.setOperator(QueryOperatorEnum.getEnum(operator).getName());
					}else if(QueryOperatorEnum.getEnum(operator) != null){
						criteria.setOperator(QueryOperatorEnum.getEnum(operator).getName());
					}else {
						criteria.setOperator(operator);
					}
					daoCriterias.add(criteria);
				}
			}	
		}
		return daoCriterias;
	}
	
	/**
	 * 暂时未用到
	 * @return
	 */
	/*public List<DaoCriteria> buildDaoCriteriasNoParam() {
		List<DaoCriteria> daoCriterias = new ArrayList<DaoCriteria>();
		String orgCode = getOrgCode();
		if(isDirector()){
			daoCriterias = buildOrgDaoCriteriaInChildren(daoCriterias,orgCode);
		}else{
			daoCriterias = buildOrgDaoCriteriaOutChildren(daoCriterias,orgCode);
		}
		return daoCriterias;
	}*/
	
	/**
	 * 
	 * <pre>
	 * 生成通过当前用户所属组织机构（包含子机构）过滤的查询条件
	 * </pre>
	 *
	 * @param daoCriterias 查询条件集合
	 * @return
	 */
	public List<DaoCriteria> buildOrgDaoCriteriaInChildren(List<DaoCriteria> daoCriterias,String orgCode) 
	{

		//添加所属公司的过滤条件
		DaoCriteria compDaoCriteria = new DaoCriteria();
		compDaoCriteria.setPropertyName("orgCode");
		compDaoCriteria.setOperator(QueryOperatorEnum.EQUAL.getName());
		compDaoCriteria.setValue(orgCode);
		daoCriterias.add(compDaoCriteria);
		
		
		//添加子公司下的过滤条件
		DaoCriteria childCompDaoCriteria = new DaoCriteria();
		childCompDaoCriteria.setPropertyName("orgCode");
		childCompDaoCriteria.setOperator(QueryOperatorEnum.LIKE.getName());
		childCompDaoCriteria.setValue(orgCode+"*%");
		daoCriterias.add(childCompDaoCriteria);
		return daoCriterias;
	}
	
	/**
	 * 
	 * <pre>
	 * 生成通过当前用户所属组织机构（不包含子机构）过滤的查询条件
	 * </pre>
	 *
	 * @param daoCriterias 查询条件集合
	 * @param orgCode 
	 * @return
	 */
	public List<DaoCriteria> buildOrgDaoCriteriaOutChildren(List<DaoCriteria> daoCriterias, String orgCode) 
	{
		/**
		 * 当前用户所属公司
		 */
		
		DaoCriteria compDaoCriteria = new DaoCriteria();
		compDaoCriteria.setPropertyName("orgCode");
		compDaoCriteria.setOperator(QueryOperatorEnum.EQUAL.getName());
		compDaoCriteria.setValue(orgCode);
		daoCriterias.add(compDaoCriteria);
		return daoCriterias;
	}

	/**
	 * 对like查询语句的内容进行特殊字符转义
	 * @param criteria
	 * @param query
	 */
	@SuppressWarnings("unchecked")
	public void setLikeCriteria(DaoCriteria criteria,CommonRequest query){
		if (query.getValue() instanceof List) {
			List<String> value = (List<String>) query.getValue();
			if (!value.isEmpty()) {
				value = value.stream().map(s -> {
					String str = s.replace("%","/%").replace("_","/_");
					return "%" + str + "%";
				}).collect(Collectors.toList());
				criteria.setValue(value);
				criteria.setOperator(QueryOperatorEnum.LIKE.getName());
			}
		} else {
			String value = (String) query.getValue();
			if(value != null){
				value = value.replace("%","/%").replace("_","/_");
				criteria.setValue("%"+value+"%");
				criteria.setOperator(QueryOperatorEnum.LIKE.getName());
			}
		}
	}
	
	/**
	 * <pre>
	 * 提取错误异常中的错误消息
	 * </pre>
	 * 
	 * <p>
	 * 当实体类中对属相注解了以下类似的注解，需要用try.catch语句捕获异常，使用 #getErrorMessage(Exception)
	 * 提取出异常信息NotNull(message = "属性不能为空！")
	 * </p>
	 * @see {@code NotBlank} ... NotNull、NotEmpty...
	 * @see {@code Valid}
	 * 
	 * @param e
	 * @return
	 */
	public String getErrorMessage(Exception e){
		StringBuilder message = new StringBuilder();
		if(e instanceof TransactionSystemException){
			TransactionSystemException exception = (TransactionSystemException) e;
			if(exception.getRootCause() instanceof ConstraintViolationException) {
				ConstraintViolationException root = (ConstraintViolationException) exception.getRootCause();
				root.getConstraintViolations().forEach(constraintViolation->{message.append(constraintViolation.getMessageTemplate());});
			}else{
				message.append(e.getMessage());
			}
		} else if (e instanceof ConstraintViolationException) {
			((ConstraintViolationException) e).getConstraintViolations().forEach(constraintViolation -> message.append(constraintViolation.getMessageTemplate()));
		} else {
			message.append("操作异常！");
		}
		return message.toString();
	}
}
