package com.kingdee.customer.Auth.handler;

import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Base64;
import com.aliyun.odps.utils.StringUtils;
import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.eas.cp.eip.sso.util.CloudParamUtil;
import com.kingdee.eas.util.app.DbUtil;
import com.kingdee.jdbc.rowset.IRowSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class TestServlet extends HttpServlet {

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

    public TestServlet() {
        super();
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        logger.error("into TestServlet.doGet");
        //标准版流程助手
        String url = "http://bos.kingdee.com/workflow/main.html?";
        String wfversion = request.getParameter("wfversion");
        String storeEid = request.getParameter("storeEid");
        //移动bos版本流程助手，客户有使用移动bos可使用这个版本
        //if("mbos".equals(wfversion)){

        /**
         * https://mbos.kdeascloud.com/mbos/page/loadPage?
         * path=cmpSubmit88sp1&name=submitbill.editui
         * &lczstype=list&cometype=havedo&billID=SPKUhmbQSQifgjFU2ESznbEdulw%3D
         * &assignId=22910d25-d1b4-425c-9e87-eaa287f438b6WFWKITEM
         * &fprocinstid=653327bb-c464-4472-aa8d-c60b35000674WFPCINST
         * &operateState=VIEW&lczsapprove=9444be02b9d40929508ff587f216a64e&canChangeLanguage=1
         * &eid=ww434cb2a638701cdd&appid=10036
         *
         * https://mbos.kdeascloud.com/mbos/page/loadPage?storeEid=21231
         * &path=lczs2&name=approveui.navui
         *
         * &eid=ww434cb2a638701cdd&appid=10036
         * &token=ZmVuZy5jaGVu
         *
         *
         *
         * &cometype=todo&assignId=22910d25-d1b4-425c-9e87-eaa287f438b6WFWKITEM
         *
         *
         */

        /**
         * https://mbos.kdeascloud.com/mbos/page/loadPage?
         *          * path=cmpSubmit88sp1&name=submitbill.editui
         *          * &lczstype=list&cometype=havedo&billID=SPKUhmbQSQifgjFU2ESznbEdulw%3D
         *          * &assignId=22910d25-d1b4-425c-9e87-eaa287f438b6WFWKITEM
         *          * &fprocinstid=653327bb-c464-4472-aa8d-c60b35000674WFPCINST
         *          * &operateState=VIEW&lczsapprove=9444be02b9d40929508ff587f216a64e&canChangeLanguage=1
         *
         *
         */

        //url = "https://mbos.kdeascloud.com/mbos/page/loadPage?storeEid=21231&path=lczs2&name=approveui.navui";


        //TODO:加入的代码拼接跳转的参数
        String assignmentId = "";
        HttpSession session = request.getSession();
        if (session != null) {
            Map<String, String> assignmentMap = (Map) session.getAttribute("assignment");
            if (assignmentMap != null && assignmentMap.size() > 0) {
                assignmentId = assignmentMap.get("assignmentId");
                logger.info("onSuccessfulValidation......assignmentId：" + assignmentId);
            }
        }
        String billId = "";
        String fprocinstid = "";
        try {
            Map<String,String> paramMap = getParamMapByAssignId(assignmentId);
            billId = paramMap.get("billId");
            fprocinstid = paramMap.get("fprocinstid");
        } catch (BOSException e) {
            logger.error("TestServlet.doGet" + e.getMessage());
            throw new ServletException(e.getMessage());
        }

        url = "https://mbos.kdeascloud.com/mbos/page/loadPage?path=cmpSubmit88sp1&name=submitbill.editui&lczstype=list&billID="+billId+"&fprocinstid="+fprocinstid+"&operateState=VIEW&lczsapprove=9444be02b9d40929508ff587f216a64e&canChangeLanguage=1";
        if (storeEid != null && !"".equals(storeEid) && !"null".equals(storeEid)) {
            url = url.replace("storeEid=21231", "storeEid=" + storeEid);
        }
        //}

        Map<String, String> infoMap = encryptUserInfo(request);

        Set<String> keySet = infoMap.keySet();
        for (String key : keySet) {
            url += "&" + key + "=" + infoMap.get(key);
        }
        url = url.replace("?&", "?");


        url += "&cometype=havedo&assignId=" + assignmentId;
        logger.info("OtherAppPortalServlet.doget.url:" + url);
        response.sendRedirect(url);
    }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }


    /**
     * accessurl
     * 如果第三方app点击链接带token，这方法可以不写，将流程助手主页作为应用url，getLoginInfoByToken中根据第三方app的token解析到用户信息即可
     * 如果第三方app点击链接不带token，将此接口作为应用的url,方法内获取第三方app用户对应的eas用户信息，方法返回值resultMap存跳转到流程助手的参数
     * http://localhost:8080/otherapp/index?eid=21231&appid=10036&param=zhangsan
     */
    public Map<String, String> encryptUserInfo(HttpServletRequest request) {
        HashMap<String, String> resultMap = new HashMap<String, String>();
        String param = request.getParameter("param");
        //下面三个参数为跳转流程助手主页参数
        String eid = request.getParameter("eid");
        String appid = request.getParameter("appid");
        String token = "";
        //........根据第三方app传来的参数，取到eas用户信息
        try {
            token = encrypt_Base64(param);
        } catch (Exception e) {
            logger.error("encryptUserInfo encrypt_Base64 Exception" + e.getMessage());
            e.printStackTrace();
        }
        logger.info("encryptUserInfo.token:"+token);
        resultMap.put("eid", eid);
        resultMap.put("appid", appid == null ? "10036" : appid);
        resultMap.put("token", token);
        return resultMap;
    }

    /***
     * Base64加密
     * @param str 需要加密的参数
     * @return
     * @throws Exception
     */
    private static String encrypt_Base64(String str) throws Exception {
        if(StringUtils.isEmpty(str)){
            return "";
        }
        String result = Base64.getEncoder().encodeToString(str.getBytes("UTF-8"));
        return result;
    }


    /**
     * 通过assignId 查询出billId 和fprocinstId
     * @param assignId
     * @return
     */
    private  Map<String,String> getParamMapByAssignId(String assignId) throws BOSException {
        Map<String,String> paramMap = new HashMap<String,String>();
        String dataCenter=ConfigAddressServletUtil.getProperty("dataCenter");
        String locale=ConfigAddressServletUtil.getProperty("locale");
        Context ctx = CloudParamUtil.getContext(dataCenter, locale, "administrator");
        String sql = "select fbizobjid as billId,fprocinstid from t_wfr_assign where fassignid = '"+assignId+"'";
        String billId = "";
        String fprocinstid = "";
        try {
            IRowSet result = DbUtil.executeQuery(ctx, sql);
            while (result.next()) {
                billId = result.getString("billId");
                fprocinstid = result.getString("fprocinstid");
                paramMap.put("billId",billId);
                paramMap.put("fprocinstid",fprocinstid);
            }
        } catch (SQLException e) {
            throw new BOSException(e);
        }
        return paramMap;
    }



}
