package cn.net.caoyao.cpzshandset.service.thread.impl.yunCar;

import java.io.IOException;
import java.net.BindException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Map;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import cn.net.caoyao.cpzshandset.bean.UploadBean;
import cn.net.caoyao.cpzshandset.common.config.Config;
import cn.net.caoyao.cpzshandset.common.config.HandsetOperation;
import cn.net.caoyao.cpzshandset.common.config.RequestConstant;
import cn.net.caoyao.cpzshandset.common.config.TConfig;
import cn.net.caoyao.cpzshandset.common.util.LogUtil;
import cn.net.caoyao.cpzshandset.common.util.OnUploadProcessListener;
import cn.net.caoyao.cpzshandset.common.util.UpCarPicture;
import cn.net.caoyao.cpzshandset.db.dal.yunCar.YunCarLingLiaoDal;
import cn.net.caoyao.cpzshandset.service.bll.UploadStatusBll;
import cn.net.cpzslibs.prot.Prot02Logout;
import cn.net.cpzslibs.prot.SocketCreate;
import cn.net.cpzslibs.prot.handset.bean.req.Prot20060ReqBean;
import cn.net.cpzslibs.prot.handset.bean.res.Prot20060ResBean;
import cn.net.cpzslibs.prot.handset.newProt.Prot20060LingLiaoChuKu;

public class YunCarUpAllLingLiaoThread implements Runnable {
	private long deviceId;
	private Handler mHandler;
	private YunCarLingLiaoDal lingLiaoDal;
	//private String url = "https://www.cpzs.org/UpFromAndroid?key="; 
	private String url = "http://218.245.0.109:8080/jymf/UpFromAndroid?key="; // 图片测试连接
	
	private int resPic = 1;
	private int option_type = HandsetOperation.OPERATION_OUT_WAREHOUSE_CONSTANT.getOption();//出库
	
	private UploadStatusBll uploadStatusBll;
	
	public YunCarUpAllLingLiaoThread(Handler mHandler, long deviceId,
			YunCarLingLiaoDal lingLiaoDal,UploadStatusBll uploadStatusBll) {
		this.mHandler = mHandler;
		this.deviceId = deviceId;
		this.lingLiaoDal = lingLiaoDal;
		this.uploadStatusBll = uploadStatusBll;
		
	}

	@Override
	public void run() {
		SocketCreate create = new SocketCreate(Config.ip, Config.port, "");
		try {
			LogUtil.d(TConfig.Echo, "登录");

			create.createLoginCpzsHandset(deviceId);

			if (create.isResult()) {
				UpCarSaleList(create);
			} else {
				Message msg = new Message();
				msg.what = RequestConstant.REQUEST_PROT01_LOGIN_FAIL;
				msg.arg1 = create.getiErrCode();
				msg.obj = create.getErrMsg();
				mHandler.sendMessage(msg);
			}

		} catch (BindException e) {
			e.printStackTrace();
			mHandler.sendEmptyMessage(RequestConstant.REQUEST_FAIL);
		} catch (ConnectException e) {
			e.printStackTrace();
			mHandler.sendEmptyMessage(RequestConstant.REQUEST_FAIL);
		} catch (SocketTimeoutException e) {
			e.printStackTrace();
			mHandler.sendEmptyMessage(RequestConstant.REQUEST_FAIL_SOCKET_TIMEOUT);
		} catch (UnknownHostException e) {
			e.printStackTrace();
			mHandler.sendEmptyMessage(RequestConstant.REQUEST_FAIL);
		} catch (IOException e) {
			e.printStackTrace();
			mHandler.sendEmptyMessage(RequestConstant.REQUEST_FAIL);
		} finally {
			new Prot02Logout().dealLogout(create);
		}

	}

