package cn.myapps.runtime.dynaform.form;

import cn.myapps.authtime.common.dao.PersistenceUtils;
import cn.myapps.authtime.common.service.AuthTimeServiceManager;
import cn.myapps.authtime.domain.model.DomainVO;
import cn.myapps.authtime.domain.service.DomainProcess;
import cn.myapps.base.web.WebUser;
import cn.myapps.common.Environment;
import cn.myapps.common.data.ParamsTable;
import cn.myapps.common.util.Security;
import cn.myapps.designtime.common.service.DesignTimeServiceManager;
import cn.myapps.designtime.form.service.FormDesignTimeService;
import cn.myapps.runtime.dynaform.document.ejb.Document;
import cn.myapps.runtime.dynaform.form.ejb.Form;
import cn.myapps.runtime.dynaform.form.ejb.QRCodeField;
import cn.myapps.runtime.dynaform.form.ejb.ValidateMessage;
import cn.myapps.runtime.macro.runner.IRunner;
import cn.myapps.runtime.macro.runner.JavaScriptFactory;
import cn.myapps.support.weixin.WeixinServiceProxy;
import cn.myapps.util.CreateProcessException;
import cn.myapps.util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;

/**
 * @author Happy
 *
 */
public class QRCodeFiledScanEventReadyServlet extends HttpServlet {

	/**
	 *
	 */
	private static final long serialVersionUID = -5644106523329927589L;
	/**
	 * 微OA365反向代理模式外网访问地址
	 */
	private static final String weioa365_addr = "https://yun.weioa365.com/{site_id}";


	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		String domainId = req.getParameter("domainId");
		String formId = req.getParameter("formId");
		String docId = req.getParameter("docId");
		String fieldId = req.getParameter("fieldId");
		String applicationId = req.getParameter("applicationId");
		String _randomCode = req.getParameter("_randomCode");
		String accessToken = Security.getTokenFromRequest(req); //WebUser.getTokenByCookie(req, Security.ACCESS_TOKEN);
		if(StringUtil.isBlank(accessToken)){
			accessToken = req.getParameter("access_token");
		}

