package com.goafanti.common.controller;

import com.goafanti.common.bo.Error;
import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.model.Admin;
import com.goafanti.common.utils.ParamUtils;
import com.goafanti.common.utils.RedisUtil;
import com.goafanti.core.shiro.token.TokenManager;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.core.io.support.ResourcePropertySource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

@Controller
public class BaseController {
	@Resource(name = "errorResource")
	private ResourcePropertySource	errorResource;

	@Value(value = "${static.host}")
	private String					staticHost			= null;

	@Value(value = "${rd.static.host}")
	private String					rdStaticHost			= null;


	@Value(value = "${avatar.host}")
	private String					avatarHost			= null;

	@Value(value = "${portal.host}")
	private String					portalHost			= null;

	@Value(value = "${avatar.upload.host}")
	private String					avatarUploadHost	= null;
	@Autowired
	private RedisUtil redisUtil;

	protected Error buildError(String key) {
		return buildError(key, null);
	}

	protected Error buildError(String key, String message) {
		String msg = (String) errorResource.getProperty(key);
		if (StringUtils.isEmpty(msg)) {
				msg = message;
		}else {
			return new Error(MessageFormat.format( msg, message));
		}
		if (StringUtils.isEmpty(msg)) {
			msg = key;
		}
		return new Error(key, msg);
	}

	/**
	 * 带参数的error message
	 *
	 * @param key
	 * @param message
	 * @param object
	 * @return
	 */
	protected Error buildError(String key, String message, Object... object) {
		String msg = (String) errorResource.getProperty(key);
		if (StringUtils.isEmpty(msg)) {
			msg = message;
		}
		msg = MessageFormat.format(msg, object);
		return new Error(key, msg);
	}

	protected Error buildErrorByMsg(String msg, Object... params) {
		return new Error(MessageFormat.format(msg, params));
	}

	protected String getErrorMessage(String key) {
		Object msg = errorResource.getProperty(key);
		if (msg == null) {
			return key;
		}
		return (String) msg;
	}
	protected Error buildErrorMessageParams(String key,Object... params) {
		String msg = (String) errorResource.getProperty(key);
		return  new Error(MessageFormat.format( msg, params));
	}

	protected Error buildParamError(T t, BindingResult bindingResult) {
		return   buildErrorMessageParams(ParamUtils.getParamMsg(t,bindingResult.getFieldError().getField()),ParamUtils.getParamName(t,bindingResult.getFieldError().getField()));
	}


	@InitBinder
	public void initBinder(WebDataBinder binder) {
		DateFormat dateFormat = new SimpleDateFormat(AFTConstants.YYYYMMDDHHMMSS);
		dateFormat.setLenient(true);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
	}

	@ModelAttribute
	public void prepareModel(HttpServletRequest request, Model model) {
		model.addAttribute("staticDomain", avatarHost);
		model.addAttribute("staticHost", staticHost);
		model.addAttribute("rdStaticHost", rdStaticHost);
		model.addAttribute("avatarHost", avatarHost);
		model.addAttribute("avatarUploadHost", avatarUploadHost);
		model.addAttribute("portalHost", portalHost);
		model.addAttribute("basePath", request.getContextPath());
		model.addAttribute("isLogin", TokenManager.isLogin());
		model.addAttribute("csrf", TokenManager.getCSRF());
		model.addAttribute("shiro", SecurityUtils.getSubject());
		model.addAttribute("isAdmin", false);
		if (TokenManager.isLogin() && TokenManager.getToken() instanceof Admin) {
			model.addAttribute("adminData", TokenManager.getAdminToken());
			model.addAttribute("userName", Objects.requireNonNull(TokenManager.getAdminToken()).getName());
			model.addAttribute("departmentId", TokenManager.getAdminToken().getDepartmentId());
			model.addAttribute("isAdmin", true);
			model.addAttribute("shiroList", getshiroList());

		}
	}
	private static String MyShiroList = "MyShiroList:";
	private String getshiroList() {
		String shiroList = redisUtil.getString(MyShiroList+TokenManager.getAdminId());
		if (StringUtils.isBlank(shiroList)){
			shiroList=shiroAddRedis();
		}
		return shiroList;
	}

	/**
	 *	获取权利列表
	 * @return String  返回权限列表 逗号隔开 1=营销员，2=营销经理，3=营销管理员，4=营销总监，5=财务专员，6=财务经理，7=财务管理员，
	 * 					8=技术员，9=技术经理，10=技术管理员,11=运营管理，12=总裁助理，13=总裁,14=董事长助理，15=董事长
	 */
	public String shiroAddRedis() {
		redisUtil.deleteString(MyShiroList+TokenManager.getAdminId());
		StringBuffer str= new StringBuffer();
		if (TokenManager.hasRole(AFTConstants.SALESMAN))str.append(1).append(",");
		if (TokenManager.hasRole(AFTConstants.SALESMAN_MANAGER))str.append(2).append(",");
		if (TokenManager.hasRole(AFTConstants.SALESMAN_ADMIN))str.append(3).append(",");
		if (TokenManager.hasRole(AFTConstants.SALESMAN_DIRECTOR))str.append(4).append(",");
		if (TokenManager.hasRole(AFTConstants.FINANCE))str.append(5).append(",");
		if (TokenManager.hasRole(AFTConstants.FINANCE_MANAGER))str.append(6).append(",");
		if (TokenManager.hasRole(AFTConstants.FINANCE_ADMIN))str.append(7).append(",");
		if (TokenManager.hasRole(AFTConstants.TECH))str.append(8).append(",");
		if (TokenManager.hasRole(AFTConstants.TECH_MANAGER))str.append(9).append(",");
		if (TokenManager.hasRole(AFTConstants.TECH_ADMIN))str.append(10).append(",");
		if (TokenManager.hasRole(AFTConstants.OPERATION_MANAGER))str.append(11).append(",");
		if (TokenManager.hasRole(AFTConstants.CED_ASSISTANT))str.append(12).append(",");
		if (TokenManager.hasRole(AFTConstants.CED))str.append(13).append(",");
		if (TokenManager.hasRole(AFTConstants.APPROVAL_DECISION_ASSISTANT))str.append(14).append(",");
		if (TokenManager.hasRole(AFTConstants.APPROVAL_DECISION))str.append(15).append(",");
		if (TokenManager.hasRole(AFTConstants.TECH_TRANSFER)) str.append(16).append(",");
		if (TokenManager.hasRole(AFTConstants.SUPERADMIN))str.append(99).append(",");

		if (str.length()<1)return "0";
		String shiroList=str.substring(0,str.length()-1);
		redisUtil.setString(MyShiroList+TokenManager.getAdminId(),shiroList);
		return shiroList;
	}

}