	private void UpCarSaleList(SocketCreate create) throws IOException {
		Prot20060LingLiaoChuKu  p60 = new Prot20060LingLiaoChuKu();
		List<Map<String, String>> list = lingLiaoDal.queryLingLiaoInfo();
		Prot20060ReqBean reqBean = null;
		String path = "";
		String lingLiaoDate = "";
		String	carNo=""; 
		for(int i = 0; i < list.size(); i++){
			path = list.get(i).get("picture_url");
			lingLiaoDate = list.get(i).get("lingLiaodate");
			carNo = list.get(i).get("car_no") ;
			reqBean = new Prot20060ReqBean(carNo,lingLiaoDate);
			Log.d("--==tag", "--==tag" + "-" + path+ "-" + lingLiaoDate+ "-" + carNo);
			p60.submitActivateInfo(create, reqBean);
			
		}
		Prot20060ResBean res = p60.getResBean();
		if (res.getResult() != 0) {
			// 请求失败
			lingLiaoDal.upErrCode(Config.SUBMIT_STATUS_SUBMIT_FAIL,
					res.getErrcode() + "", list.get(0).get("car_no"));
			Message msg = mHandler.obtainMessage();
			msg.what = RequestConstant.REQUEST_YUNCAR_LIST_FAIL;
			msg.obj = res;
			mHandler.sendMessage(msg);
			return;
		}
			int carId  = res.getId();
		if (!"".equals(path) || null != path) {//有图片
			String [] date  = lingLiaoDate.split("-");
			String lingLiao = date[0]+date[1]+date[2];
			
		//	Log.d("--==tag", "--==tag" + "-" + path+ "-" + date.length + "-" + carNo+Arrays.toString(date)+"-"+lingLiao);
			upPic(create, carId+"", lingLiao ,path);
		}else{//无图片
			String errCode = String.valueOf(resPic);
			lingLiaoDal.upErrCode(Config.SUBMIT_STATUS_PIC_SUBMIT_FAIL,
					errCode + "", list.get(0).get("car_no"));
			Message msg = mHandler.obtainMessage();
			msg.what = RequestConstant.REQUEST_YUNCAR_LIST_FAIL;
			msg.obj = res;
			mHandler.sendMessage(msg);
		}
		
		//全部上传完成后的处理
		if (resPic == 0) {// 图片上传成功 有图片成功。
			uploadStatusBll.insertUploadStatus(getUploadBean());//提交数量+1
			lingLiaoDal.deleteAllLingLiaoInfo();
			mHandler.sendEmptyMessage(RequestConstant.REQUEST_YUNCAR_LIST__SUCCESS);
			
		} else {// 图片上传失败
		// String errCode = "51"+ String.valueOf(resPic); 
			String errCode = String.valueOf(resPic);
			lingLiaoDal.upErrCode(Config.SUBMIT_STATUS_PIC_SUBMIT_FAIL,
					errCode + "", list.get(0).get("car_no"));
			Message msg = mHandler.obtainMessage();
			msg.what = RequestConstant.REQUEST_YUNCAR_LIST_FAIL;
			msg.obj = res;
			mHandler.sendMessage(msg);
		}
	
		
	}

	private void upPic(SocketCreate create, String carID,String lingLiaoDate, String imaPtah) {
		UpCarPicture.getInstance().setOnUploadProcessListener(
				new OnUploadProcessListener() {
					
					@Override
					public void onUploadProcess(int uploadSize) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onUploadDone(int responseCode, String message) {

						if (responseCode == UpCarPicture.SUCCESS) {// 上传图片成功
							resPic = 0;
							//canConfigDal.deleteAllSaleInfoPicture();
						} else {
							// canConfigDal.deleteAllSaleInfoPicture();
							resPic = responseCode;
							Log.d("--==tag", "--==responseCode"+responseCode);
						}

					}

					@Override
					public void initUpload(int fileSize) {
						// TODO Auto-generated method stub

					}
				});

	
		
		String key =create.getiCompanyId() + "_" + carID + "_" + lingLiaoDate; 
		
		//String key2 =  create.getiCompanyId() + "_" + "1111110028058080"; 
		
		Log.d("--==key2", "--==key2" + key+"-"+imaPtah);
		
		UpCarPicture.getInstance().uploadFile(key, imaPtah, "image", url+key);

	}
	
	private UploadBean getUploadBean() {
		UploadBean b = new UploadBean();

		b.setLabel_count(1);

		b.setOption_type(option_type);
		return b;
	}


}

