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

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

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.google.gson.Gson;

import cn.net.caoyao.cpzshandset.bean.ActivateBean;
import cn.net.caoyao.cpzshandset.bean.SingleLabelOptionBean;
import cn.net.caoyao.cpzshandset.bean.SubmitBean;
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.InternalOptionConstant;
import cn.net.caoyao.cpzshandset.common.config.RequestConstant;
import cn.net.caoyao.cpzshandset.service.bll.ActivateBll;
import cn.net.caoyao.cpzshandset.service.bll.BatchLabelBll;
import cn.net.caoyao.cpzshandset.service.bll.SingleLabelBll;
import cn.net.caoyao.cpzshandset.service.bll.UploadStatusBll;
import cn.net.caoyao.cpzshandset.service.presenter.LoginApis;
import cn.net.caoyao.cpzshandset.ui.activity.LoginActivity;
import cn.net.caoyao.cpzshandset.ui.activity.ProductDetailListActivity;
import cn.net.cpzslibs.prot.Prot02Logout;
import cn.net.cpzslibs.prot.SocketCreate;
import cn.net.cpzslibs.prot.bean.res.ProtStatusResBean;
import cn.net.cpzslibs.prot.handset.bean.req.Prot20002ReqBean;
import cn.net.cpzslibs.prot.handset.bean.req.Prot20017ReqBean;
import cn.net.cpzslibs.prot.handset.bean.res.Prot20017LabelBean;
import cn.net.cpzslibs.prot.handset.newProt.Prot20002Activate;
import cn.net.cpzslibs.prot.handset.newProt.Prot20017CheckLabelStatus;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class CommonSubmitAllActivateThread implements Runnable {
	private long deviceId;
	private ActivateBll bll;
	private SingleLabelBll labelBll;
	private BatchLabelBll batchBll;
	private UploadStatusBll uploadStatusBll;
	private List<ActivateBean> aBeans;
	private Handler mHandler;
	private int option_type = HandsetOperation.OPERATION_ACTIVATE_CONSTANT.getOption();
	Context context;
//	List<String> list=new ArrayList<>();
	public CommonSubmitAllActivateThread(Handler mHandler,long deviceId,ActivateBll bll,SingleLabelBll labelBll,BatchLabelBll batchBll,UploadStatusBll uploadStatusBll,List<ActivateBean> aBeans,Context context) {
		this.mHandler = mHandler;
		this.deviceId = deviceId;
		this.bll = bll;
		this.labelBll = labelBll;
		this.batchBll = batchBll;
		this.uploadStatusBll = uploadStatusBll;
		this.aBeans = aBeans;
		this.context = context;
	}

	@Override
	public void run() {
		try {
			submitActivateInfo();
		} catch (IOException e) {
			e.printStackTrace();
		}
//		SocketCreate create = new SocketCreate(Config.ip, Config.port, "");
//		try {
////			LogUtil.d(TConfig.Echo, "登录");
//			create.createLoginCpzsHandset(deviceId);
//			if (create.isResult()) {
//				submitActivateInfo(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 submitActivateInfo() throws IOException,SocketTimeoutException{
		for (ActivateBean activateBean : aBeans) {
			if (activateBean.getOption_mode() == Config.SINGLE_OPTION_LABEL_TYPE) {
				//单标
				submitSingleActivateInfo(activateBean);
			} else if (activateBean.getOption_mode() == Config.BATCH_OPTION_LABEL_TYPE) {
				//批量
				submitBatchActivateInfo(activateBean);
			}
		}
		mHandler.sendEmptyMessage(RequestConstant.SUBMIT_ALL_ACTIVATE_COMPLETE);
	}
	private void submitBatchActivateInfo(final ActivateBean activateBean) throws IOException{
		int count = batchBll.queryBatchCountById(option_type, activateBean.getId());
		if (count > 0) {
//			Prot20002Activate activate = new Prot20002Activate();
//			activate.submitActivateInfo(create, getBatchReqBean(activateBean));
//			ProtStatusResBean resBean = activate.getResBean();
//			if (resBean == null) {
//				return;
//			}

			Prot20002ReqBean batchReqBean = getBatchReqBean(activateBean);
			String end = batchReqBean.getBatcher().getEnd();
			String start = batchReqBean.getBatcher().getStart();
			SharedPreferences user_token =context.getSharedPreferences("data", 0);
			String token = user_token.getString("appToken", "");
			Log.d("我提交的===》参数",token);
			Map<String,Object> map=new HashMap<>();
			map.put("batchNumber",Long.valueOf(activateBean.getProduct_batch_number()));
		map.put("companyId",activateBean.getCompany_id());
			map.put("productId",Long.valueOf(activateBean.getProduct_id()));
			map.put("endTag",end);
			map.put("startTag",start);
			Gson gson=new Gson();
			String s = gson.toJson(map);
			Log.d("我提交的===》参数",s);
			RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), s);


			Retrofit retrofit = new Retrofit.Builder()
					.baseUrl(Config.caoyaoUrl)
					.addConverterFactory(GsonConverterFactory.create())
					.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
					.build();
			LoginApis loginApis = retrofit.create(LoginApis.class);
			Observable<ResponseBody> observable=loginApis.getBatchSubmit("Bearer  "+token,requestBody);
			observable.subscribeOn(Schedulers.io());
			observable.observeOn(AndroidSchedulers.mainThread());
			observable.subscribe(new Observer<ResponseBody>() {
				@Override
				public void onSubscribe(Disposable d) {
				}
				@Override
				public void onNext(ResponseBody value) {
					try {
						String string = value.string();
						Log.d("我上传批量参数===》",string);
						Gson gson = new Gson();
						SubmitBean submitBean= gson.fromJson(string, SubmitBean.class);
						int code = submitBean.getCode();
						if (code==200){
							uploadStatusBll.insertUploadStatus(getUploadBean(activateBean));
//				LogUtil.i(TConfig.Echo, "插入批量激活提交状态：" + getUploadBean(activateBean).toString());
							bll.delActivateById(activateBean);
						}else if (code==401){
							SharedPreferences sp=context.getSharedPreferences("data",0);
							SharedPreferences.Editor edit = sp.edit();
							edit.putString("appToken","");
							edit.commit();
							Intent intent = new Intent(context, LoginActivity.class);
							context.startActivity(intent);
						}else {
							bll.updateActivateErrorById(submitBean.getCode(), activateBean.getId());
						}


					} catch (IOException e) {
						Log.d("我上传之后的===》",e.getMessage());
					}
				}

				@Override
				public void onError(Throwable e) {
					Log.d("我上传之后的===》",e.getMessage());
				}

				@Override
				public void onComplete() {

				}
			});























//			if (resBean.getResult() == 0) {
//				//上传成功，插入记录到提交状态表
//				uploadStatusBll.insertUploadStatus(getUploadBean(activateBean));
////				LogUtil.i(TConfig.Echo, "插入批量激活提交状态：" + getUploadBean(activateBean).toString());
//				bll.delActivateById(activateBean);
////				bll.delActivateById(activateBean.getId());
////				batchBll.deleteBatchById(option_type, activateBean.getId());
//			} else {
//				bll.updateActivateErrorById(resBean.getErrcode(), activateBean.getId());
//			}
//
		}
		
	}

	private UploadBean getUploadBean(ActivateBean activateBean) {
		UploadBean b = new UploadBean();
		if (activateBean.getOption_mode() == Config.SINGLE_OPTION_LABEL_TYPE) {
			b.setLabel_count(labelBll.queryLabelCountById(option_type, activateBean.getId()));
		} else {
			b.setLabel_count(batchBll.queryBatchCountById(option_type, activateBean.getId()));
		}
		b.setOption_type(option_type);
		return b;
	}

	private Prot20002ReqBean getBatchReqBean(ActivateBean activateBean) {
		Prot20002ReqBean reqBean = new Prot20002ReqBean();
		reqBean.setProduct_id(activateBean.getProduct_id());
		reqBean.setProducer(activateBean.getProducer());
		reqBean.setProduce_date(activateBean.getProduct_date());
		reqBean.setProduce_batch(activateBean.getProduct_batch_number());
		reqBean.setType(Config.BATCH_OPTION_LABEL_TYPE);
		reqBean.setBatcher(batchBll.queryBatchBeanById(option_type, activateBean.getId()));
		return reqBean;
	}

	private void submitSingleActivateInfo(final ActivateBean activateBean) throws IOException{
		int count = labelBll.queryLabelCountById(option_type, activateBean.getId());
		if (count > 0) {
			SharedPreferences user_token =context.getSharedPreferences("data", 0);
			String token = user_token.getString("appToken", "");
			Map<String,Object> map=new HashMap<>();
			map.put("batchNumber",Long.valueOf(activateBean.getProduct_batch_number()));
		map.put("companyId",activateBean.getCompany_id());
			map.put("productId",Long.valueOf(activateBean.getProduct_id()));
			List<String> singleOptions = getLabels(activateBean.getId());
			map.put("singles",singleOptions);
			Gson gson=new Gson();
			final String s = gson.toJson(map);
			RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), s);


			Retrofit retrofit = new Retrofit.Builder()
					.baseUrl(Config.caoyaoUrl)
					.addConverterFactory(GsonConverterFactory.create())
					.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
					.build();
			LoginApis loginApis = retrofit.create(LoginApis.class);
			Observable<ResponseBody> observable=loginApis.getSingleSubmit("Bearer  "+token,requestBody);
			observable.subscribeOn(Schedulers.io());
			observable.observeOn(AndroidSchedulers.mainThread());
			observable.subscribe(new Observer<ResponseBody>() {
				@Override
				public void onSubscribe(Disposable d) {
				}
				@Override
				public void onNext(ResponseBody value) {
					try {
						String string = value.string();
						Log.i("我上传的数据===》",string);
						Gson gson = new Gson();
						SubmitBean submitBean = gson.fromJson(string, SubmitBean.class);
						int code = submitBean.getCode();
						if (code==200){
							uploadStatusBll.insertUploadStatus(getUploadBean(activateBean));
//				LogUtil.i(TConfig.Echo, "插入单标激活提交状态：" + getUploadBean(activateBean).toString());
							bll.delActivateById(activateBean);
						}else if (code==401){
							SharedPreferences sp=context.getSharedPreferences("data",0);
							SharedPreferences.Editor edit = sp.edit();
							edit.putString("appToken","");
							edit.commit();
							Intent intent = new Intent(context, LoginActivity.class);
							context.startActivity(intent);
						}else {
							bll.updateActivateErrorById(submitBean.getCode(), activateBean.getId());
//							checkLabel(create,activateBean);
						}

					} catch (IOException e) {
					}
				}

				@Override
				public void onError(Throwable e) {
				}

				@Override
				public void onComplete() {

				}
			});
		}
		
	}

	private void checkLabel(SocketCreate create,ActivateBean activateBean) throws IOException{
		Prot20017CheckLabelStatus prot20017 = new Prot20017CheckLabelStatus();
		prot20017.checkLabel(create, getProt20017ReqBean(activateBean));
		if (prot20017.getResBean() != null && prot20017.getResBean().getResult() == 0) {
			List<Prot20017LabelBean> invilad = prot20017.getResBean().getLabel_invalid();
			if (invilad != null) {
				List<String> inviladLabel = new ArrayList<>();
				for (Prot20017LabelBean prot20017LabelBean : invilad) {
					inviladLabel.add(prot20017LabelBean.getLabel_id());
				}
				labelBll.updateLableStatusById(inviladLabel, option_type, activateBean.getId(), InternalOptionConstant.SINGLE_LABEL_STATUS_INVALID);
			}
			
			List<Prot20017LabelBean> repeat = prot20017.getResBean().getLabel_double_active();
			if (repeat != null) {
				List<String> repeatLabel = new ArrayList<>();
				for (Prot20017LabelBean prot20017LabelBean : repeat) {
					repeatLabel.add(prot20017LabelBean.getLabel_id());
				}
				labelBll.updateLableStatusById(repeatLabel, option_type, activateBean.getId(), InternalOptionConstant.SINGLE_LABEL_STATUS_REPEAT_ACTIVATE);
			}
		}
		
	}

	private Prot20017ReqBean getProt20017ReqBean(ActivateBean activateBean) {
		Prot20017ReqBean reqBean = new Prot20017ReqBean();
		reqBean.setLabels(getLabels(activateBean.getId()));
		reqBean.setOpt(8);
		return reqBean;
	}

	private Prot20002ReqBean getSingleReqBean(ActivateBean activateBean) {
		Prot20002ReqBean reqBean = new Prot20002ReqBean();
		reqBean.setProduct_id(activateBean.getProduct_id());
		reqBean.setProducer(activateBean.getProducer());
		reqBean.setProduce_date(activateBean.getProduct_date());
		reqBean.setProduce_batch(activateBean.getProduct_batch_number());
		reqBean.setType(Config.SINGLE_OPTION_LABEL_TYPE);
		reqBean.setSingle(getLabels(activateBean.getId()));
//		LogUtil.i(TConfig.Echo, "提交的数据：" + reqBean.toString());
		return reqBean;
	}

	private List<String> getLabels(int id) {
		List<String> singles = new ArrayList<>();
		List<SingleLabelOptionBean> singleOptions = labelBll.queryAllLabelById(option_type, id);
		for (SingleLabelOptionBean sLBean : singleOptions) {
			singles.add(sLBean.getLabel_id());
		}
		return singles;
	}


}
