package com.efounder.chat.activity;


import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;

import com.efounder.builder.base.data.EFDataSet;
import com.efounder.builder.base.data.EFRowSet;
import com.efounder.chat.R;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.http.GetHttpUtil;
import com.efounder.chat.model.Constant;
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.frame.utils.Constants;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;

import java.util.List;

import static com.efounder.frame.utils.Constants.CHAT_PASSWORD;
import static com.efounder.frame.utils.Constants.CHAT_USER_ID;
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;


/**
 * 修改自己的昵称，个性签名
 */
public class UpdatePersonalInfoActivity extends BaseActivity {
    User user;
    TextView recording_hint;
    TextView tv_title;//标题
    String type;//判断修改昵称还是 个性签名
    String value;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        type = getIntent().getStringExtra("type");

        user = WeChatDBManager.getInstance().getOneUserById(Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)));


        setContentView(R.layout.activity_update_nick);
        initView();


    }

    private void initView() {


        recording_hint = (TextView) findViewById(R.id.recording_hint);
        tv_title = (TextView) findViewById(R.id.tv_title);
        final EditText et_nick = (EditText) this.findViewById(R.id.et_nick);

        if (type.equals("nickName")) {
            tv_title.setText(R.string.chat_update_nick_name);
            value = user.getNickName();
        } else if (type.equals("sigNature")) {
            tv_title.setText(R.string.chat_personal_sign_name);
            recording_hint.setVisibility(View.INVISIBLE);
            if (user.getSigNature() != null) {
                value = user.getSigNature();
            } else {
                value = "";
            }

        }
        et_nick.setText(value);
        et_nick.setSelection(value.length());
        TextView tv_save = (TextView) this.findViewById(R.id.tv_save);
        tv_save.setVisibility(View.VISIBLE);
        tv_save.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                String newNick = et_nick.getText().toString().trim();
                //更改昵称
                if (type.equals("nickName")) {
                    if (newNick.equals("") || newNick.equals("0")) {
                        ToastUtil.showToast(UpdatePersonalInfoActivity.this, R.string.chat_nick_name_not_empty);
                        return;
                    }
                    if (newNick.length() > 20) {
                        ToastUtil.showToast(UpdatePersonalInfoActivity.this, R.string.chat_max_ten_chinese);
                        return;
                    }

                    updateIvnServer(newNick);
                    //更改签名
                } else if (type.equals("sigNature")) {
                    if (newNick == null || "".equals(newNick)) {
                        newNick = "";
                    }
                    updateSignNature(newNick);
                }
            }

        });

    }

    /**
     * 更改昵称
     *
     * @param newText
     */
    private void updateIvnServer(final String newText) {
        if (EnvironmentVariable.getProperty("LoginType", "").equals("0")) {
            showLoading(ResStringUtil.getString(R.string.chat_updateing));
            GetHttpUtil.updateMyselfInfo(this, "nickName", newText, new GetHttpUtil
                    .UpdateUserInfoCallBack() {


                @Override
                public void updateSuccess(boolean isSuccess) {
                    if (isSuccess) {
                        dismissLoading();
                        user.setNickName(newText);
                        WeChatDBManager.getInstance().insertUserTable(user);
                        ToastUtil.showToast(UpdatePersonalInfoActivity.this, R.string.chat_fix_nick_name_success);
                        UpdatePersonalInfoActivity.this.finish();
                    } else {
                        dismissLoading();
                        ToastUtil.showToast(UpdatePersonalInfoActivity.this, R.string.chat_fix_nick_name_fail);
                    }
                }
            });
        } else {
            new AsyncTask<Void, Void, JResponseObject>() {

                @Override
                protected void onPreExecute() {
                    showLoading(ResStringUtil.getString(R.string.chat_updateing_nick_name));
                    super.onPreExecute();
                }

                @Override
                protected JResponseObject doInBackground(Void... params) {

                    // TODO 调用后台接口，更换昵称
                    // Thread.sleep(2000);

                    JParamObject PO = JParamObject.Create();
                    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;

                    JResponseObject RO = null;
                    PO.SetValueByParamName("method", "changeNickName");
                    PO.SetValueByParamName("userId", EnvironmentVariable.getProperty(CHAT_USER_ID));
                    PO.SetValueByParamName("passWord", EnvironmentVariable.getProperty(CHAT_PASSWORD));
                    PO.SetValueByParamName("nickName", newText);
                    PO.SetValueByParamName("APPID", EnvironmentVariable.getProperty("APPID"));

                    PO.setEnvValue("DBNO", EnvironmentVariable.getProperty(KEY_SIGN));// 数据标示
                    PO.setEnvValue("DataBaseName", EnvironmentVariable.getProperty("DataBaseName"));// 数据标示
                    try {
                        // 连接服务器
                        String serverKey = EnvironmentVariable.getProperty("ServerKey");
                        RO = EAI.DAL.SVR(serverKey, PO);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    return RO;
                }

                @Override
                protected void onPostExecute(JResponseObject result) {
                   dismissLoading();
                    if (result != null) {

                        EFDataSet efDataSet = (EFDataSet) result
                                .getResponseObject();
                        List<EFRowSet> list = efDataSet.getRowSetArray();
                        if (list == null) {
                            return;
                        }

                        for (EFRowSet efRowSet : list) {
                            if (efRowSet.hasKey("result")) {
                                if (efRowSet.getString("result", "-1").equals("0")) {
                                    user.setNickName(newText);
                                    WeChatDBManager.getInstance().insertUserTable(user);
                                    ToastUtil.showToast(UpdatePersonalInfoActivity.this, R.string.chat_fix_sign_name_success);
                                    EnvironmentVariable.setProperty(Constants.KEY_NICK_NAME, newText);
                                    UpdatePersonalInfoActivity.this.finish();
                                }
                            } else {
                                ToastUtil.showToast(UpdatePersonalInfoActivity.this, R.string.chat_fix_sign_name_fail);
                            }

                        }


                    }

                }

            }.execute();
        }

    }

    /**
     * 更改签名
     *
     * @param newText
     */
    private void updateSignNature(final String newText) {
        showLoading(ResStringUtil.getString(R.string.chat_updateing));
        GetHttpUtil.updateMyselfInfo(this, "sign", newText, new GetHttpUtil
                .UpdateUserInfoCallBack() {


            @Override
            public void updateSuccess(boolean isSuccess) {
                if (isSuccess) {
                    dismissLoading();
                    user.setSigNature(newText);
                    WeChatDBManager.getInstance().insertUserTable(user);
                    ToastUtil.showToast(UpdatePersonalInfoActivity.this, R.string.chat_fix_sign_name_success);
                    UpdatePersonalInfoActivity.this.finish();
                } else {
                    dismissLoading();
                    ToastUtil.showToast(UpdatePersonalInfoActivity.this, R.string.chat_fix_sign_name_fail);
                }
            }
        });


    }

    @Override
    public void back(View view) {

        finish();
    }
}
