package com.sino.rescue.oauth.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
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.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sino.publicclass.base.CException;
import com.sino.publicclass.database.ConnectionPool;
import com.sino.rescue.oauth.entity.SNSUserInfo;
import com.sino.rescue.oauth.entity.WeixinOauth2Token;
import com.sino.rrs.business.SnsVehicleUserManager;
import com.sino.rrs.entity.RcWeixinUserPO;
import com.sino.rrs.oper.RcWeixinUserOper;
import com.sino.rrs.oper.UserOrderOper;
import com.sino.weixin.oauth.util.AdvancedUtil;
import com.sino.weixin.oauth.util.Constants;
import com.sino.weixin.oauth.util.HttpsUtil;

//当前工单
public class CurrentOrderServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private AdvancedUtil util=new AdvancedUtil();
	
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		response.setCharacterEncoding("gb2312");  // 用户同意授权后，能获取到code
		  String code=request.getParameter("code");
		  if (!"authdeny".equals(code)) {
			   // 获取网页授权access_token
			   WeixinOauth2Token weixinOauth2Token = util.getOauth2AccessToken(Constants.AppId, Constants.AppSecret, code);
			   // 网页授权接口访问凭证
			   String accessToken = weixinOauth2Token.getAccess_token();
			   // 用户标识
			   String openId = weixinOauth2Token.getOpenid();
			
			   RcWeixinUserPO weixinUser=SnsVehicleUserManager.getWeixinDispatcherUserByOpenId(openId);
			   if(weixinUser!=null){
				   request.setAttribute("weixinUserId", String.valueOf(weixinUser.getId()));
				   System.out.println(String.valueOf(weixinUser.getId())+"ooooooooooooooooo");
				   Connection conn=null;
				   JSONObject json=new JSONObject();
				   try {
					 conn=ConnectionPool.getConnection();
					 RcWeixinUserOper weixinOper=new RcWeixinUserOper(conn);
					 UserOrderOper orderOper=new UserOrderOper(conn);
					 
					 Map<String,Object> regist=weixinOper.findUserByOpenID(openId);
						if(!regist.get("company_rescue_code").equals("")){  //服务商注册过
							int dispatchMode=(Integer) regist.get("company_dispatch_mode");
							if(dispatchMode==3){   //微信调度
								String rescueCode=(String) regist.get("company_rescue_code");
								
								List<String> orderList = orderOper.findOrderListByRescueCode(rescueCode);
								json.put("orderList", orderList);
								json.put("rescueCode", rescueCode);
								json.put("action", 10);
								
								if(orderList!=null&&orderList.size()>0){
									JSONObject list=JSON.parseObject(HttpsUtil.doPost(Constants.url, json, "utf-8"));  //远程调用查询当前订单
									request.setAttribute("list", list.get("currentOrderList"));
									request.getRequestDispatcher("/supplier/currentOrder.jsp?rescueCode="+rescueCode+"&openId="+openId).forward(request, response); 
								}else{
									request.setAttribute("list", "");
									request.getRequestDispatcher("/supplier/currentOrder.jsp?rescueCode="+rescueCode+"&openId="+openId).forward(request, response); 
								}
							}else{   //其它调度
								request.getRequestDispatcher("/supplier/power.jsp").forward(request, response); //权限页面
							}
							
						}else if(!regist.get("vehicle_rescue_code").equals("")){   //司机注册过
							int dispatchMode=(Integer) regist.get("vehicle_dispatch_mode");
							if(dispatchMode==3){    //微信调度
								String rescueCode=(String) regist.get("vehicle_rescue_code");
								int vehicleId=(Integer) regist.get("ID");  //师傅id
								Map<String,String> vehicleOrders= orderOper.findVehicleOrderDetailByVehicleId(vehicleId); //查询司机当前订单
								if(vehicleOrders!=null&&vehicleOrders.size()>0){
									request.setAttribute("list",vehicleOrders);
								}else{
									request.setAttribute("list",""); 
								}
									request.getRequestDispatcher("/supplier/vehicleCurrentOrder.jsp?rescueCode="+rescueCode+"&openId="+openId+"&rescueVehicleId="+vehicleId).forward(request, response);	
							}else{  //其它调度
								request.getRequestDispatcher("/supplier/power.jsp").forward(request, response); //权限页面
							}
							
						}else{
								 request.getRequestDispatcher("/supplier/userRegister.jsp?weixinUserId="+String.valueOf(weixinUser.getId())).forward(request, response);
							}
				   }catch (CException e) {
						e.printStackTrace();
					} catch (Exception e) {
					e.printStackTrace();
				}finally{
						try {
							conn.close();
						} catch (SQLException e) {
							e.printStackTrace();
						}
					}
			   }else{
				// 获取用户信息
				   Connection conn=null;
				   try {
					   conn=ConnectionPool.getConnection();
					   SNSUserInfo snsUserInfo = util.getSNSUserInfo(accessToken, openId); // 设置要传递的参数
					   
					   RcWeixinUserPO snsUser = new RcWeixinUserPO();
					   snsUser.setOpen_id(snsUserInfo.getOpenid());
					   snsUser.setNick_name(snsUserInfo.getNickname());
					   snsUser.setSex(snsUserInfo.getSex());
					   snsUser.setProvince(snsUserInfo.getProvince());
					   snsUser.setCity(snsUserInfo.getCity());
					   snsUser.setCountry(snsUserInfo.getCountry());
					   SnsVehicleUserManager.createWeixinUserDispatch(snsUser);
					   RcWeixinUserOper dispatchOper = new RcWeixinUserOper(conn);
					   int weixinUserId= dispatchOper.findRescueCode(openId).getId();
					   request.setAttribute("weixinUserId", String.valueOf(weixinUserId));
					   request.getRequestDispatcher("/supplier/userRegister.jsp?weixinUserId="+String.valueOf(weixinUserId)).forward(request, response);
				} catch (CException e) {
					e.printStackTrace();
				}finally{
					try {
						conn.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
			   } 
			   
			}
	}
}
