package cn.net.caoyao.cpzshandset.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import java.io.IOException;
import java.util.List;

import cilico.tools.barcode.PhoneScanner;
import cn.net.caoyao.cpzshandset.R;
import cn.net.caoyao.cpzshandset.adapter.PiCiListAdapter;
import cn.net.caoyao.cpzshandset.adapter.ProductListAdapter;
import cn.net.caoyao.cpzshandset.bean.ProductListBean;
import cn.net.caoyao.cpzshandset.common.config.Config;
import cn.net.caoyao.cpzshandset.common.util.StringUtils;
import cn.net.caoyao.cpzshandset.service.presenter.LoginApis;
import cn.net.caoyao.cpzshandset.service.presenter.ProductDetailListConstact;
import cn.net.caoyao.cpzshandset.service.presenter.ProductDetailListConstact.Presenter;
import cn.net.caoyao.cpzshandset.ui.activity.base.BaseScanActivity;
import cn.net.caoyao.cpzshandset.ui.weight.MyToast;
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.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class ProductDetailListActivity extends BaseScanActivity implements OnClickListener,ProductDetailListConstact.View {

	private ProductDetailListConstact.Presenter presenter;
	private TextView tv_title_common;
	private Button btn_title_more_option;
	private View btn_p_list_scanner,btn_p_list_search;
	private EditText et_p_list_search_condition;
	private ListView lv_p_list,lv_p_list_search;
	private MyToast myToast;
	private Context context;
	private RecyclerView xrv_productList;
	ProductListAdapter productListAdapter;
	private int choiceProductResultCode = 1001;
	@Override
	protected Handler initHandler() {
		return presenter != null ? presenter.getHandler() : null;
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		PhoneScanner.isDeviceId = true;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		PhoneScanner.isDeviceId = false;
		if (myToast != null) myToast.cancel();
	}
	@Override
	public int loadView() {
		init();
		return R.layout.activity_product_list;
	}

	private void init() {
		context = this;
		myToast = new MyToast(context);
	}

	@Override
	public void initTitleView() {
		View image_title_back_common = findViewById(R.id.image_title_back_common);
		image_title_back_common.setVisibility(View.VISIBLE);
		image_title_back_common.setOnClickListener(this);
		tv_title_common = (TextView) findViewById(R.id.tv_title_common);
		tv_title_common.setText("选择产品");
		btn_title_more_option = (Button) findViewById(R.id.btn_title_more_option);

		btn_title_more_option.setVisibility(View.GONE);
		btn_title_more_option.setOnClickListener(this);
		xrv_productList = (RecyclerView) findViewById(R.id.xrv_productList);

	}

	@Override
	public void initView() {
		btn_p_list_scanner = findViewById(R.id.btn_p_list_scanner);
		et_p_list_search_condition = (EditText) findViewById(R.id.et_p_list_search_condition);
		btn_p_list_search = findViewById(R.id.btn_p_list_search);
		lv_p_list = (ListView) findViewById(R.id.lv_p_list);
		lv_p_list_search = (ListView) findViewById(R.id.lv_p_list_search);
		LinearLayoutManager manager = new LinearLayoutManager(ProductDetailListActivity.this);
		manager.setOrientation(LinearLayoutManager.VERTICAL);
		xrv_productList.setLayoutManager(manager);


	}

	@Override
	public void initPresenter() {


		presenter = createService.createProductListPresenter(cacheG, context, this, getIntent());
//		LogUtil.d(TConfig.Echo, "initPresenter:" + presenter);
	}

	@Override
	public void setListener() {
		btn_p_list_scanner.setOnClickListener(this);
		btn_p_list_search.setOnClickListener(this);
		lv_p_list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if (presenter == null) return;
				presenter.onPLvItemClickListener(position);
			}
		});
		lv_p_list_search.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if (presenter == null) return;
				presenter.onSearchLvItemClickListener(position);
			}
		});
	}

	@Override
	public void initData() {

	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (presenter != null) {
			presenter.onActivityResult(requestCode, resultCode, data);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.image_title_back_common:
			//返回按钮
			finish();
			break;

		case R.id.btn_title_more_option:
			//更新产品列表操作
//			LogUtil.d(TConfig.Echo, "更新产品列表");
			if (presenter == null)return;
				presenter.updatePListClick();
			break;
		case R.id.btn_p_list_scanner:
			if (presenter == null)return;
			presenter.btnScannerClick();
			break;
		case R.id.btn_p_list_search:
			if (presenter == null)return;
			presenter.btnSearchClick();
			break;
		}
	}

	@Override
	public void setPresenter(Presenter presenter) {
		if (presenter != null) {
			this.presenter = presenter; 
		}
	}

	@Override
	public void startAcForResult(int reqCode, Intent intent) {
		if (reqCode < 0 || intent == null) return;
		startActivityForResult(intent, reqCode);
	}

	@Override
	public void showMsgToast(String msg, int duration) {
		if(myToast == null || StringUtils.isEmpty(msg)) return;
		myToast.show(msg, duration);
	}

	@Override
	public void readQRCode() {
		PhoneScanner.Read(createService, cacheG, context);
	}

	@Override
	public void setPageTitleStr(String titleStr) {
		if (tv_title_common == null || titleStr == null) return;
		tv_title_common.setText(titleStr+"");		
	}

	@Override
	public void setAllPLvAdapter(BaseAdapter adapter) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				getProjectList();
			}
		}).start();
		if (lv_p_list == null || adapter == null) return;
		lv_p_list.setAdapter(adapter);

	}

	@Override
	public void setEtText(String etStr) {
		if (et_p_list_search_condition == null || etStr == null) return;
		et_p_list_search_condition.setText(etStr+"");
		
	}

	@Override
	public String getEtText() {
		return et_p_list_search_condition == null ? "":et_p_list_search_condition.getText().toString().trim();
	}

	@Override
	public void setBtnRightStr(String moreStr) {
		if (btn_title_more_option == null || moreStr == null) return;
		btn_title_more_option.setText(moreStr +"");
	}

	@Override
	public void addTextChangedListener(TextWatcher t) {
		if (et_p_list_search_condition == null || t == null) return;
		et_p_list_search_condition.addTextChangedListener(t);
	}

	@Override
	public void removeTextChangedListener(TextWatcher t) {
		if (et_p_list_search_condition == null || t == null) return;
		et_p_list_search_condition.removeTextChangedListener(t);
	}

	@Override
	public void finishWithResult(int resultCode, Intent intent) {
		if (intent != null) {
			setResult(resultCode, intent);
			finish();
		}
	}

	@Override
	public void setPSearchAdapter(BaseAdapter adapter) {
//		if (lv_p_list_search == null || adapter == null) return;
//		lv_p_list_search.setAdapter(adapter);
	}

	@Override
	public void setSearchPLvVisible() {
//		if (lv_p_list_search != null && lv_p_list_search.getVisibility() != View.VISIBLE) lv_p_list_search.setVisibility(View.VISIBLE);
//		if (lv_p_list != null && lv_p_list.getVisibility() != View.GONE) lv_p_list.setVisibility(View.GONE);
	}

	@Override
	public void setAllPLvVisible() {
//		if (lv_p_list_search != null && lv_p_list_search.getVisibility() != View.GONE) lv_p_list_search.setVisibility(View.GONE);
//		if (lv_p_list != null && lv_p_list.getVisibility() != View.VISIBLE) lv_p_list.setVisibility(View.VISIBLE);
	}

	@Override
	public void vibrate(int duration) {
		vibrateReadQRComplete(duration);
	}

	public void getProjectList(){
		SharedPreferences user_token = getSharedPreferences("data", 0);
		String token = user_token.getString("appToken", "");
		Log.i("我拿到的token==>",token);

		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.getProjectList("Bearer  "+token);
		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();
					ProductListBean productListBean = gson.fromJson(string, ProductListBean.class);
					int code = productListBean.getCode();
					if (code==200){
						List<ProductListBean.DataBean> data = productListBean.getData();
						Message message=new Message();
						message.obj=data;
						message.what=1;
						handler.sendMessage(message);

					}else if (code==401){
						SharedPreferences sp=getSharedPreferences("data",0);
						SharedPreferences.Editor edit = sp.edit();
						edit.putString("appToken","");
						edit.commit();
						Intent intent = new Intent(ProductDetailListActivity.this, LoginActivity.class);
						startActivity(intent);
					}else {
						Message message=new Message();
						message.obj=productListBean.getMsg();
						message.what=2;
						handler.sendMessage(message);
					}

//					int code = loginBean.getCode();

				} catch (IOException e) {
				}
			}

			@Override
			public void onError(Throwable e) {
			}

			@Override
			public void onComplete() {

			}
		});
	}
	Handler handler=new Handler(){
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what){
				case 1:
					final List<ProductListBean.DataBean> list=(List<ProductListBean.DataBean>)msg.obj;
					productListAdapter = new ProductListAdapter(list, ProductDetailListActivity.this);
					xrv_productList.setAdapter(productListAdapter);
					productListAdapter.onClick(new PiCiListAdapter.JieKou() {
						@Override
						public void onClick(int pos) {
							Log.i("我点击了","1111111111");
//							configView.setPId(currentProduct.getId());
//				configView.setPName(currentProduct.getName());
//				configView.setPNid(currentProduct.getNid());
							ProductListBean.DataBean dataBean=new ProductListBean.DataBean();
							dataBean.setId(list.get(pos).getId());
							dataBean.setProductName(list.get(pos).getProductName());
							dataBean.setCompanyId(list.get(pos).getCompanyId());
					Intent intent = new Intent();
//					intent.putExtra("choicedProduct", list.get(pos).toString());
					intent.putExtra("choicedProduct", dataBean);
					setResult(choiceProductResultCode,intent);
					finish();
//					finishWithResult(choiceProductResultCode, intent);
						}
					});

					break;
				case 2:
					String str=(String) msg.obj;
					Toast.makeText(ProductDetailListActivity.this,str,Toast.LENGTH_LONG).show();
					break;
			}
		}
	};
}
