package cn.net.caoyao.cpzshandset.service.presenter.impl.activateWithRelation.liqueurSFY;

import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.Toast;
import cilico.tools.barcode.PhoneScanner;
import cn.net.caoyao.cpzshandset.R;
import cn.net.caoyao.cpzshandset.bean.ConfigBean;
import cn.net.caoyao.cpzshandset.common.config.HandsetVersionConstant;
import cn.net.caoyao.cpzshandset.common.config.RequestConstant;
import cn.net.caoyao.cpzshandset.common.util.StringUtils;
import cn.net.caoyao.cpzshandset.service.bll.ProductBll;
import cn.net.caoyao.cpzshandset.service.bll.config.ConfigBll;
import cn.net.caoyao.cpzshandset.service.presenter.ProductDetailListConstact;
import cn.net.caoyao.cpzshandset.service.presenter.base.impl.ProductDetailListConstactImpl;
import cn.net.caoyao.cpzshandset.service.thread.ThreadPoolManager;
import cn.net.caoyao.cpzshandset.service.thread.impl.liqueurSFY.LiqueurSFYUpdateProductListThread;
import cn.net.caoyao.cpzshandset.ui.adapter.ProductAdapter;
import cn.net.caoyao.cpzshandset.ui.weight.DialogUtils;
import cn.net.cpzslibs.prot.handset.bean.Product;
import cn.net.cpzslibs.prot.handset.bean.res.Prot20001ResBean;
import cn.net.handsetlib.utils.ReadDeviceIDUtil;

