package com.lianxin.pubqq.main;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.RadioGroup.OnCheckedChangeListener;

import com.lianxin.pubqq.R;
import com.lianxin.panqq.common.BaseActivity;
import com.lianxin.panqq.common.Utils;
import com.lianxin.panqq.list.utils.AddressUtils;
import com.lianxin.panqq.client.entity.RegisterFor;
import com.lianxin.panqq.picker.AddressPickerDialog;
import com.lianxin.panqq.picker.ImagePickerDialog;
import com.lianxin.panqq.picker.ServipPickerDialog;
import com.lianxin.panqq.client.callback.netCallBack;
import com.lianxin.panqq.utils.CheckGetUtil;
import com.lianxin.panqq.utils.ImagesUtils;
import com.lianxin.panqq.utils.LoginUtil;
import com.lianxin.panqq.client.RegClient;
import com.lianxin.panqq.widget.CheckView;

//注册模块
public class RegisterActivity extends BaseActivity implements OnClickListener {
	private TextView txt_title;
	private ImageView img_back;
	private Button btn_register, btn_send;
	private RelativeLayout lay_image,lay_address;	
	private EditText txt_servip, txt_username, txt_password, txt_confirmpsw;	
	private EditText txt_age, txt_address, txt_sex, txt_image;
	private EditText txt_telenum;	
	private EditText txt_checkcode;		
	private ImageView img_user;	
	private ImageButton but_servip;	
	private int nImageid=-1,nAddress=0,nAge,nSex;	
    RadioGroup rag_sex;
    RadioButton rab_sex_male;
    RadioButton rab_sex_female;	
    CheckBox checkbox1;    
    private CheckView mMyView = null;  
    private String[] checkNum = new String[4];  //获取每次更新的验证码，可用于判断用户输入是否正确   
//	private MyCount mc;
	private RegisterFor reginfo;
	public static String bakServerip = "";
	public static String bakUsername = "";
	public static int regCount = 0;
    private static String tmpServip = "";
    
