package com.efounder.chat.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
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.adapter.AddFriendsUserListAdapter;
import com.efounder.chat.adapter.AddGroupUserListAdapter;
import com.efounder.chat.adapter.AddPublicUserListAdapter;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.http.GetHttpUtil;
import com.efounder.chat.model.AddFriendUser;
import com.efounder.chat.model.Constant;
import com.efounder.chat.model.Group;
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.mobilecomps.contacts.User;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;

import org.json.JSONException;

import java.util.ArrayList;
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.NetStateBroadcastReceiver.isNetActive;

/**
 * Created by will on 17-1-9.
 */

public class AddAllTypesFriendsPG extends BaseActivity {

    private String TAG = "AddAllTypesFriendsPG";
    private String searchKeyword;
    private int friendType;//朋友类型
    private static final int TYPE_PERSON = 0;
    private static final int TYPE_GROUP = 1;
    private static final int TYPE_OFFICAL_ACCOUNT = 2;
    private String hint;//搜索提示
    private List<User> accountUsers = new ArrayList<>();
    private List<Group> groupUsers = new ArrayList<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addfriends_two);
        final InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        final RelativeLayout re_search = (RelativeLayout) findViewById(R.id.re_search);
        final TextView tv_search = (TextView) re_search.findViewById(R.id.tv_search);
        final EditText et_search = (EditText) findViewById(R.id.et_search);

        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        if (bundle!=null){
            friendType = bundle.getInt("type",0);
        }
        switch (friendType){
            case TYPE_PERSON:
                hint = ResStringUtil.getString(R.string.wrchatview_search_username);
                break;
            case TYPE_GROUP:
                hint = getResources().getString(R.string.wechatview_serach_hint_group);
                break;
            case TYPE_OFFICAL_ACCOUNT:
                hint = ResStringUtil.getString(R.string.wrchatview_search_app_number);
                break;
        }
        et_search.setHint(hint);

        et_search.addTextChangedListener(new TextWatcher() {
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0) {
                    re_search.setVisibility(View.VISIBLE);
                    tv_search.setText(et_search.getText().toString().trim());
                } else {
                    re_search.setVisibility(View.GONE);
                    tv_search.setText("");
                }
            }
            public void beforeTextChanged(CharSequence s, int start, int count,int after) {

            }
            public void afterTextChanged(Editable s) {

            }
        });
        re_search.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(),InputMethodManager.SHOW_FORCED);
                searchKeyword = et_search.getText().toString().trim();
                if (searchKeyword.equals("")) {
                    return;
                }
                if (!isNetActive()) {//无网络
                    ToastUtil.showToast(AddAllTypesFriendsPG.this, ResStringUtil.getString(R.string.network_anomalies));
                    return;
                }

                switch (friendType){
                    case TYPE_PERSON:
                        new AddPersonalFriendTask().execute();
                        break;
                    case TYPE_GROUP://搜索聊天群
                        try {
                            GetHttpUtil.searchGroup(AddAllTypesFriendsPG.this, searchKeyword, new GetHttpUtil.SearchGroupCallback() {
                                @Override
                                public void getGroupSuccess(List<Group> groups, boolean isSuccess) {
                                    if (isSuccess){
                                        if (groups.size()==0){
                                            Toast.makeText(AddAllTypesFriendsPG.this, ResStringUtil.getString(R.string.wrchatview_no_match_user), Toast.LENGTH_SHORT).show();
                                        }else {
                                            groupUsers.addAll(groups);
                                            generateGroupListView(groups);
                                        }
                                    }
                                }
                            });
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                        break;
                    case TYPE_OFFICAL_ACCOUNT://搜索公众号
                        try {
                            GetHttpUtil.searchPublicNumber(AddAllTypesFriendsPG.this, searchKeyword, new GetHttpUtil.SearchPublicNumberCallBack() {

                                @Override
                                public void getPublicSuccess(List<User> users, boolean isSuccess) {
                                    if (isSuccess) {
                                        if (users.size() == 0) {
                                            Toast toast = Toast.makeText(AddAllTypesFriendsPG.this, ResStringUtil.getString(R.string.wrchatview_no_match_user), Toast.LENGTH_SHORT);
                                            toast.setGravity(Gravity.CENTER, 0, 0);
                                            toast.show();

                                            return;
                                        }
                                        accountUsers.addAll(users);
                                        generatePublicAccountListView(accountUsers);
                                    }
                                }
                            });

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        break;
                }

            }

        });

    }

    /**
     * 添加个人好友
     */
    private class AddPersonalFriendTask extends AsyncTask<Void, Void, JResponseObject>{

        private ProgressDialog dialog;

        @Override
        protected void onPreExecute() {
            dialog = new ProgressDialog(AddAllTypesFriendsPG.this);
            dialog.setMessage(ResStringUtil.getString(R.string.wrchatview_looking_for_contacts));
            dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            dialog.show();
            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", "search");
            PO.SetValueByParamName("searchName", searchKeyword);
            PO.SetValueByParamName("chatUserId", EnvironmentVariable.getProperty(CHAT_USER_ID, ""));
            PO.SetValueByParamName("chatPassword", EnvironmentVariable.getProperty(CHAT_PASSWORD, ""));
            PO.SetValueByParamName("APPID", EnvironmentVariable.getProperty("APPID"));
            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) {
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
            if (result != null) {
                // {F_SYBB=0, F_KSRQ=, F_CRDATE=2016-7-29.16.37. 10.
                // 0,
                // F_CHDATE=2016-7-29.16.37. 10. 0, F_IP=, F_CPWD=0,
                // F_IM_PASSWORD=3.1415926,
                // F_MACA=, F_PASS1=, _Self_RowSet=, F_CERT=,
                // F_JSRQ=, F_YHZT=0,
                // F_MASK=, F_SYKM=0, F_EMAIL=785072254@qq.com,
                // F_ISROLE=0,
                // F_PASS=NzZSNCsvZyE7RWQ2KWY9KEcoMCU=, F_MANA=0,
                // F_TYBZ=0,
                // F_CPRQ=, F_BZ=, F_IPKZ=0, F_CRUSER=,
                // F_NAME=style, F_PHONE=18366103362,
                // F_SQMS=1, F_FC=0, F_REMOTE=0, F_CERTENABLE=,
                // F_IM_USERID=19, F_YSQX=0,
                // F_ZGBH=18366103362, F_MESSAGE=, SQMS=0, F_SYZT=1}
                EFDataSet efDataSet = (EFDataSet) result
                        .getResponseObject();
                List<EFRowSet> list = efDataSet.getRowSetArray();
                if (list == null) {
                    Toast.makeText(AddAllTypesFriendsPG.this, ResStringUtil.getString(R.string.wrchatview_no_search_user), Toast.LENGTH_LONG).show();
                    return;
                }
                // TODO 如果返回一条数据，直接跳转； 如果返回多条，生成列表
                List<AddFriendUser> users = new ArrayList<AddFriendUser>();
                for (EFRowSet efRowSet : list) {
                    if (efRowSet.hasKey("tip")) {
                        Toast.makeText(AddAllTypesFriendsPG.this, ResStringUtil.getString(R.string.wrchatview_no_search_user), Toast.LENGTH_LONG).show();
                        return;
                    }
                    AddFriendUser user = new AddFriendUser();
                    String userName = efRowSet.getString("F_NAME", "");
                    if("".equals(userName)){
                        userName = efRowSet.getString("userName", "");
                    }
                    String userId = efRowSet.getString("F_IM_USERID", "");
                    String ZGBH = efRowSet.getString("F_ZGBH", "");
                    String phone = efRowSet.getString("F_PHONE", "");
                    String adName = efRowSet.getString("F_EMAIL", "");
                    String avatarUrl = efRowSet.getString("avatar", "");
                    user.setName(userName);
                    user.setAdName(adName);
                    user.setTelphone(phone);
                    user.setNumber(ZGBH);
                    user.setAvatar(avatarUrl);
                    if (!avatarUrl.equals("")) {
                        Log.i(TAG, avatarUrl);
                    }
                    try {
                        user.setId(Integer.valueOf(userId));
                        users.add(user);
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                }
                generateListView(users);
            }else {
                Toast.makeText(AddAllTypesFriendsPG.this, ResStringUtil.getString(R.string.wrchatview_please_again_or_keyword), Toast.LENGTH_LONG).show();
            }
        }

    }

    private void generateListView(final List<AddFriendUser> users) {
        if (users.size() == 1) {
            User isExists = WeChatDBManager.getInstance().getOneFriendById(users.get(0).getId());
            //查询数据库属否存在该好友，如果得到的昵称跟id相同，说明不存在该好友
            if (isExists.getNickName().equals(String.valueOf(users.get(0).getId()))) {


                Intent intent = new Intent(AddAllTypesFriendsPG.this,
                        AddFriendUserDetailPGActivity.class);
                intent.putExtra("user", users.get(0));
                startActivity(intent);
                AddAllTypesFriendsPG.this.finish();

            } else {//本地存在该好友

                Intent intent = new Intent(AddAllTypesFriendsPG.this,
                        UserInfoActivity.class);
                intent.putExtra("id", users.get(0).getId());
                startActivity(intent);
                AddAllTypesFriendsPG.this.finish();
            }

            return;

        }
        ListView listView = (ListView) findViewById(R.id.listView_addfriend);
        AddFriendsUserListAdapter adapter = new AddFriendsUserListAdapter(users);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                Intent intent = new Intent(AddAllTypesFriendsPG.this,AddFriendUserDetailPGActivity.class);
                intent.putExtra("user", users.get(position));
                startActivity(intent);
                AddAllTypesFriendsPG.this.finish();
            }
        });

    }

    public void generatePublicAccountListView(final List<User> users) {
        if (users.size() == 1) {
            Intent intent = new Intent(AddAllTypesFriendsPG.this,
                    AddPublicFriendInfoActivity.class);
            intent.putExtra("user", users.get(0));
            startActivity(intent);
            AddAllTypesFriendsPG.this.finish();
            return;
        }
        ListView listView = (ListView) findViewById(R.id.listView_addfriend);
        AddPublicUserListAdapter adapter = new AddPublicUserListAdapter(users);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                Intent intent = new Intent(AddAllTypesFriendsPG.this,
                        AddPublicFriendInfoActivity.class);
                intent.putExtra("user", users.get(position));
                startActivity(intent);
                AddAllTypesFriendsPG.this.finish();
            }
        });

    }

    public void generateGroupListView(final List<Group> groups) {
        if (groups.size() == 1) {
            Intent intent = new Intent(AddAllTypesFriendsPG.this,
                    AddGroupUserInfoActivity.class);
            Bundle bundle = new Bundle();
            String groupId = String.valueOf(groups.get(0).getGroupId());
            Group tempGroup = WeChatDBManager.getInstance().getGroupWithUsers(Integer.valueOf(groupId));
            bundle.putInt("id", Integer.valueOf(groupId));
            //进入群信息页，处理加群操作
            //如果数据库没有，则没有加入群，在新界面中处理
            if (String.valueOf(tempGroup.getGroupId()).equals(tempGroup.getGroupName())) {
                bundle.putBoolean("added",false);//是否加群
            }else {
                bundle.putBoolean("added",true);//是否加群
            }
            bundle.putString("avatar",groups.get(0).getAvatar());
            intent.putExtras(bundle);
            startActivity(intent);
            AddAllTypesFriendsPG.this.finish();
            return;
        }
        ListView listView = (ListView) findViewById(R.id.listView_addfriend);
        AddGroupUserListAdapter adapter = new AddGroupUserListAdapter(groups);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                Intent intent = new Intent(AddAllTypesFriendsPG.this,
                        AddGroupUserInfoActivity.class);
                Bundle bundle = new Bundle();
                String groupId = String.valueOf(groups.get(position).getGroupId());
                Group tempGroup = WeChatDBManager.getInstance().getGroupWithUsers(Integer.valueOf(groupId));
                bundle.putInt("id", Integer.valueOf(groupId));
                bundle.putString("avatar",groups.get(position).getAvatar());
                //进入群信息页，处理加群操作
                //如果数据库没有，则没有加入群，在新界面中处理
                if (String.valueOf(tempGroup.getGroupId()).equals(tempGroup.getGroupName())) {
                    bundle.putBoolean("added",false);//是否加群
                }else {
                    bundle.putBoolean("added",true);//是否加群
                }
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });

    }

    @Override
    public void back(View view) {
        finish();
    }
}
