package com.customer.controller;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.kingdee.bos.ctrl.swing.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;


/**
 * 此Servlet用于流程助手调用，解析流程助手的token，返回eas的用户信息
 */
//api请求路径
public class TokenAuthServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private final Logger logger = LoggerFactory.getLogger(TokenAuthServlet.class);

    public TokenAuthServlet() {
        super();
    }

    /**
     *  token的处理逻辑，请根据第三方app的实际业务需求实现
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        logger.info("into.TokenAuthServlet.doGet");
        String token = request.getParameter("token");
        logger.info("into.TokenAuthServlet.doGet.token:"+token);
        String appid = request.getParameter("appid");
        logger.info("into.TokenAuthServlet.doGet.appid:"+appid);
        String secret = request.getParameter("secret");
        logger.info("into.TokenAuthServlet.doGet.secret:"+secret);
        Map<String, String> result = null;
        try {
            result = getLoginInfoByToken(token, appid, secret);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("getLoginInfoByToken异常："+e.getMessage());
            throw new ServletException();
        }
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
        response.getWriter().write(JSON.toJSONString(result));
    }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }


    /**
     * tokenurl
     * 根据token解析出要登陆eas的用户信息
     * http://localhost:8080/otherapp/token?token=emhhbnNhbg==
     */
    public Map<String, String> getLoginInfoByToken(String token, String appid, String secret) throws Exception {
        HashMap<String, String> resultMap = new HashMap<String, String>();
        logger.info("getLoginInfoByToken.token="+token);
        String userNumber = "";
        try {
            //Base64解密
            userNumber = decrypt_Base64(token);
        } catch (Exception e) {
            logger.error("encryptUserInfo encrypt_Base64 Exception："+e.getMessage());
            e.printStackTrace();
            throw new Exception("AD域解密失败："+ e.getMessage());
        }
        logger.info("getLoginInfoByToken.userNumber="+userNumber);
        //.........根据流程助手传来的token参数，获取eas用户信息逻辑
        resultMap.put("status", "0");
        resultMap.put("message", userNumber);

        return resultMap;
    }

    /***
     * Base64解密
     * @param str 需要解密的参数
     * @return
     * @throws Exception
     */
    private  String decrypt_Base64(String str) throws Exception {
        logger.info("decrypt_Base64.str="+str);
        if(StringUtils.isEmpty(str)){
            return "";
        }
        String sDecode = URLDecoder.decode(str,"UTF-8");
        logger.info("decrypt_Base64.sDecode="+sDecode);
        byte[] asBytes = Base64.getDecoder().decode(sDecode);
        String result = new String(asBytes,"UTF-8");
        return result;
    }

    /**
     * 登录获取设备类型
     * @param requestHeader
     * @return
     */
    private int getDeviceType(String requestHeader){
        if (requestHeader.indexOf("Android") != -1) {
            //安卓
            return 1;
        } else if ((requestHeader.indexOf("iPhone") != -1) || (requestHeader.indexOf("iPad") != -1)) {
            //苹果
            return 2;
        } else {
            //电脑
            return 3;
        }

    }


    public final void getKK(String requestHeader){
        int type = getDeviceType(requestHeader);
        if(type == 1 ||type == 2) {

        }
    }


}
