package com.efounder.chat.activity;


import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.efounder.builder.base.data.EFDataSet;
import com.efounder.builder.base.data.EFRowSet;
import com.efounder.chat.R;
import com.efounder.chat.manager.PictureAndCropManager;
import com.efounder.chat.model.Constant;
import com.efounder.chat.utils.ImageUtil;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.eai.EAI;
import com.efounder.eai.data.JParamObject;
import com.efounder.eai.data.JResponseObject;
import com.efounder.form.util.CloudUtil;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;
import com.utilcode.util.UriUtils;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_ADDRESS;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_HTTP_TYPE;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_PATH;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_PORT;
import static com.efounder.frame.utils.Constants.KEY_SIGN;
import static com.efounder.frame.utils.NetStateBroadcastReceiver.isNetActive;

public class RegisterActivity extends Activity implements OnClickListener {

    private String nickName;
    private String avatar;
    private String userName;
    private String userPassWord;
    private String userPassWordConfirm;
    private String sex;
    private ImageView iv_hideImage;
    private ImageView iv_showImage;
    private EditText et_userPassWord;
    private EditText et_userPassWord_confirm;
    private ImageView iv_avater;
    private TextView tv_total;
    private EditText et_userName;
    private String picturePath;//图片在相册中的路径
    private String pictureUrlPath;//图片在网络上的路径
    private String imageName;//图片名称
    private static final int PHOTO_REQUEST_TAKEPHOTO = 1;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
    private static final int PHOTO_REQUEST_CUT = 3;// 结果
    private static final int UPDATE_FXID = 4;// 结果
    private static final int UPDATE_NICK = 5;// 结果
    private PictureAndCropManager pictureAndCropManager;//拍照裁剪

    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.fragment_register);
        pictureAndCropManager = new PictureAndCropManager(this);
        ImageView iv_backImage = (ImageView) findViewById(R.id.iv_back);
        iv_backImage.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                RegisterActivity.this.finish();
            }
        });

        tv_total = (TextView)findViewById(R.id.tv_title);
        tv_total.setText(R.string.wrchatview_registered);

        iv_avater = (ImageView) findViewById(R.id.iv_photo);
        iv_avater.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO 打开系统相册，选择头像
//                int PICTURE = 0;
//                Intent picture = new Intent(Intent.ACTION_PICK, android.provider.MediaStore
//                        .Images.Media.EXTERNAL_CONTENT_URI);
//                startActivityForResult(picture, PICTURE);
                getNowTime();
                imageName = getNowTime() + ".png";
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
            }
        });

        et_userName = (EditText) findViewById(R.id.et_username);
        et_userPassWord = (EditText) findViewById(R.id.et_password);
        et_userPassWord_confirm = (EditText) findViewById(R.id.et_password_corfirm);

        String usernamestring = getIntent().getStringExtra("userName");
        String passwordstring = getIntent().getStringExtra("password");


        if (usernamestring != null && !"".equals(usernamestring)) {
            et_userName.setText(usernamestring);
        }
        if (passwordstring != null && !"".equals(passwordstring)) {
            et_userPassWord.setText(passwordstring);
        }

        Button btn = (Button) findViewById(R.id.btn_register);
        iv_hideImage = (ImageView) findViewById(R.id.iv_hide);
        iv_showImage = (ImageView) findViewById(R.id.iv_show);

        iv_hideImage.setOnClickListener(this);
        iv_showImage.setOnClickListener(this);

        btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText et_nickName = (EditText) findViewById(R.id.et_usernick);
                RadioButton rb_sex = (RadioButton) findViewById(R.id.rb_male);

                nickName = et_nickName.getText().toString();
                avatar = iv_avater.getDrawable().toString();
                userName = et_userName.getText().toString();
                userPassWord = et_userPassWord.getText().toString();
                userPassWordConfirm = et_userPassWord_confirm.getText().toString();
                sex = rb_sex.isChecked() ? "男" : "女";

                if ((nickName == null || "".equals(nickName.trim())) || (userName == null || ""
                        .equals(userName.trim())) || (userPassWord == null || "".equals
                        (userPassWord.trim())) || (userPassWordConfirm == null || "".equals
                        (userPassWordConfirm.trim()))) {
                    Toast.makeText(RegisterActivity.this, R.string.wrchatview_nickname_registered, Toast.LENGTH_LONG)
                            .show();
                    return;
                }
                if (!userPassWord.equals(userPassWordConfirm)) {
                    Toast.makeText(RegisterActivity.this, R.string.wrchatview_password_not_same, Toast.LENGTH_LONG)
                            .show();
                    return;
                }

                final JParamObject PO = JParamObject.Create();
