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

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 android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import cn.net.caoyao.cpzshandset.R;
import cn.net.caoyao.cpzshandset.bean.LoginBean;
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.LoginConstact;
import cn.net.caoyao.cpzshandset.service.presenter.LoginConstact.Presenter;
import cn.net.caoyao.cpzshandset.ui.activity.base.BaseActivity;
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.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class LoginActivity extends BaseActivity implements LoginConstact.View, OnClickListener{

	private LoginConstact.Presenter presenter;
	private TextView tv_update_config_info,tv_update_date_tips_info;
	private EditText et_login_account,et_login_pwd;
	private View btn_login_submit;
	private Context context;
	private MyToast myToast;
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (myToast != null) {
			myToast.cancel();
		}
	}
	@Override
	public int loadView() {
		context = this;
		myToast = new MyToast(context);
		return R.layout.activity_login;
	}

	@Override
	public void initTitleView() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void initView() {
		tv_update_config_info = (TextView) findViewById(R.id.tv_update_config_info);		
		et_login_account = (EditText) findViewById(R.id.et_login_account);
		et_login_pwd = (EditText) findViewById(R.id.et_login_pwd);
		btn_login_submit = findViewById(R.id.btn_login_submit);
		tv_update_date_tips_info = (TextView) findViewById(R.id.tv_update_date_tips_info);
	}

	@Override
	public void initPresenter() {
		presenter = createService.createLoginPresenter(cacheG, context, this, getIntent());		
	}

	@Override
	public void setListener() {
		tv_update_config_info.setOnClickListener(this);
		btn_login_submit.setOnClickListener(this);
	}

	@Override
	public void initData() {
		
	}

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

	@Override
	public void startAcForResult(int reqCode, Intent intent) {
		// TODO Auto-generated method stub
		
	}

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

	@Override
	public void finishPage() {
		finish();
	}

	@Override
	public void setUpdateBtnVisibility(int visibility) {
		if(tv_update_config_info == null) return;
		tv_update_config_info.setVisibility(visibility);		
	}

	@Override
	public void setBottomTipsVisibility(int visibility) {
		if(tv_update_date_tips_info == null) return;
		tv_update_date_tips_info.setVisibility(visibility);
	}

	@Override
	public void setUpdateBtnStr(String btnUpdateStr) {
		if(tv_update_config_info == null || btnUpdateStr == null) return;
		tv_update_config_info.setText(btnUpdateStr+"");
	}

	@Override
	public void setBottomTipsStr(String bottomTips) {
		if(tv_update_date_tips_info == null || bottomTips == null) return;
		tv_update_date_tips_info.setText(bottomTips+"");
	}

	@Override
	public String getAccountStr() {
		return et_login_account != null ? et_login_account.getText().toString().trim():"";
	}

	@Override
	public void setAccountStr(String account) {
		if(et_login_account == null || account == null) return;
		et_login_account.setText(account);
	}

	@Override
	public String getPwdStr() {
		return et_login_pwd != null ? et_login_pwd.getText().toString().trim() : "";
	}

	@Override
	public void setPwdStr(String pwd) {
		if(et_login_pwd == null || pwd == null) return;
		et_login_pwd.setText(pwd+"");
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tv_update_config_info:
			if (presenter != null) {
				presenter.updateBtnClick();
			}
			break;

		case R.id.btn_login_submit:
			final String account = getAccountStr();
			final String pwd = getPwdStr();
			if (StringUtils.isEmpty(account)) {
			     showMsgToast("账号不能为空！", Toast.LENGTH_SHORT);
				return;
			}
			if (StringUtils.isEmpty(pwd)) {
				showMsgToast("密码不能为空！", Toast.LENGTH_SHORT);
				return;
			}
			new Thread(new Runnable() {
				@Override
				public void run() {
					loginButton(account,pwd);
				}
			}).start();
			break;
		}
	}
	public void loginButton(String principalPhone,String password){
		Map<String,String> map=new HashMap<>();
		map.put("username",principalPhone);
		map.put("password",password);
		Gson gson=new Gson();
		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.getWeChatLogin(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();
					Gson gson = new Gson();
					LoginBean loginBean = gson.fromJson(string, LoginBean.class);
					int code = loginBean.getCode();
					if (code==200){
						SharedPreferences sp=getSharedPreferences("data",0);
						SharedPreferences.Editor edit = sp.edit();
						edit.putString("appToken",loginBean.getData().getToken());
						edit.putString("companyName",loginBean.getData().getCompanyName());
						edit.commit();
						Log.i("====>",loginBean.getData().getCompanyName());
						Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
						startActivity(intent);
					}else {
						Message message=new Message();
						message.what=1;
						message.obj = loginBean.getMsg();
						handler.sendMessage(message);
					}
				} 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:
					String msgString = (String) msg.obj;
					Toast.makeText(LoginActivity.this,msgString,Toast.LENGTH_LONG).show();
					break;
			}
		}
	};
}
