package cn.com.countrygarden.bi.main.controller;

import cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.model.AccessToken;
import cn.com.countrygarden.bi.main.service.AccessTokenService;
import cn.com.countrygarden.bi.main.service.RoleService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * package: cn.com.countrygarden.bi.main.controller
 * describe: 基础控制层实现
 * creat_user: lsl
 * creat_date: 2018/6/9
 * creat_time: 1:04
 **/
public abstract class BaseController {

    protected Logger logger= LoggerFactory.getLogger(getClass());

    protected final Result ERROR_MSG = Response.responseFail("操作失败,请稍后重试！");
    protected final Result SUCCESS_MSG = Response.response();

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HttpServletResponse response;
    @Autowired
    private AccessTokenService accessTokenService;
    @Autowired
    private RoleService roleService;


    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, new CustomDateEditor(
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true));
        binder.registerCustomEditor(Date.class, new CustomDateEditor(
                new SimpleDateFormat("yyyy-MM-dd HH:mm"), true));
        binder.registerCustomEditor(Date.class, new CustomDateEditor(
                new SimpleDateFormat("yyyy-MM-dd"), true));
        binder.registerCustomEditor(Date.class, new CustomDateEditor(
                new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"), true));
        binder.registerCustomEditor(Date.class, new CustomDateEditor(
                new SimpleDateFormat("yyyy/MM/dd HH:mm"), true));
    }

    @Deprecated
    public AccessToken getAccessToken(HttpServletRequest request){
        //        根据授权获取用户信息
        String accessToken = request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);
        return token;
    }

    /**
     * 获取授权信息
     * @return
     */
    public AccessToken getAccessToken(){
//      根据授权获取用户信息
        String accessToken = this.request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);
        return token;
    }

    /**
     * 当前登录用户是否存在角色
     * @param roleCode
     * @return
     */
    public boolean hasRole(String roleCode){
        String userCode = getAccessToken().getUserCode();
        return roleService.isExistRoleCode(roleCode,userCode);
    }

    /**
     * @category 判断浏览器.
     * @author www.justintoForest@Gamil.com
     * @since 2017-06-09 下午 04:26
     */
    protected boolean isIE() {
        return this.request.getHeader("USER-AGENT").toLowerCase().indexOf("msie") > 0 || request.getHeader("USER-AGENT").toLowerCase().indexOf("rv:11.0") > 0 || request.getHeader("USER-AGENT").toLowerCase().indexOf("edge") > 0;
    }


    /**
     * 判断User-Agent 是不是来自于手机
     * @param ua
     * @return
     */
    protected boolean checkAgentIsMobile(String ua) {
        String[] agent = { "Android", "iPhone", "iPod","iPad", "Windows Phone", "MQQBrowser" };
        boolean flag = false;
        if (!ua.contains("Windows NT") || (ua.contains("Windows NT") && ua.contains("compatible; MSIE 9.0;"))) {
// 排除 苹果桌面系统
            if (!ua.contains("Windows NT") && !ua.contains("Macintosh")) {
                for (String item : agent) {
                    if (ua.contains(item)) {
                        flag = true;
                        break;
                    }
                }
            }
        }
        return flag;
    }

    /**
     * 获取客户端ip
     * @return
     */
    public String getRemoteHost(){
        String ip = this.request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = this.request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = this.request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = this.request.getRemoteAddr();
        }
        return "0:0:0:0:0:0:0:1".equals(ip)?"127.0.0.1":ip;
    }



    /**
     * 获取指定的Cookie对象
     * @param key
     * @return
     */
    public Cookie getCookie(String key){
        Cookie[] cookie = this.request.getCookies();
        if(cookie==null){
            return null;
        }
        for (int i = 0; i < cookie.length; i++) {
            Cookie cook = cookie[i];
            if(cook.getName().equalsIgnoreCase(key)){ //获取键
                return cook;
            }
        }
        return null;
    }

    /**
     * 输出信息到页面
     */
    public void printOutMsg(String msg){
        try {
            this.response.setCharacterEncoding("UTF-8");
            this.response.setContentType("text/html;charset=utf-8");
            PrintWriter out = null;
            out = this.response.getWriter();
            out.print(msg);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出excel文件
     * @param workbook
     */
    protected void downloadExcelData(Workbook workbook, String excelName) {
        if(workbook instanceof HSSFWorkbook) {
            excelName = excelName + ".xls";
        } else {
            excelName = excelName + ".xlsx";
        }
        try {
            if(isIE()) {
                excelName = URLEncoder.encode(excelName, "UTF8");
            } else {
                excelName = new String(excelName.getBytes("UTF-8"), "ISO-8859-1");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new ServiceException("文件名URl转码异常！" );
        }
        response.setHeader("content-disposition", "attachment;filename=" + excelName);
        try {
            ServletOutputStream out = response.getOutputStream();
            workbook.write(out);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
            throw new ServiceException("文件导出异常！" );
        }
    }


}
