package com.example.cici.voice;

import java.util.Calendar;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.text.TextUtils;
import android.widget.TextView;
import android.widget.Toast;
import android.util.Log;
import android.widget.DatePicker;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;

import com.bumptech.glide.Glide;
import com.example.cici.voice.R;
import com.example.cici.bean.User;
import com.example.cici.utils.ImageLoader;
import com.example.cici.utils.TimeCountUtil;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.ninegrid.ImageInfo;

import java.io.File;
import java.util.ArrayList;

import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UploadFileListener;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

public class RegisterActivity extends AppCompatActivity implements  View.OnClickListener{
    private EditText reg_user,reg_pasd;
    String name,password,male,famale,birthday;
    private String head_url_res = "";//获得后的头像url
    private ImageView userIcon;
    private ArrayList<ImageItem> imageItems;
    private EditText edit_phone;
    private EditText edit_cord;
    private EditText editPwd;
    private EditText editName;
    private TextView now;
    private Button btn_getCord;
    private Button btn_register;
    private RadioButton mMaleRb;
    private RadioButton mFamaleRb;
    private String phone_number;
    private String cord_number;
    EventHandler eventHandler;
    private TimeCountUtil mTimeCountUtil;
    private int time=60;
    private boolean flag=true;
    private TextView tvShowDialog;
    private Calendar cal;
    private int year,month,day;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.regist);
        getDate();

        getId();

        mTimeCountUtil = new TimeCountUtil(btn_getCord, 60000, 1000);
        eventHandler = new EventHandler() {
            public void afterEvent(int event, int result, Object data) {
                Message msg=new Message();
                msg.arg1=event;
                msg.arg2=result;
                msg.obj=data;
                handler.sendMessage(msg);
            }
        };

        SMSSDK.registerEventHandler(eventHandler);

    }


    private void getDate() {
        cal=Calendar.getInstance();
        year=cal.get(Calendar.YEAR);       //获取年月日时分秒
        Log.i("wxy","year"+year);
        month=cal.get(Calendar.MONTH);   //获取到的月份是从0开始计数
        day=cal.get(Calendar.DAY_OF_MONTH);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        SMSSDK.unregisterEventHandler(eventHandler);
    }

    /**
     * 使用Handler来分发Message对象到主线程中，处理事件
     */
    Handler handler=new Handler()
    {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int event=msg.arg1;
            int result=msg.arg2;
            Object data=msg.obj;
            if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                if(result == SMSSDK.RESULT_COMPLETE) {
                    boolean smart = (Boolean)data;
                    if(smart) {
                        Toast.makeText(getApplicationContext(),"该手机号已经注册过，请重新输入",
                                Toast.LENGTH_LONG).show();
                        edit_phone.requestFocus();
                        return;
                    }
                }
            }
            if(result==SMSSDK.RESULT_COMPLETE)
            {

                if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                    Toast.makeText(getApplicationContext(), "验证码输入正确",
                            Toast.LENGTH_LONG).show();
                    changeHead();
                }
            }
            else
            {
                if(flag)
                {
                    btn_getCord.setVisibility(View.VISIBLE);
                    Toast.makeText(getApplicationContext(),"验证码获取失败请重新获取", Toast.LENGTH_LONG).show();
                    edit_phone.requestFocus();
                }
                else
                {
                    Toast.makeText(getApplicationContext(),"验证码输入错误", Toast.LENGTH_LONG).show();
                }
            }

        }

    };
    private void getId()
    {
        userIcon = findViewById(R.id.reg_head);
        userIcon.setOnClickListener(this);
        edit_phone=findViewById(R.id.editPhone);
        edit_cord=findViewById(R.id.editCode);
        btn_getCord=findViewById(R.id.btnGetcord);
        btn_register=findViewById(R.id.btnRegist);
        editPwd =  findViewById(R.id.editPwd);
        editName=findViewById(R.id.editName);
        mMaleRb = findViewById(R.id.male);
        mFamaleRb = findViewById(R.id.famle);
        tvShowDialog= findViewById(R.id.tvShowDialog);
        tvShowDialog.setOnClickListener(this);
        btn_getCord.setOnClickListener(this);
        btn_register.setOnClickListener(this);
    }


    public void onClick(View v)
    {
        switch (v.getId())
        {
            case R.id.btnGetcord:
                if(judPhone())//去掉左右空格获取字符串
                {
                    mTimeCountUtil.start();
                    SMSSDK.getVerificationCode("86",phone_number);
                    edit_cord.requestFocus();
                }
                break;
            case R.id.btnRegist:
                if(judCord())
                {
                    SMSSDK.submitVerificationCode("86", phone_number, cord_number);
                }
                flag=false;
                break;
            case R.id.tvShowDialog:
                OnDateSetListener listener=new OnDateSetListener() {

                    @Override
                    public void onDateSet(DatePicker arg0, int year, int month, int day) {
                        tvShowDialog.setText(year+"-"+(++month)+"-"+day);      //将选择的日期显示到TextView中,因为之前获取month直接使用，所以不需要+1，这个地方需要显示，所以+1
                    }
                };
                DatePickerDialog dialog=new DatePickerDialog(RegisterActivity.this, 0,listener,year,month,day);//后边三个参数为显示dialog时默认的日期，月份从0开始，0-11对应1-12个月
                dialog.show();
                break;
            case R.id.reg_head:
                addHead();
                break;
            default:
                break;
        }
    }

    private boolean judPhone()
    {
        if(TextUtils.isEmpty(edit_phone.getText().toString().trim()))
        {
            Toast.makeText(RegisterActivity.this,"请输入您的电话号码",Toast.LENGTH_LONG).show();
            edit_phone.requestFocus();
            return false;
        }
        else if(edit_phone.getText().toString().trim().length()!=11)
        {
            Toast.makeText(RegisterActivity.this,"您的电话号码位数不正确",Toast.LENGTH_LONG).show();
            edit_phone.requestFocus();
            return false;
        }
        else
        {
            phone_number=edit_phone.getText().toString().trim();
            String num="[1][358]\\d{9}";
            if(phone_number.matches(num))
                return true;
            else
            {
                Toast.makeText(RegisterActivity.this,"请输入正确的手机号码",Toast.LENGTH_LONG).show();
                return false;
            }
        }
    }

    private boolean judCord()
    {
        judPhone();
        if(TextUtils.isEmpty(edit_cord.getText().toString().trim()))
        {
            Toast.makeText(RegisterActivity.this,"请输入您的验证码",Toast.LENGTH_LONG).show();
            edit_cord.requestFocus();
            return false;
        }
        else if(edit_cord.getText().toString().trim().length()!=4)
        {
            Toast.makeText(RegisterActivity.this,"您的验证码位数不正确",Toast.LENGTH_LONG).show();
            edit_cord.requestFocus();

            return false;
        }
        else
        {
            cord_number=edit_cord.getText().toString().trim();
            return true;
        }

    }

    /**
     * 添加头像哦
     */
    private void addHead() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new ImageLoader());
        imagePicker.setMultiMode(false);   //多选
        imagePicker.setSelectLimit(1);    //最多选择X张
        imagePicker.setCrop(true);       //不进行裁剪
        Intent intent = new Intent(RegisterActivity.this, ImageGridActivity.class);
        startActivityForResult(intent, 100);
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == 100) {
                ArrayList<ImageInfo> imageInfo = new ArrayList<>();
                imageItems = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                String[] filePaths = new String[imageItems.size()];
                filePaths[0] = imageItems.get(0).path;
                head_url_res = filePaths[0];
                Glide.with(RegisterActivity.this).load(head_url_res).into(userIcon);
            } else {
                toast("没有选择图片");
            }
        }
    }
    /*
       获取图片url然后上传
        */
    public void changeHead() {
        name =editName.getText().toString();
        password=editPwd.getText().toString();
        phone_number=edit_phone.getText().toString();
        birthday=tvShowDialog.getText().toString();
        male=mMaleRb.getText().toString();
        famale=mFamaleRb.getText().toString();
        final String[] filePaths = new String[imageItems.size()];
        for (int i = 0; i < imageItems.size(); i++) {
            filePaths[i] = imageItems.get(i).path;
            head_url_res = filePaths[0];
            toast("注册中请稍等...");
            final BmobFile bmobFile = new BmobFile(new File(head_url_res));
            bmobFile.uploadblock(new UploadFileListener() {
               @Override
               public void done(BmobException e) {
                   if (e==null){
                       User user = new User();
                       user.setUsername(name);
                       user.setPassword(password);
                       if(mMaleRb.isChecked()) user.setSex(male);
                       else user.setSex(famale);
                       user.setBirthday(birthday);
                       user.setPhone(phone_number);
                       user.setHead(bmobFile.getFileUrl());
                       user.signUp(new SaveListener<User>() {
                           @Override
                           public void done(User s, BmobException e) {
                               if(e==null){
                                   toast("注册成功:" +s.toString());
                                   Intent intent = new Intent();
                                   intent.setClass(RegisterActivity.this, MainActivity.class);
                                   startActivity(intent);
                                   finish();
                               }else{
                                   toast("注册失败，可能用户名已存在" );
                               }
                           }
                       });

                   }
               }
           });


        }

    }


    public void toast(String msg) {
        Toast.makeText(RegisterActivity.this, msg, Toast.LENGTH_SHORT).show();
    }
}