		try {
			DomainProcess domainProcess = AuthTimeServiceManager.domainRuntimeService();
			FormDesignTimeService formService = DesignTimeServiceManager.formDesignTimeService();

			if(isFromWeixin(req)){//通过微信客户端访问

				DomainVO domain =  (DomainVO) domainProcess.doView(domainId);
				Form form = (Form) formService.doView(formId);
				QRCodeField qrcodeField = (QRCodeField) form.findField(fieldId);

				String redirect = null;//跳转地址
				if(QRCodeField.HANDLE_TYPE_LINK.equals(qrcodeField.getHandleType())){//跳转到表单

					if(DomainVO.WEIXIN_PROXY_TYPE_LOCAL.equals(domain.getWeixinProxyType()) || DomainVO.WEIXIN_PROXY_TYPE_ENTERPRISE_WECHAT.equals(domain.getWeixinProxyType())){//本地绑定模式
						redirect = domain.getServerHost()+"/mobile/index.html?application="+applicationId+"#/open?linkType=00&actionContent="+formId;

					}else if(DomainVO.WEIXIN_PROXY_TYPE_CLOUD.equals(domain.getWeixinProxyType())){//云端代理模式
						redirect = weioa365_addr.replace("{site_id}", Environment.getMACAddress())+"/portal/phone/main.jsp?application="+applicationId+"&jumpToUrl="+Environment.getInstance().getContextPath()+"/portal/dynaform/document/view.action?_formid="+formId+"&_docid="+docId+"&application="+applicationId+"&openType=from_weixin_message&_backURL="+Environment.getInstance().getContextPath()+"/portal/index.html";
					}

				}else if(QRCodeField.HANDLE_TYPE_CALLBACK_EVENT.equals(qrcodeField.getHandleType())){//执行扫码回调事件

					if(DomainVO.WEIXIN_PROXY_TYPE_LOCAL.equals(domain.getWeixinProxyType()) || DomainVO.WEIXIN_PROXY_TYPE_ENTERPRISE_WECHAT.equals(domain.getWeixinProxyType())){//本地绑定模式
						redirect = domain.getServerHost()+"/portal/document/qrcodefield/handle?action=excute&domainId="+domain.getId()+"&formId="+formId+"&formId="+formId+"&docId="+docId+"&fieldId="+fieldId+"&applicationId="+applicationId+"&application="+applicationId+"&_randomCode="+_randomCode;
					}else if(DomainVO.WEIXIN_PROXY_TYPE_CLOUD.equals(domain.getWeixinProxyType())){//云端代理模式
						redirect = weioa365_addr.replace("{site_id}", Environment.getMACAddress())+"/portal/document/qrcodefield/handle?action=excute&domainId="+domain.getId()+"&formId="+formId+"&formId="+formId+"&docId="+docId+"&fieldId="+fieldId+"&applicationId="+applicationId+"&_randomCode="+_randomCode;
					}

				}
				redirect = URLEncoder.encode(redirect, "utf-8");
				String redirect_uri = null;
				if(QRCodeField.HANDLE_TYPE_LINK.equals(qrcodeField.getHandleType())){
					redirect_uri = redirect;
				} else if(QRCodeField.HANDLE_TYPE_CALLBACK_EVENT.equals(qrcodeField.getHandleType())){
					if(DomainVO.WEIXIN_PROXY_TYPE_LOCAL.equals(domain.getWeixinProxyType()) || DomainVO.WEIXIN_PROXY_TYPE_ENTERPRISE_WECHAT.equals(domain.getWeixinProxyType())){//本地绑定模式
						redirect_uri = domain.getServerHost()+"/mobile/index.html?#/qrcodeCallback";
					}else if(DomainVO.WEIXIN_PROXY_TYPE_CLOUD.equals(domain.getWeixinProxyType())){//云端代理模式
						redirect_uri = weioa365_addr.replace("{site_id}", Environment.getMACAddress())+"/portal/phone/resource/component/qrcodeFiled/callback-confirm.jsp";
					}
					IRunner runner = JavaScriptFactory.getInstance("", applicationId);
					runner.initBSFManager(new Document(), new ParamsTable(), new WebUser(), new ArrayList<ValidateMessage>());
					redirect_uri += "?application="+applicationId+"&redirect=" + redirect + "&title=" + qrcodeField.getName() + "&discript=" + qrcodeField.getDiscript(runner);
					redirect_uri = URLEncoder.encode(redirect_uri,"utf-8");
				}
				String url = getWeiXinOAuthUrl(domain,redirect_uri);
				resp.sendRedirect(url);
				return;
			} else if(isFromDingDing(req)) {
				DomainVO domain =  (DomainVO) domainProcess.doView(domainId);
				String dingdingCorpId = domain.getDingdingCorpID();
				String dingdingUrl = "/static/dingding.html?domainid="+domain.getId()+"&corpid="+dingdingCorpId+"&appid="+applicationId+"&actionContent="+formId+"&docid="+docId+"&formid="+formId;
				resp.sendRedirect(dingdingUrl);
				return;
			} else {
				Form form = formService.doView(formId);
				QRCodeField qrcodeField = (QRCodeField) form.findField(fieldId);

				String redirect = null;//跳转地址
				if(QRCodeField.HANDLE_TYPE_LINK.equals(qrcodeField.getHandleType())){//跳转到表单
					redirect = "/static/mobile/index.html?application="+applicationId+"#/open?linkType=00&actionContent="+formId+"&docid="+docId+"&accessToken="+accessToken;
				}else if(QRCodeField.HANDLE_TYPE_CALLBACK_EVENT.equals(qrcodeField.getHandleType())){//执行扫码回调事件
					redirect = req.getContextPath()+"/portal/document/qrcodefield/handle?action=excute&domainId="+domainId+"&formId="+formId+"&formId="+formId+"&docId="+docId+"&fieldId="+fieldId+"&applicationId="+applicationId+"&application="+applicationId+"&_randomCode="+_randomCode+"&accessToken="+accessToken;
				}
				resp.sendRedirect(redirect);
				return;
			}
		} catch (CreateProcessException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				PersistenceUtils.closeSessionAndConnection();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}




	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		super.doPost(req, resp);
	}

	/**
	 * 获取微信OAuth2用户认证url
	 * @return
	 */
	@SuppressWarnings("static-access")
	private String getWeiXinOAuthUrl(DomainVO domain ,String redirect_uri){
		StringBuilder url = new StringBuilder();

		if(DomainVO.WEIXIN_PROXY_TYPE_LOCAL.equals(domain.getWeixinProxyType()) || DomainVO.WEIXIN_PROXY_TYPE_ENTERPRISE_WECHAT.equals(domain.getWeixinProxyType())){//本地绑定模式
			url.append("https://open.weixin.qq.com/connect/oauth2/authorize?appid=")
					.append(domain.getWeixinCorpID())
					.append("&redirect_uri=").append(redirect_uri)
					.append("&response_type=code&scope=snsapi_base&state=").append(domain.getId())
					.append("#wechat_redirect");

		}else if(DomainVO.WEIXIN_PROXY_TYPE_CLOUD.equals(domain.getWeixinProxyType())){//云端代理模式
			String corpId = null;
			try {
				corpId = WeixinServiceProxy.getCorpId(Environment.getInstance().getMACAddress(), domain.getId());
			} catch (Exception e) {
				e.printStackTrace();
			}
			url.append("https://open.weixin.qq.com/connect/oauth2/authorize?appid=")
					.append(corpId)
					.append("&redirect_uri=").append(redirect_uri)
					.append("&response_type=code&scope=snsapi_base&state=").append(domain.getId())
					.append("#wechat_redirect");
		}
		return url.toString();
	}

	/**
	 * 是否来自微信
	 * @param request
	 * @return
	 */
	private boolean isFromWeixin(HttpServletRequest request) {
//        HttpServletRequest request = this.request;
		String userAgent = request.getHeader("user-agent");
		if(userAgent.contains("MicroMessenger")) return true;
		return false;
	}

	/**
	 * 是否来自钉钉
	 * @param request
	 * @return
	 */
	private boolean isFromDingDing(HttpServletRequest request) {
//        HttpServletRequest request = this.request;
		String userAgent = request.getHeader("user-agent");
		if(userAgent.contains("DingTalk")) return true;
		return false;
	}

}
