package com.iformall.controller.base;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.iformall.domain.po.MallUserInfo;
import com.iformall.domain.po.base.TenantEntity;
import com.iformall.shiro.UserSession;
import com.iformall.utils.IPUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@RestController
public class BaseController {

	@InitBinder
	public void InitBinder(WebDataBinder dataBinder) {
		dataBinder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
			public void setAsText(String value) {
				try {
					setValue(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(value));
				} catch(ParseException e) {
					try {
						setValue(new SimpleDateFormat("yyyy-MM-dd ").parse(value));
					} catch (ParseException e1) {
						setValue(null);
					}
				}
			}

			public String getAsText() {
				return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((Date) getValue());
			}

		});
	}
	public MallUserInfo getUser(){
		MallUserInfo user = (MallUserInfo) SecurityUtils.getSubject().getSession().getAttribute(UserSession.userInfo);
		return user;
	}

    public Long getUserId(){
        Long userId = (Long) SecurityUtils.getSubject().getSession().getAttribute(UserSession.userId);
        return userId;
    }
	
    @Deprecated
	public String getTenantId(){
		String tenantId = (String)SecurityUtils.getSubject().getSession().getAttribute(UserSession.tenantId);
		return tenantId;
	}

	/**
	 * 返回租户信息
	 * @return
	 */
	public TenantEntity getTenantInfo(){
		Session session = SecurityUtils.getSubject().getSession();
		String tenantId = (String)session.getAttribute(UserSession.tenantId);

		TenantEntity tenantEntity = new TenantEntity(){{
			setTenantId(tenantId);
		}};
		return tenantEntity;
	}

	public String getIpAddr() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		String ipaddress = IPUtil.getIpAddr(request);
		return ipaddress;
	}
}
