
package com.sino.rrs.action;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sino.publicclass.base.BaseAction;
import com.sino.publicclass.base.CException;
import com.sino.publicclass.database.ConnectionPool;
import com.sino.rrs.business.ChangeOrderMessageDispatch;
import com.sino.rrs.business.RescueVehicleDispatchMessage;
import com.sino.rrs.entity.RcRescueVehiclePO;
import com.sino.rrs.entity.RescueVehicleDispatchPO;
import com.sino.rrs.oper.RcRescueUpdateOper;
import com.sino.rrs.oper.RcRescueVehicleOper;
import com.sino.rrs.oper.RescueVehicleDispatchOper;
import com.sino.rrs.oper.UserOrderOper;
import com.sino.weixin.oauth.util.Constants;
import com.sino.weixin.oauth.util.HttpsUtil;
import com.sino.weixin.oauth.util.ProgressProcess;

public class UpdateOrderStateAction extends BaseAction{
	/**
	 * 查询某个服务商下的司机信息
	 * 根据服务商编号rescueCode
	 * @throws IOException 
	 * @throws SQLException 
	 * @throws CException
	 * @throws Exception
	 */
	public void getVehicles() throws IOException, SQLException{
		Connection conn=null;
		String rescueCode=getParameter("rescueCode", "");
		JSONObject jsonObject=new JSONObject();
		JSONObject json=new JSONObject();
		json.put("rescueCode", rescueCode);
		json.put("action", 13);
		
		List<RcRescueVehiclePO> vehicleList=null;
		try {
			conn=ConnectionPool.getConnection();
			RcRescueVehicleOper vehicleOper=new RcRescueVehicleOper(conn);
			vehicleList = vehicleOper.rescueVehicles(rescueCode);
			//远程查询忙碌车辆
			JSONObject httpRequest=JSON.parseObject(HttpsUtil.doPost(Constants.url, json, "utf-8"));
			List<String> busyVehicleIds= (List<String>) httpRequest.get("busyVehicles");
			
			for(RcRescueVehiclePO po:vehicleList){
				if(busyVehicleIds.contains(String.valueOf(po.getVehicle_id()) )){
				//	System.out.println("可以走到此处===");
					po.setDispatch_flag(7);//设置为忙碌车辆
				}
			}
		} catch (CException e) {
			e.printStackTrace();
		}finally{
			conn.close();
		}
	//	System.out.println("jihe===="+vehicleList.get(0).getDispatch_flag()+vehicleList.get(0).getVehicle_id());
		jsonObject.put("vehicleList",vehicleList);
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().print(jsonObject.toJSONString());
		setNext(false);
	}
	