//                EAI.Protocol = "https";
//                EAI.Server = "pgyd.zyof.com.cn";
//                EAI.Port = "443";// "8085";
//                EAI.Path = "EnterpriseServer";// "EnterpriseServer";
//                EAI.Service = "Android";
                EAI.Protocol = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_HTTP_TYPE);

                EAI.Server = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_ADDRESS);
                EAI.Port = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_PORT);// "8085";
                EAI.Path = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_PATH);// "EnterpriseServer";
                EAI.Service = Constant.EAI_SERVICE;
                EAI.Protocol = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_HTTP_TYPE);

//                EAI.Server = "192.168.253.17";
//                EAI.Port = "8080";
//                EAI.Path = "ESTMobile";
//                EAI.Service = "Android";


                PO.SetValueByParamName("method", "sign");
                PO.SetValueByParamName("userName", userName);
                PO.SetValueByParamName("userPassWord", userPassWord);
                PO.SetValueByParamName("nikeName", nickName);
                PO.SetValueByParamName("sex", sex);
                PO.SetValueByParamName("APPID", EnvironmentVariable.getProperty("APPID"));
                PO.SetValueByParamName("avatar", pictureUrlPath);

                PO.setEnvValue("DBNO", EnvironmentVariable.getProperty(KEY_SIGN));// 数据标示
                PO.setEnvValue("DataBaseName", EnvironmentVariable.getProperty("DataBaseName"));// 数据标示



                new AsyncTask<String, Integer, String>() {
                    private ProgressDialog dialog;

                    @Override
                    protected void onPreExecute() {
                        dialog = new ProgressDialog(RegisterActivity.this);
                        dialog.setMessage(ResStringUtil.getString(R.string.wrchatview_registering));
                        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                        dialog.show();
                        super.onPreExecute();
                    }

                    @Override
                    protected String doInBackground(String... params) {
                        //调用后台接口，注册
                        try {
                            //连接服务器
                            String serverKey = EnvironmentVariable.getProperty("ServerKey");
                            JResponseObject RO = EAI.DAL.SVR(serverKey, PO);
                            //解析RO，是否注册成功
                            if (RO == null) {
                                return "RO_NULL";
                            } else {
                                EFDataSet dataSet = (EFDataSet) RO.getResponseObject();
                                if (dataSet.getRowCount() <= 0) {
                                    return "RO_NULL";
                                }
                                EFRowSet rowSet = dataSet.getRowSet(0);
                                Map<String, Object> map = new HashMap<String, Object>();
                                map = rowSet.getDataMap();
                                String result = (String) map.get("tip");
                                return result;
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                            return "error";
                        }
                    }

                    @Override
                    protected void onPostExecute(String result) {
                        if (dialog.isShowing()) {

                            dialog.dismiss();
                        }
                        if ("注册成功".equals(result)) {
                            Toast.makeText(RegisterActivity.this, R.string.wrchatview_registered_success, Toast.LENGTH_LONG).show();
                            Intent intent = getIntent();
                            intent.putExtra("name", userName);
                            intent.putExtra("password", userPassWord);
                            setResult(RESULT_OK, intent);
                            RegisterActivity.this.finish();
                        }
                        if ("您已注册。".equals(result)) {
                            Toast.makeText(RegisterActivity.this, R.string.wrchatview_you_registered, Toast
                                    .LENGTH_LONG).show();
                            return;
                        }
                        if ("RO_NULL".equals(result)) {
                            Toast.makeText(RegisterActivity.this, R.string.wrchatview_server_request_fail, Toast
                                    .LENGTH_LONG).show();
                            return;
                        }
                        if ("error".equals(result)) {
                            Toast.makeText(RegisterActivity.this, R.string.wrchatview_app_error, Toast
                                    .LENGTH_LONG).show();
                            return;
                        }
                    }
                }.execute();
            }
        });
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();

        if (id == R.id.iv_hide) {
            iv_hideImage.setVisibility(ImageView.INVISIBLE);
            iv_showImage.setVisibility(ImageView.VISIBLE);
            et_userPassWord.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            iv_hideImage.setVisibility(ImageView.VISIBLE);
            iv_showImage.setVisibility(ImageView.INVISIBLE);
            et_userPassWord.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }
    }

