package com.sino.rrs.business;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.sino.publicclass.database.ConnectionPool;
import com.sino.rrs.entity.RescueCompanyDispatchPO;
import com.sino.rrs.entity.RescueVehicleDispatchPO;
import com.sino.rrs.entity.SendOrderMessage;
import com.sino.rrs.oper.RcRescueUpdateOper;
import com.sino.rrs.oper.RcTempleteOrder;
import com.sino.rrs.oper.RescueCompanyDispatchOper;
import com.sino.rrs.oper.RescueVehicleDispatchOper;
import com.sino.rrs.oper.UserOrderOper;
import com.sino.weixin.oauth.util.Constants;

/**
 * 系统调度订单线程池
 * @author Administrator
 *
 */
public class RescueCompanyDispatchMessage implements Runnable{
	public static Log log=LogFactory.getLog(RescueCompanyDispatchMessage.class);
	public RescueCompanyDispatchPO rescueCompanyDispatchPO;
	private SendOrderMessage sendMessage= new SendOrderMessage();
	
	Connection conn = null;
	PreparedStatement pstmt = null;
	
	public RescueCompanyDispatchMessage(RescueCompanyDispatchPO rescueCompanyDispatchPO){
		this.rescueCompanyDispatchPO=rescueCompanyDispatchPO;
	}
	
