package com.yeejoin.amos.boot.biz.common.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.typroject.tyboot.core.foundation.context.RequestContext;

import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.component.feign.config.InnerInvokException;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;

import springfox.documentation.annotations.ApiIgnore;

/**
 * 基础控制器
 *
 * @author
 */
@ApiIgnore
@RestController
@RequestMapping("/base")
public class BaseController {

	@Autowired
	private RedisUtils redisUtils;

	/**
	 * 获取token
	 **/
	protected String getToken() {
		return RequestContext.getToken();
	}

	protected String buildKey(String token) {
		// 由于用户id 不是接口携带参数，为了避免，公共字段填充时频繁访问平台，缓存用户信息时，
		return "region_" + token;

	}

	/**
	 * 用户选择信心redis获取
	 **/
	protected ReginParams getSelectedOrgInfo() {
		return JSONObject.parseObject(redisUtils.get(buildKey(RequestContext.getToken())).toString(),
				ReginParams.class);
	}

	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;
	}

	/**
	 * 当前登录用户信息
	 */
	protected AgencyUserModel getUserInfo() {
		AgencyUserModel userModel = null;
		if (getToken() != null) {
			FeignClientResult<?> feignClientResult;
			try {
				feignClientResult = Privilege.agencyUserClient.getme();
				userModel = (AgencyUserModel) feignClientResult.getResult();

			} catch (InnerInvokException e) {
				throw new RuntimeException(e.getMessage());
			}

		}
		return userModel;

	}
}