public class LiqueurSFYProductListPresenter extends ProductDetailListConstactImpl{
	private final ProductDetailListConstact.View pView;
	private Context context;
	private List<Product> allProducts = new ArrayList<Product>();
	private List<Product> searchProducts = new ArrayList<Product>();
	private ProductAdapter allAdapter;
	private ProductAdapter searchAdapter;
	private ProductBll bll;
	private TextWatcher t;
	private int choiceProductResultCode = 1001;
	private ProgressDialog bProgressDialog = null;
	private ConfigBll configBll;
	private int currentHansetVersion = HandsetVersionConstant.HANDSET_LIQUEUR_SFY_VERSION_MODE;
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case PhoneScanner.BARCODE_READ:
			case PhoneScanner.BARCODE_ERR_LABEL: // 成功
				scannerRecuess(msg.obj.toString());
				break;
			case PhoneScanner.BARCODE_NOREAD:
				// 数据扫描失败
				if (checkViewAvailable()) {
					pView.showMsgToast("取消扫描", Toast.LENGTH_SHORT);
				}
				break;
			case RequestConstant.REQUEST_FAIL:
				//请求失败
				if (!checkViewAvailable())return;
				dismissProgress();
				pView.showMsgToast("请求失败！", Toast.LENGTH_SHORT);
				break;
			case RequestConstant.REQUEST_FAIL_SOCKET_TIMEOUT:
				//超时
				if (!checkViewAvailable())return;
				dismissProgress();
				pView.showMsgToast("请求超时！", Toast.LENGTH_SHORT);
				break;
			case RequestConstant.REQUEST_PROT01_LOGIN_FAIL:
				//登录失败
				if (!checkViewAvailable())return;
				dismissProgress();
				String errorMsg = msg.obj.toString();
				int errorCode = msg.arg1;
				pView.showMsgToast(errorMsg + errorCode, Toast.LENGTH_SHORT);
				break;
			case RequestConstant.REQUEST_PRODUCT_LIST_SUCCESS:
				//请求产品信息成功
				if (!checkViewAvailable())return;
				dismissProgress();
				pView.showMsgToast("请求产品信息成功！", Toast.LENGTH_SHORT);
				allProducts = bll.queryAllProductInfo();
				pView.setAllPLvVisible();
				allAdapter.refreshData(allProducts);
				break;
			case RequestConstant.REQUEST_PRODUCT_LIST_FAIL:
				//请求产品信息失败
				if (!checkViewAvailable())return;
				dismissProgress();
				Prot20001ResBean resBean = (Prot20001ResBean) msg.obj;
				pView.showMsgToast("请求失败 错误码：" + resBean.getErrcode(), Toast.LENGTH_SHORT);
				break;
			case RequestConstant.REQUEST_PRODUCT_LIST_IS_EMPTY:
				if (!checkViewAvailable())return;
				dismissProgress();
				String errorMsg1 = msg.obj.toString();
//				int errorCode1 = msg.arg1;
				allProducts = bll.queryAllProductInfo();
				pView.setAllPLvVisible();
				allAdapter.refreshData(allProducts);
				pView.showMsgToast(errorMsg1, Toast.LENGTH_SHORT);
				break;
			}

		}

	};

	public LiqueurSFYProductListPresenter(ProductDetailListConstact.View pView, Context context) {
		this.pView = pView;
		this.context = context;
		start();
	}

	private void scannerRecuess(String str) {
		if (!checkViewAvailable())
			return;
		pView.vibrate(100);
		if (StringUtils.isEmpty(str))
			pView.showMsgToast("抱歉，扫描内容为空", Toast.LENGTH_SHORT);
		pView.removeTextChangedListener(t);
		pView.setEtText(str);
		pView.addTextChangedListener(t);
		search();
	}
	public void dismissProgress() {
		if (bProgressDialog != null) {
			try {
				DialogUtils.dismissProgressDialog(bProgressDialog);
			} catch (Exception e) {
			}
		}
	}

	/**
	 * 提示正在更新数据
	 */
	protected void showProgressDialog(String titleStr, String tipsMsg) {
		bProgressDialog = DialogUtils.showProgressDialog(bProgressDialog, titleStr,
				tipsMsg, context);
	}
	/**
	 * 搜索功能
	 */
	private void search() {
		if (!checkViewAvailable())
			return;
		String searchCondition = pView.getEtText();

		if (StringUtils.isEmpty(searchCondition)) {
			pView.setAllPLvVisible();
			return;
		}

		searchProducts = bll.getPSearch(searchCondition);
		if (searchProducts.size() <= 0) {
			pView.showMsgToast(context.getResources().getString(R.string.p_list_search_not_find_tips_str),
					Toast.LENGTH_SHORT);
			return;
		}

		if (searchAdapter != null) {
			pView.setSearchPLvVisible();
			searchAdapter.refreshData(searchProducts);
		}

	}

	@Override
	public void start() {
		if (!checkViewAvailable())
			return;
		init();
		pView.setBtnRightStr("更新");
		pView.addTextChangedListener(t);
		allAdapter = new ProductAdapter(allProducts);
		searchAdapter = new ProductAdapter(searchProducts);
		pView.setAllPLvAdapter(allAdapter);
		pView.setPSearchAdapter(searchAdapter);
		allProducts = bll.queryAllProductInfo();
//		LogUtil.d(TConfig.Echo, allProducts.size() + " allProducts:" + allProducts.toString());
		pView.setAllPLvVisible();
		allAdapter.refreshData(allProducts);
		searchAdapter.refreshData(searchProducts);

	}

	private void init() {
		configBll = new ConfigBll(context);
		bll = new ProductBll(context);
		t = new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
				if (!checkViewAvailable())
					return;
				search();
			}
		};
	}

	@Override
	public boolean checkViewAvailable() {
		boolean b = false;
		if (pView != null || context != null) {
			b = true;
		}
		return b;
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {

	}

	@Override
	public Handler getHandler() {
		return mHandler;
	}

	@Override
	public void onPLvItemClickListener(int position) {
		if (!checkViewAvailable())
			return;
		Intent intent = new Intent();
		intent.putExtra("choicedProduct", allProducts.get(position));
		pView.finishWithResult(choiceProductResultCode, intent);
	}

	@Override
	public void onSearchLvItemClickListener(int position) {
		// TODO Auto-generated method stub
		if (!checkViewAvailable())
			return;
		Intent intent = new Intent();
		intent.putExtra("choicedProduct", searchProducts.get(position));
		pView.finishWithResult(choiceProductResultCode, intent);

	}

	@Override
	public void btnSearchClick() {
		if (!checkViewAvailable()) return;
		search();
	}

	@Override
	public void btnScannerClick() {
		if (!checkViewAvailable())
			return;
		pView.readQRCode();
	}

	@Override
	public void updatePListClick() {
		ConfigBean configBean = configBll.queryConfigByHandsetMode(currentHansetVersion);
		if (configBean != null) {
			showProgressDialog("提示", "正在请求产品信息，请稍后……");
			 long deviceId = Long.parseLong(ReadDeviceIDUtil.readScanDecrypt(configBean.getDeviceId()));
			 ThreadPoolManager.getThreadPool().execute(new LiqueurSFYUpdateProductListThread(mHandler,deviceId,bll));
		} else {
			pView.showMsgToast("当前设备还未配置过手持机id，请先配置手持机的设备id", Toast.LENGTH_SHORT);
		}
	}

}