	@Override
	public void run() {
		try {
			conn=ConnectionPool.getConnection();
			RescueCompanyDispatchOper rescueOper=new RescueCompanyDispatchOper(conn);
			RescueVehicleDispatchOper vehicleOper=new RescueVehicleDispatchOper(conn);
			UserOrderOper orderOper=new UserOrderOper(conn);
			RcTempleteOrder templeteOrder=new RcTempleteOrder(conn);
			RcRescueUpdateOper updateOper=new RcRescueUpdateOper(conn);
			
			String tempID=templeteOrder.insertTempleteMessage(rescueCompanyDispatchPO.getOrder_id(), rescueCompanyDispatchPO.getRESCUE_COMPANY_CODE());
			if(tempID!=null){
				List<Map<String,String>> rescueCompanyList= rescueOper.getRescueCompanyCode(rescueCompanyDispatchPO.getRESCUE_COMPANY_CODE());
				if(rescueCompanyList!=null&&rescueCompanyList.size()>0){  //已注册
					boolean sendFlag = false;
					for(Map<String,String> rescueCompanyMap:rescueCompanyList){
						if(Integer.parseInt(rescueCompanyMap.get("accept_flag"))==0 ){  //供应商处于愿意接收消息状态
							rescueCompanyDispatchPO.setOpenId(rescueCompanyMap.get("open_id"));
							rescueCompanyDispatchPO.setTempleteId(tempID);
							int result = sendMessage.send_template_message(Constants.AppId, Constants.AppSecret,rescueCompanyDispatchPO);
							if(result == 40001||result == 42001){
								WeixinSignatureThread signature = new WeixinSignatureThread();
								signature.bulidApiAccessToken();
							    result = sendMessage.send_template_message(Constants.AppId, Constants.AppSecret,rescueCompanyDispatchPO);
							}
							if(result==0){
								sendFlag = true;
							}
						}
					}
					if(sendFlag){
						log.info("调度模板发送成功，开始录入订单表。。。。。。。。。。。。。。。。。");
						//判断订单表是否存在该订单，存在则更改，不存在则新增
						Map<String,String> map=orderOper.findOrderByOrderId(rescueCompanyDispatchPO.getOrder_id());
						if(map!=null){  //存在该订单任务
							updateMessage();
						}else{
							log.info("调度模板发送成功，开始录入订单表。。。。。。。。。。。。。。。。。4444");
							insertMessage();
						}
						//判断服务商调度表是否存在，如果存在未处理的纪录则变为超时，不存在则新增纪录
						log.info("录入订单表录入成功，开始录入服务商调度表。。。。。。。。。。。。。。。。。");
						rescueOper.updateRescueCompanyDispatchOverTime(rescueCompanyDispatchPO.getOrder_id());
						rescueOper.insertRescueCompanyMessage(rescueCompanyDispatchPO);
						
						//判断师傅调度表是否存在该订单（救援中任务修改救援车重新派服务商需要将之前的师傅订单任务删除）
						RescueVehicleDispatchPO vehiclePO=vehicleOper.changedVehicle(rescueCompanyDispatchPO.getOrder_id());
						if(vehiclePO!=null){   
							updateOper.insertVehicleChangedMessage(rescueCompanyDispatchPO.getOrder_id(),5,vehiclePO.getRESCUE_VEHICLE_ID(),"","救援车被修改");
							vehicleOper.deleteVehicleMessageByOrderId(rescueCompanyDispatchPO.getOrder_id());
						}
					}else{
						log.info("调度模板发送失败。。。。。。。。。。。。。。。。。");
					}
				}
			}
		}catch (Exception e) {
			e.printStackTrace();
			log.equals(e.getMessage());
		}finally{
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 更新数据信息
	 */
	public void updateMessage(){
			try {
			      String sql = "update RC_USER_ORDER set ORDER_CODE=?,FLOW_ID=?,SERVICE_NAME=?,LICENSE=?,STYLE=?,USER_NAME=?,USER_PHONE=?,LON=?,LAT=?,ADDRESS=?,ADDRESS_ADD=?,DEST_ADDRESS=?,REMARK=?,STATE=?,CREATE_TIME=?,DISPATCH_USER=?,ADDRESS_PROPERTY=?,CONTRACTING_NAME=?,MILEAGE1=?,MILEAGE2=?,UPDATE_TIME=?,FINISHTIME=? where ORDER_ID=?";

			      pstmt=conn.prepareStatement(sql);
				
				    pstmt.setString(1, rescueCompanyDispatchPO.getOrder_code());
				    pstmt.setInt(2,rescueCompanyDispatchPO.getFlow_id()); 
				    pstmt.setString(3, rescueCompanyDispatchPO.getService_name());
				    pstmt.setString(4, rescueCompanyDispatchPO.getLicense());
				    pstmt.setString(5, rescueCompanyDispatchPO.getStyle());
				    pstmt.setString(6, rescueCompanyDispatchPO.getUserName());
				    pstmt.setString(7, rescueCompanyDispatchPO.getUserPhone());
				    pstmt.setDouble(8, rescueCompanyDispatchPO.getLon());
				    pstmt.setDouble(9, rescueCompanyDispatchPO.getLat());
				    pstmt.setString(10, rescueCompanyDispatchPO.getAddress());
				    pstmt.setString(11, rescueCompanyDispatchPO.getAddressAdd());
				    pstmt.setString(12, rescueCompanyDispatchPO.getDest_address());  
				    pstmt.setString(13, rescueCompanyDispatchPO.getRemark()); 
				    pstmt.setInt(14, 62);
				    pstmt.setTimestamp(15, new Timestamp(System.currentTimeMillis()));
				    pstmt.setString(16, rescueCompanyDispatchPO.getDispatchUser());
				    pstmt.setString(17, rescueCompanyDispatchPO.getADDRESS_PROPERTY());
				    pstmt.setString(18, rescueCompanyDispatchPO.getCONTRACTING_NAME());
				    pstmt.setDouble(19, rescueCompanyDispatchPO.getMileage1());
				    pstmt.setDouble(20, rescueCompanyDispatchPO.getMileage2());
				    pstmt.setTimestamp(21, new Timestamp(System.currentTimeMillis()));
				    pstmt.setTimestamp(22, (Timestamp)rescueCompanyDispatchPO.getFinish_time());
				    pstmt.setInt(23,rescueCompanyDispatchPO.getOrder_id()); 
				    
			    pstmt.executeUpdate();
			    
			} catch (Exception e) {
				e.printStackTrace();
				log.error("数据库更新异常",e);
				try {
					conn.rollback();
				} catch (SQLException e1) {
					e1.printStackTrace();
				}
			} finally {
				if (pstmt != null)
					try {
						pstmt.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
			}
		}
	
	/**
	 * 添加数据信息
	 */
	public void insertMessage(){
			try {
				String sql="insert into RC_USER_ORDER(ORDER_ID,ORDER_CODE,FLOW_ID,SERVICE_NAME,LICENSE,STYLE," +
						"USER_NAME,USER_PHONE,LON,LAT,ADDRESS,ADDRESS_ADD,DEST_ADDRESS,REMARK,STATE,CREATE_TIME," +
						"DISPATCH_USER,ADDRESS_PROPERTY,CONTRACTING_NAME,MILEAGE1,MILEAGE2,UPDATE_TIME,FINISHTIME) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; 
				
				pstmt = conn.prepareStatement(sql); 
				
			    pstmt.setInt(1,rescueCompanyDispatchPO.getOrder_id());   //任务id
			    pstmt.setString(2, rescueCompanyDispatchPO.getOrder_code());
			    pstmt.setInt(3,rescueCompanyDispatchPO.getFlow_id()); 
			    pstmt.setString(4, rescueCompanyDispatchPO.getService_name());
			    pstmt.setString(5, rescueCompanyDispatchPO.getLicense());
			    pstmt.setString(6, rescueCompanyDispatchPO.getStyle());
			    pstmt.setString(7, rescueCompanyDispatchPO.getUserName());
			    pstmt.setString(8, rescueCompanyDispatchPO.getUserPhone());
			    pstmt.setDouble(9, rescueCompanyDispatchPO.getLon());
			    pstmt.setDouble(10, rescueCompanyDispatchPO.getLat());
			    pstmt.setString(11, rescueCompanyDispatchPO.getAddress());
			    pstmt.setString(12, rescueCompanyDispatchPO.getAddressAdd());
			    pstmt.setString(13, rescueCompanyDispatchPO.getDest_address());  
			    pstmt.setString(14, rescueCompanyDispatchPO.getRemark()); 
			    pstmt.setInt(15, 62);
			    pstmt.setTimestamp(16, new Timestamp(System.currentTimeMillis()));
			    pstmt.setString(17, rescueCompanyDispatchPO.getDispatchUser());
			    pstmt.setString(18, rescueCompanyDispatchPO.getADDRESS_PROPERTY());
			    pstmt.setString(19, rescueCompanyDispatchPO.getCONTRACTING_NAME());
			    pstmt.setDouble(20, rescueCompanyDispatchPO.getMileage1());
			    pstmt.setDouble(21, rescueCompanyDispatchPO.getMileage2());
			    pstmt.setTimestamp(22, (Timestamp) rescueCompanyDispatchPO.getUpdate_time());
			    pstmt.setTimestamp(23, (Timestamp)rescueCompanyDispatchPO.getFinish_time());
			    
			    pstmt.executeUpdate();
			    System.out.println("----------zhixing到测试");
			} catch (Exception e) {
				e.printStackTrace();
				log.error("数据库插入异常", e);
				try {
					conn.rollback();
				} catch (SQLException e1) {
					e1.printStackTrace();
				}
			} finally {
				if (pstmt != null)
					try {
						pstmt.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				} 
		}
	
	
	
	
	/*public static void main(String[] args) {
		RescueCompanyDispatchMessage a=new RescueCompanyDispatchMessage();
	}*/
	
}