	@Override
	public void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_register);
		super.onCreate(savedInstanceState);
		
		initControl();
		initView();
		initData();
		setListener();		
	}

	protected void initControl() {

		img_back = (ImageView) findViewById(R.id.img_back);
//		img_back.setVisibility(View.VISIBLE);
		btn_register = (Button) findViewById(R.id.btn_register);
		txt_servip = (EditText) findViewById(R.id.tv_user_serverip);		
		txt_username = (EditText) findViewById(R.id.tv_user_nickname);
		img_user = (ImageView)findViewById(R.id.iv_user_image); 		
		txt_password = (EditText) findViewById(R.id.tv_user_password);
		txt_confirmpsw = (EditText) findViewById(R.id.tv_user_confirmpsw);
		txt_telenum = (EditText) findViewById(R.id.tv_user_telenum);	
		txt_checkcode = (EditText) findViewById(R.id.tv_user_checkcode);		
		txt_address = (EditText) findViewById(R.id.tv_user_address);		
		lay_image = (RelativeLayout) findViewById(R.id.rl_user_image);
		lay_address = (RelativeLayout) findViewById(R.id.rl_user_address);		
		txt_age = (EditText) findViewById(R.id.tv_user_age);
		but_servip = (ImageButton) findViewById(R.id.ImageButton01);
		checkbox1 = (CheckBox) findViewById(R.id.CheckBox08);		
		rag_sex=(RadioGroup)findViewById(R.id.rg_sex);
		rab_sex_male=(RadioButton)findViewById(R.id.rb_sex_male);
		rab_sex_female=(RadioButton)findViewById(R.id.rb_sex_female);
        
		rag_sex.setOnCheckedChangeListener(new OnCheckedChangeListener(){       	 
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                // TODO Auto-generated method stub
                if(checkedId==rab_sex_male.getId()){
                    Toast.makeText(RegisterActivity.this,"男", Toast.LENGTH_LONG).show();
                }
                if(checkedId==rab_sex_female.getId()){
                    Toast.makeText(RegisterActivity.this,"女", Toast.LENGTH_LONG).show();
                }                
            } 
        });	

		mMyView = (CheckView) findViewById(R.id.checkView);
		// 初始化验证码
		checkNum = mMyView.getValidataAndSetImage();
		mMyView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 重新初始化验证码
				checkNum = mMyView.getValidataAndSetImage();
			}
		});			
	
	}

	protected void initView() {

	}

	protected void initData() {
	    if(!TextUtils.isEmpty(bakServerip)){
	    	txt_servip.setText(bakServerip);
	    	return;
	    }
	    
		String strip = LoginUtil.getLastLoginServIP();
		if(strip=="")
			return;
		//serverip = strip;
		txt_servip.setText(strip);	    
	}

	protected void setListener() {

		img_back.setOnClickListener(this);
		btn_register.setOnClickListener(this);		
		lay_image.setOnClickListener(this);	
		but_servip.setOnClickListener(this);		
		lay_address.setOnClickListener(this); 
		txt_address.setOnClickListener(this);
		txt_servip.addTextChangedListener(new IpTextChange());	
	}

	public void onClick(View v) {
		int id = v.getId();
		if (id == R.id.img_back) {
			Utils.finish(RegisterActivity.this);
		} else if (id == R.id.btn_send) {
		} else if (id == R.id.btn_register) {
			getRegister();
		} else if (id == R.id.rl_user_image) {//修改头像
			change_image();
		} else if (id == R.id.rl_user_address) {//修改城市
			change_address();
		} else if (id == R.id.tv_user_address) {//修改城市
			change_address();
		} else if (id == R.id.ImageButton01) {
			new ServipPickerDialog(RegisterActivity.this, ServipPickerDialog.THEME_HOLO_LIGHT, 0,
					new ServipPickerDialog.OnServSetListener() {
						@Override
						public void onSelect(String servip, String servname) {
							txt_servip.setText(servip);
						}
					}).show();
		}
	}

	private void getRegister() {
		String serverip = txt_servip.getText().toString().trim();
		String userName = txt_username.getText().toString().trim();		
		String password = txt_password.getText().toString().trim();	
		String confirmpsw = txt_confirmpsw.getText().toString().trim();	
		String telenum = txt_telenum.getText().toString().trim();		
		if (TextUtils.isEmpty(serverip)){
			Utils.showShortToast(RegisterActivity.this, "请填写服务器ip地址！");	
			txt_servip.requestFocus();			
            return;
	    }
		if (TextUtils.isEmpty(userName)){
			Utils.showShortToast(RegisterActivity.this, "请填写用户名！");	
			txt_username.requestFocus();			
            return;
	    }
		if (TextUtils.isEmpty(password)){
			Utils.showShortToast(RegisterActivity.this, "请填写登录密码！");
			txt_password.requestFocus();			
            return;
	    }
		if (TextUtils.isEmpty(confirmpsw)){
			Utils.showShortToast(RegisterActivity.this, "请再次确认登录密码！");
			txt_confirmpsw.requestFocus();			
            return;
	    }		
		if (serverip.length() < 7){
			Utils.showShortToast(RegisterActivity.this, "错误的服务器ip地址！");	
			txt_servip.requestFocus();			
            return;
	    }
		if (userName.length() < 3){
			Utils.showShortToast(RegisterActivity.this, "用户名至少要3个英文字符或者两个汉字！");	
			txt_username.requestFocus();			
            return;
	    }
		if (password.length() < 5){
			Utils.showShortToast(RegisterActivity.this, "错误的用户密码！");	
			txt_password.requestFocus();			
            return;
	    }
		if (!password.equals(confirmpsw)){
			Utils.showShortToast(RegisterActivity.this, "两次输入的密码不一致！");	
			txt_confirmpsw.requestFocus();			
            return;
	    }
		if (regCount > 10){
			Utils.showShortToast(RegisterActivity.this, "不能恶意疯狂注册！");	
			txt_username.requestFocus();			
            return;
	    }		
		if (userName.equals(bakUsername)){
			Utils.showShortToast(RegisterActivity.this, "不能重复注册！");	
			txt_username.requestFocus();			
            return;
	    }	
        nAge = Integer.parseInt(txt_age.getText().toString().trim()); // 获取年龄
		if (nAge < 0 || nAge > 120 ){
			Utils.showShortToast(RegisterActivity.this, "请输入正确的年龄！");	
			txt_age.requestFocus();			
            return;
	    }
		if (nImageid < 0 || nImageid > 80 ){
			Utils.showShortToast(RegisterActivity.this, "请选择你的默认头像！");			
            return;
	    }
		if (nAddress <= 0 || nAddress > 720 ){
			Utils.showShortToast(RegisterActivity.this, "请选择你的所在地区！");			
            return;
	    }		
		int checkedRadioButtonId = rag_sex.getCheckedRadioButtonId();
		if (checkedRadioButtonId == R.id.rb_sex_female) {
			nSex = 2;
		} else if (checkedRadioButtonId == R.id.rb_sex_male) {
			nSex = 1;
		} else {
			Utils.showShortToast(RegisterActivity.this, "请选择性别！");
			txt_age.requestFocus();
			return;
		}
		boolean isTeleLog = false;
		if( checkbox1.isChecked() ) {
			isTeleLog = true;
			if (telenum.length() != 11){
				Utils.showShortToast(RegisterActivity.this, "错误的手机号码！");	
				txt_telenum.requestFocus();			
	            return;
		    }		
		}else{
			telenum = "";
		}
        String userInput = txt_checkcode.getText().toString();
        if(!CheckGetUtil.checkNum(userInput, checkNum)){
			Utils.showShortToast(RegisterActivity.this, "验证码不对！");	
			txt_checkcode.requestFocus();			
            return;
	    }
		// 重新初始化验证码
		checkNum = mMyView.getValidataAndSetImage();       
		reginfo = new RegisterFor();		
		reginfo.m_strServip = serverip;// 服务器IP  
    	reginfo.m_strName = userName;// 用户登录ID
		reginfo.m_strPassword = password;// 用户登录密码
		if (telenum.length() == 11){
			reginfo.m_strTeleNum = telenum;// 用户登录密码
	    }		
		reginfo.imageid = nImageid;// 默认头像
		reginfo.age = nAge;// 年龄
		reginfo.sex = nSex;// 性别		
		reginfo.address = nAddress;// 地址		
		getLoadingDialog("正在注册...  ").show();
		btn_register.setEnabled(false);

		RegClient.regServer(this,reginfo,  new netCallBack() {// 回调	
			@Override
			public void onError(int code, final String message) {
				runOnUiThread(new Runnable() {
					public void run() {
						getLoadingDialog("正在注册...").dismiss();
						Utils.showLongToast(RegisterActivity.this, message);
						btn_register.setEnabled(true); 						
					}
				});			
			}

			/*@Override
			public void onSuccess(int code, Object contex) {
			}*/

			@Override
			public void onFailure(final int errorCode, final String message) {
			}

			@Override
			public void onSuccess(int code, String retMessage) {	
				runOnUiThread(new Runnable() {
					public void run() {
						getLoadingDialog("正在注册...").dismiss();		
						String str = "注册成功,\n你的用户号码是" + reginfo.userid + ",\n密码是"+reginfo.m_strPassword+",\n请牢记!\n";  
						Utils.showLongToast(RegisterActivity.this, str);
						bakServerip = reginfo.m_strServip;	
						bakUsername = reginfo.m_strName;
						regCount++;
            		    btn_register.setEnabled(true); 
            		    int userId = reginfo.userid;
            		    LoginUtil.saveLastLoginUser(bakServerip, ""+userId);
					}
				});	
			     //延迟一秒
                try {
                    Thread.sleep( 1000 );
            	//	btn_register.setEnabled(true);                 
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            
			}
		});
		txt_telenum.setText("");
		btn_register.setEnabled(true); 		
	}
	/**
	 * 更改头像
	 */
	public void change_image(){

		new ImagePickerDialog(this,
				ImagePickerDialog.THEME_HOLO_LIGHT,
				new ImagePickerDialog.OnImageSetListener() {
					@Override
					public void onImageSelect(int imageid) {
						nImageid = imageid;
						img_user.setImageResource(ImagesUtils.images[imageid]); 						
					}
				}).show();		
    
	}	
	/**
	 * 更改地址
	 */
	public void change_address(){	
		new AddressPickerDialog(RegisterActivity.this,
				AddressPickerDialog.THEME_HOLO_LIGHT,
				new AddressPickerDialog.OnAddressSetListener() {
					@Override
					public void onAddressSelect(int address) {
						nAddress = address;
						txt_address.setText(AddressUtils.getAddress(address));						
					}
				}).show();	       
	}

	class IpTextChange implements TextWatcher {

		@Override
		public void afterTextChanged(Editable arg0) {
            String str = arg0.toString(); 
            if( str.length() == 0 || str.equals(tmpServip)) return; 
            tmpServip = checkIp(str); 
            txt_servip.setText(tmpServip); 
            txt_servip.setSelection(tmpServip.length()); 
		}

		@Override
		public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {

		}

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

		}
	}	
    private static String checkIp(String ip){ 
        String validStr = ".0123456789"; 
        StringBuffer sb = new StringBuffer(); 
        int i = 0; 
 
        for( i = 0; i < ip.length(); i++){ 
            if( validStr.indexOf(ip.charAt(i)) >= 0 ) sb.append(ip.charAt(i)); 
        } 
        if( sb.toString().length() == 0 ) return ""; 
 
        String newIP = ""; 
        String[] arrIp = sb.toString().split("\\."); 
        for( i = 0; i < arrIp.length && i < 4 ; i++){ 
            if( arrIp.equals("")) break;            
            if( i > 0 && i < 4 ) newIP += "."; 
            if( arrIp[i] == null ||arrIp[i].equals("") ){ 
            	//newIP += arrIp[i];
            }else if( Integer.parseInt(arrIp[i]) > 255 ){ 
                    newIP += String.format("%d", Integer.parseInt(arrIp[i])/10); 
            }else{             	
                newIP += arrIp[i]; 
            } 
      
        } 
        //if( i < 4 && sb.toString().endsWith("-")) newIP += "."; 
        if( i < 4 && sb.toString().endsWith(".")) newIP += ".";         
        return newIP; 

    } 
}