//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == 0 && resultCode == Activity.RESULT_OK && null != data) {
//            Uri selectedImage = data.getData();
//            cropRawPhoto(selectedImage);
//            String[] filePathColumns = {MediaStore.Images.Media.DATA};
//            Cursor c = this.getContentResolver().query(selectedImage, filePathColumns, null,
//                    null, null);
//            c.moveToFirst();
//            int columnIndex = c.getColumnIndex(filePathColumns[0]);
//            picturePath = c.getString(columnIndex);
//            c.close();
////	      //获取图片并显示
//            // iv_avater.setImageURI(selectedImage);
//        } else if (requestCode == 1 && null != data && resultCode == Activity.RESULT_OK) {
//                Bundle extras = data.getExtras();
//                if (extras != null) {
//                    Bitmap photo = extras.getParcelable("data");
//                    iv_avater.setImageBitmap(photo);
//                    File file = new File(picturePath);
//                    if (file.exists()) {
//                        try {
//                            ImageUtil.saveFile(photo, file.getName());
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//                        String avatarPath = ImageUtil.chatpath + ImageUtil.
//                                getFileName(ImageUtil.chatpath + file.getName() + ".pic");
//                        Log.i("剪裁后头像文件路径：", avatarPath);
//                        QiNiuUtil.getQiNiuRes(avatarPath, new QiNiuUtil.UpLoadListener() {
//                            @Override
//                            public void getHttpUrl(Boolean isSuccess, String url) {
//                                if (isSuccess) {
//                                    Log.i("RegisterActivity", "---头像在七牛服务器上的路径:" + url);
//                                    pictureUrlPath = url;
//                                } else {
//                                    pictureUrlPath = "http://oap8mw8pg.bkt.clouddn" +
//                                            ".com/FpDdVce3uiMlxVTY0IGDWYnZosUZ";
//                                }
//
//                            }
//                        });
//                    }
//
//                }
//            }
//    }
//


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PHOTO_REQUEST_TAKEPHOTO:
                    pictureAndCropManager.startPhotoZoom(
                            UriUtils.getUriForFile((new File(ImageUtil.chatpath, imageName))),
                            480);
                    picturePath = ImageUtil.chatpath + imageName;

                    break;

                case PHOTO_REQUEST_GALLERY:
                    if (data != null)
                        pictureAndCropManager.startPhotoZoom(data.getData(), 480);
                    break;

                case PHOTO_REQUEST_CUT:
                    Bitmap bitmap = BitmapFactory.decodeFile(ImageUtil.chatpath
                            + imageName);

                    // File file = new File(picturePath);
                    //  if (file.exists()) {
                    try {
                        ImageUtil.saveFile(bitmap, imageName);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    String avatarPath = ImageUtil.chatpath + ImageUtil.
                            getFileName(ImageUtil.chatpath + imageName + ".pic");
                    final Bitmap bitmap1 = BitmapFactory.decodeFile(ImageUtil.chatpath
                            + imageName + ".pic");

                    Log.i("剪裁后头像文件路径：", avatarPath);
                    if (!isNetActive()) {
                        ToastUtil
                                .showToast(RegisterActivity.this, R.string.wrchatview_online_error_please);

                        return;
                    }




                    CloudUtil.getCloudRes(avatarPath, new CloudUtil.UpLoadListenerWithProgress() {
                        @Override
                        public void getHttpUrl(Boolean isSuccess, String url) {
                            if (isSuccess) {
                                pictureUrlPath = url;
                                pictureUrlPath.trim();
                            } else {
                                pictureUrlPath = "";
                            }
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    iv_avater.setImageBitmap(bitmap1);
                                }
                            });
                        }

                        @Override
                        public void getHttpProgress(int progress) {

                        }
                    });


//                    try {
//                        //todo 普联云盘上传
//                        PansoftCloudUtil.getCloudRes(avatarPath, new PansoftCloudUtil.UpLoadListener() {
//                            @Override
//                            public void getHttpUrl(Boolean isSuccess, String url) {
//                                if (isSuccess) {
//
//                                    Log.i("RegisterActivity", "---头像在普联云盘服务器上的路径:" + url);
//                                    pictureUrlPath = url;
//                                    pictureUrlPath.trim();
//
//
//                                } else {
//                                    pictureUrlPath = "http://oap8mw8pg.bkt.clouddn" +
//                                            ".com/FpDdVce3uiMlxVTY0IGDWYnZosUZ";
//
//                                }
//                            }
//                        });
//                        //todo 七牛上传
//
////                        QiNiuUtil.getQiNiuRes(avatarPath, new QiNiuUtil.UpLoadListener() {
////                            @Override
////                            public void getHttpUrl(Boolean isSuccess, String url) {
////                                if (isSuccess) {
////
////                                    Log.i("RegisterActivity", "---头像在七牛服务器上的路径:" + url);
////                                    pictureUrlPath = url;
////                                    pictureUrlPath.trim();
////
////
////                                } else {
////                                    pictureUrlPath = "http://oap8mw8pg.bkt.clouddn" +
////                                            ".com/FpDdVce3uiMlxVTY0IGDWYnZosUZ";
////
////                                }
////
////                            }
////                        });
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
                    // }


                    break;

            }
            super.onActivityResult(requestCode, resultCode, data);

        }
    }

    private String getNowTime() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("MMddHHmmssSS");
        return dateFormat.format(date);
    }

}