	/**
	 * 供应商派单到司机
	 * 1.根据id查询师傅对应信息
	 * 2.师傅此时是否忙碌，不忙碌则远程派单
	 * 3.微信系统插入信息
	 * 4.发送模板消息
	 * id  师傅id
	 * @throws CException
	 * @throws Exception
	 */
	public void distributeOrder() throws CException, Exception{
		String rescueCode=getParameter("rescueCode","");
		int id=Integer.parseInt(getParameter("id", ""));  //员工id
		int orderId=Integer.parseInt(getParameter("orderId", ""));
		String orderCode=getParameter("orderCode","");
		String serviceName=getParameter("serviceName","");
		String address=getParameter("address","");

		String dispatchFlag = "0";  //分配失败
		Connection conn =null;
		try {
			conn = ConnectionPool.getConnection();
			RcRescueVehicleOper vehicleOper = new RcRescueVehicleOper(conn);
			RescueVehicleDispatchOper vehiDispatchOper = new RescueVehicleDispatchOper(conn);
			UserOrderOper orderOper=new UserOrderOper(conn);
			JSONObject json=new JSONObject();
			JSONObject httpRequest=null;
			
			Map<String,String> orderMap=orderOper.findOrderDetailByOrderId(orderId);
			if(orderMap!=null){
				int state=Integer.parseInt(orderMap.get("STATE"));
				//判断是否满足分配条件（即user_order state=1 接受状态下）
				if(orderMap.get("rescueCode").equals(rescueCode)){
					if(state==1){
						RcRescueVehiclePO vehiclePO = vehicleOper.findByPrimaryKey(id);
						if (vehiclePO != null) {
							Map<String, String> vehicleService = vehiDispatchOper.vehicleDistributeService(id);
							if (vehicleService == null) {
								json.put("orderId", orderId);
								json.put("vehicleId", vehiclePO.getVehicle_id());  //车辆id
								json.put("staff_name", vehiclePO.getStaff_name());	  //员工编号
								json.put("staff_phone", vehiclePO.getStaff_phone());  //员工电话
								json.put("action", 6);
								
								httpRequest = JSON.parseObject(HttpsUtil.doPost(Constants.url, json, "utf-8"));
								if(httpRequest.getIntValue("errorCode")==0){
									dispatchFlag="1";   //分配成功
									vehiDispatchOper.insertVehicleDispatcher(orderId, id);
									orderOper.updateUserOrderByOrderId(orderId, 7);
									Constants.poolExecutor.execute(new RescueVehicleDispatchMessage(id,orderId,orderCode,serviceName,address));
								}
								
							}
						}
					}else if(state==4){   //订单被撤回
						dispatchFlag="4"; 
					}else if(state==19){   //订单被取消
						dispatchFlag="19";  
					}
				}else{   //订单被改派
					dispatchFlag="5";   //修改救援车，改派服务商
				}
			}	
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			conn.close();
		}
		JSONObject jsonObject=new JSONObject();
		jsonObject.put("code",dispatchFlag);

		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().print(jsonObject.toJSONString());
		setNext(false);
	}

	
	/**
	 * 供应商改派司机
	 * 1.通知上家师傅订单被改派
	 * 2.判断要改派的师傅是否忙碌
	 * 3.系统录入数据
	 * 4.发送模板消息
	 * @throws CException
	 * @throws Exception
	 */
	public void changeDistributeOrder() throws CException, Exception{
		int id=Integer.parseInt(getParameter("id", ""));
		int orderId=Integer.parseInt(getParameter("orderId", ""));
		String orderCode=getParameter("orderCode", "");
		String rescueCode=getParameter("rescueCode");
		String serviceName=getParameter("serviceName","");
		String address=getParameter("address","");
		
		String changeService="1";
		JSONObject json=new JSONObject();
		JSONObject httpRequest=null;
		
		Connection conn=null;
		try {
			conn=ConnectionPool.getConnection();
			RescueVehicleDispatchOper vehiDispatchOper = new RescueVehicleDispatchOper(conn);
			UserOrderOper orderOper=new UserOrderOper(conn);
			RcRescueVehicleOper vehicleOper = new RcRescueVehicleOper(conn);
			
			Map<String,String> orderMap=orderOper.findOrderDetailByOrderId(orderId);
			if(orderMap!=null){
				int state=Integer.parseInt(orderMap.get("STATE"));
				if(orderMap.get("rescueCode").equals(rescueCode)){
					if(state==4){
						changeService="4";
					}else if(state==15){  //订单完成
						changeService="15";
					}else if(state==19){  
						changeService="19";
					}else{
						RescueVehicleDispatchPO  rescueVehiclePO= vehiDispatchOper.changedVehicle(orderId);
						if(rescueVehiclePO!=null){
							int staff_name_id=rescueVehiclePO.getRESCUE_VEHICLE_ID();
							String openId = vehiDispatchOper.getRescueVehicleCode(staff_name_id);
							Constants.poolExecutor.execute(new ChangeOrderMessageDispatch(openId,orderCode,staff_name_id,orderId,rescueCode));
						}
						
						RcRescueVehiclePO vehiclePO = vehicleOper.findByPrimaryKey(id);
						if (vehiclePO != null) {
							Map<String, String> vehicleService = vehiDispatchOper.vehicleDistributeService(id);
							if (vehicleService == null) {
								json.put("orderId", orderId);
								json.put("vehicleId", vehiclePO.getVehicle_id());  //车辆id
								json.put("staff_name", vehiclePO.getStaff_name());  //员工编号
								json.put("staff_phone", vehiclePO.getStaff_phone());
								json.put("action", 6);
								
								httpRequest = JSON.parseObject(HttpsUtil.doPost(Constants.url, json, "utf-8"));
								if(httpRequest.getIntValue("errorCode")==0){
									vehiDispatchOper.updateVehicleDispatcher(orderId,id);
									orderOper.updateUserOrderByOrderId(orderId, 7);
									Constants.poolExecutor.execute(new RescueVehicleDispatchMessage(id,orderId,orderCode,serviceName,address));
								}
								
							}
						}
					}
				}else{
					changeService="5";
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			conn.close();
		}
		JSONObject jsonObject=new JSONObject();
		jsonObject.put("code",changeService);
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().print(jsonObject.toJSONString());
		setNext(false);
	}
	
	/**
	 * 判断此订单是否还存在改师傅名下（没被取消和改派）
	 * 1.查询师傅调度表（订单编号+师傅id）
	 * 2.不存在，查看是否改派
	 * 3.存在，user_order 订单是否取消
	 * 4.否，查看详情；是，提示订单取消
	 * 5.否，则可修改订单状态
	 * @throws IOException 
	 * @throws Exception
	 */
	public void vehicleChanged1() throws IOException{
		int orderID=Integer.parseInt(request.getParameter("orderID"));  //订单id
		String rescueVehicleId=request.getParameter("rescueVehicleId");
		boolean flag=false;
		JSONObject json=new JSONObject();
		
		Connection conn=null;
		try {
			conn=ConnectionPool.getConnection();
			RcRescueUpdateOper updateOper=new RcRescueUpdateOper(conn);
			RescueVehicleDispatchOper vehicleOper=new RescueVehicleDispatchOper(conn);
			UserOrderOper orderOper=new UserOrderOper(conn);
			
			Map<String,String> vehicleMap=vehicleOper.existVehicleByRecueCompany(orderID,rescueVehicleId);
			if(vehicleMap!=null){
				if(vehicleMap.get("rescueVehicleId").equals(rescueVehicleId)){
					Map<String,String> orderMap=orderOper.findOrderByOrderId(orderID);
					if(orderMap!=null){
						if(Integer.parseInt(orderMap.get("STATE"))==19){
							flag=false;   //订单被取消
						}else{
							flag=true;    //可以正常执行
						}
					}
				}
			}else{  //判断订单是否改派
				Map<String,String> updateMap=updateOper.findOrderChangeVehicleOrCancel(orderID,Integer.parseInt(rescueVehicleId));
				if(updateMap!=null){
					flag=false;  //订单被改派
				}
			}
		} catch (CException e) {
			e.printStackTrace();
		}finally{
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		json.put("code",flag);
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().print(json.toJSONString());
		setNext(false);
	}
	
	
	/**
	 * 判断此订单是否还存在改师傅名下（没被取消和改派）
	 * 1.查询师傅调度表（订单编号+师傅id）
	 * 2.不存在，查看是否改派
	 * 3.存在，user_order 订单是否取消
	 * 4.否，查看详情；是，提示订单取消
	 * 5.否，则可修改订单状态
	 * @throws Exception
	 */
	public void vehicleChanged(){
		int state=Integer.parseInt(request.getParameter("state"));
		int flow_id=Integer.parseInt(request.getParameter("flow_id"));
		int orderID=Integer.parseInt(request.getParameter("orderID"));
		double lon=Double.valueOf(getParameter("lon","0"));
		double lat=Double.valueOf(getParameter("lat","0"));
		String rescueVehicleId=request.getParameter("rescueVehicleId");  //司机表id
		
		Connection conn=null;
		try {
			conn=ConnectionPool.getConnection();
			UserOrderOper orderOper=new UserOrderOper(conn);
			Map<String,String> orderMap=orderOper.findOrderByOrderId(orderID);
			int nextState=ProgressProcess.getProcess(state,flow_id);
			if(Integer.parseInt(orderMap.get("STATE"))==state){    //判断当前状态是否和数据库一致
				System.out.println("测试出错是的下一步状态"+nextState);
				 updateOrderState(nextState,orderID,lon,lat,rescueVehicleId);
			}
		} catch (CException e) {
			e.printStackTrace();
		}finally{
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 提交工单状态
	 * 1.一致调用远程方法更改状态
	 * 2.成功，更改当地订单状态
	 * @throws CException
	 * @throws Exception
	 */
	public void updateOrderState(int currentState,int orderId,double lon,double lat,String rescueVehicleId){
		JSONObject json=new JSONObject();
		JSONObject httpRequest=null;
		Connection conn=null;
		
		json.put("orderId", orderId);
		json.put("currentState", currentState);
		json.put("lon", lon);
		json.put("lat", lat);
		json.put("action", 7);
		
		try {
			conn=ConnectionPool.getConnection();
			UserOrderOper orderOper=new UserOrderOper(conn);
			
			httpRequest=JSON.parseObject(HttpsUtil.doPost(Constants.url, json,"utf-8"));
			if(httpRequest.getIntValue("errorCode")==0){
				orderOper.updateUserOrderByOrderId(orderId, currentState);
				Map<String,String> orderMap=orderOper.findOrderByOrderId(orderId);
				int nextState=ProgressProcess.getProcess(currentState,Integer.parseInt(orderMap.get("FLOW_ID")));
				request.setAttribute("list", orderMap);
				setNextPage("/supplier/currentOrderDetail.jsp?&nextState="+nextState+"&rescueVehicleId="+rescueVehicleId);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	/**
	 * 提交工单公里数
	 * 1.远程提交里程数
	 * 2.本地更改里程数
	 * @throws IOException 
	 * @throws CException
	 * @throws Exception
	 */
	public void uploadOrderMileage() throws Exception {
		int orderId=Integer.parseInt(getParameter("orderID", ""));
		double milesage1=Double.valueOf(getParameter("milesage1","0"));
		double milesage2=Double.valueOf(getParameter("milesage2","0"));
		
		int state=Integer.parseInt(request.getParameter("state"));
		int flow_id=Integer.parseInt(request.getParameter("flow_id"));
		double lon=Double.valueOf(getParameter("lon","0")).doubleValue();
		double lat=Double.valueOf(getParameter("lat","0")).doubleValue();
		int nextState=ProgressProcess.getProcess(state,flow_id);
		
		JSONObject json=new JSONObject();
		JSONObject jsonObject=new JSONObject();
		JSONObject httpRequest1=null;
		JSONObject httpRequest2=null;
		boolean isSuccess=false;
		Connection conn=null;
		
		json.put("orderId",orderId );
		json.put("mileage1",milesage1*1000 );
		json.put("mileage2",milesage2*1000 );
		json.put("currentState", nextState);
		json.put("lon", lon);
		json.put("lat", lat);
		json.put("action", 7);
		
		jsonObject.put("action", 9);
		jsonObject.put("orderId",orderId);
		jsonObject.put("mileage1",milesage1*1000);
		jsonObject.put("mileage2",milesage2*1000);
		
		try {
			conn=ConnectionPool.getConnection();
			System.out.println(nextState+"此时的状态是为多少");
			UserOrderOper orderOper=new UserOrderOper(conn);
			
			httpRequest1=JSON.parseObject(HttpsUtil.doPost(Constants.url, jsonObject,"utf-8"));
			httpRequest2=JSONObject.parseObject(HttpsUtil.doPost(Constants.url, json,"utf-8"));
			if(httpRequest1.getIntValue("errorCode")==0 && httpRequest2.getIntValue("errorCode")==0){
				orderOper.updateUserOrderMilesByOrderId(orderId,milesage1*1000,milesage2*1000);
				orderOper.updateUserOrderByOrderId(orderId, 15);
				isSuccess=true;
			}
		} catch (CException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			conn.close();
		}
		
		json.put("code",isSuccess);
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().print(json.toJSONString());
		setNext(false);
	}

}
