package cn.net.caoyao.cpzshandset.service.presenter.impl.activate.ythImage;

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

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
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.bitmap.MBitmapService;
import cn.net.caoyao.cpzshandset.common.config.HandsetVersionConstant;
import cn.net.caoyao.cpzshandset.common.config.RequestConstant;
import cn.net.caoyao.cpzshandset.common.config.SDCardConfig;
import cn.net.caoyao.cpzshandset.common.util.NetWorkUtils;
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.ythImage.DownloadImageRunable;
import cn.net.caoyao.cpzshandset.service.thread.impl.ythImage.YthImageUpdateProductListThread;
import cn.net.caoyao.cpzshandset.ui.adapter.ProductImageAdapter;
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 YthImageProductListPresenter extends ProductDetailListConstactImpl {
	private final ProductDetailListConstact.View pLView;
	private Context context;
	private List<Product> allProducts = new ArrayList<Product>();
	private List<Product> searchProducts = new ArrayList<Product>();
	private ProductImageAdapter allAdapter;
	private ProductImageAdapter searchAdapter;
	private ProductBll bll;
	private TextWatcher t;
	private int choiceProductResultCode = 1001;
	private ProgressDialog bProgressDialog = null;
	private ConfigBll configBll;
	private MBitmapService bitmapService;
	private List<String> beforeImages;
	private Bitmap defaultBitmap;
	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()) {
					pLView.showMsgToast("取消扫描", Toast.LENGTH_SHORT);
				}
				break;
			case RequestConstant.REQUEST_FAIL:
				//请求失败
				if (!checkViewAvailable())return;
				dismissProgress();
				pLView.showMsgToast("请求失败！", Toast.LENGTH_SHORT);
				break;
			case RequestConstant.REQUEST_FAIL_SOCKET_TIMEOUT:
				//超时
				if (!checkViewAvailable())return;
				dismissProgress();
				pLView.showMsgToast("请求超时！", Toast.LENGTH_SHORT);
				break;
			case RequestConstant.REQUEST_PROT01_LOGIN_FAIL:
				//登录失败
				if (!checkViewAvailable())return;
				dismissProgress();
				String errorMsg = msg.obj.toString();
				int errorCode = msg.arg1;
				pLView.showMsgToast(errorMsg + errorCode, Toast.LENGTH_SHORT);
				break;
			case RequestConstant.REQUEST_PRODUCT_LIST_SUCCESS:
				//请求产品信息成功
				if (!checkViewAvailable())return;
//				dismissProgress();
//				pLView.showMsgToast("请求产品信息成功！", Toast.LENGTH_SHORT);
				if (!checkViewAvailable())return;
				bProgressDialog.setMessage("产品列表请求成功，开始请求产品图片信息");
				downloadPImage();
				/*allProducts = bll.queryAllProductInfo();
				pLView.setAllPLvVisible();
				allAdapter.refreshData(allProducts);*/
				break;
			case RequestConstant.REQUEST_PRODUCT_LIST_FAIL:
				//请求产品信息失败
				if (!checkViewAvailable())return;
				dismissProgress();
				Prot20001ResBean resBean = (Prot20001ResBean) msg.obj;
				pLView.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;
				pLView.showMsgToast(errorMsg1 + errorCode1, Toast.LENGTH_SHORT);
				break;
			case RequestConstant.DOWNLOAD_PRODUCT_IMAGE_SUCCESS:
				if (!checkViewAvailable())return;
				dismissProgress();
				pLView.showMsgToast("产品图片下载完成", Toast.LENGTH_SHORT);
				allProducts = bll.queryAllProductInfo();
				pLView.setAllPLvVisible();
				allAdapter.refreshData(allProducts);
				break;
			}

		}

	};

	public YthImageProductListPresenter(ProductDetailListConstact.View pLView, Context context) {
		this.pLView = pLView;
		this.context = context;
		start();
	}

	private void scannerRecuess(String str) {
		if (!checkViewAvailable())
			return;
		pLView.vibrate(100);
		if (StringUtils.isEmpty(str))
			pLView.showMsgToast("抱歉，扫描内容为空", Toast.LENGTH_SHORT);
		pLView.removeTextChangedListener(t);
		pLView.setEtText(str);
		pLView.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 = pLView.getEtText();

		if (StringUtils.isEmpty(searchCondition)) {
			pLView.setAllPLvVisible();
//			pLView.showMsgToast(context.getResources().getString(R.string.p_list_search_condition_empty_tips_str),
//					Toast.LENGTH_SHORT);
			return;
		}

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

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

	}

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

	}

	private void addTestData() {
		Product p = new Product();
		p.setName("测试图片");
		allProducts.add(p);
	}


	private void init() {
		defaultBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.product_image_bg_default);
		bitmapService = MBitmapService.create(MBitmapService.getInstance(context), context, SDCardConfig.getImageCachePath(context));
		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 (pLView != 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;
		bll.updateChoiceCountById(allProducts.get(position).getId());
		Intent intent = new Intent();
		intent.putExtra("choicedProduct", allProducts.get(position));
		pLView.finishWithResult(choiceProductResultCode, intent);
	}

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

	}

	@Override
	public void btnSearchClick() {
		search();
	}

	@Override
	public void btnScannerClick() {
		if (!checkViewAvailable())
			return;
		pLView.readQRCode();
	}
	private void downloadPImage() {
		ThreadPoolManager.getThreadPool().execute(new DownloadImageRunable(mHandler, bll.queryAllImage(), beforeImages, bitmapService));			
	};

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

}
