package com.efounder.chat.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.efounder.chat.R;
import com.efounder.chat.adapter.ChatRoomAdapter;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.model.Group;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.http.UniversalRequestManager;
import com.efounder.utils.ResStringUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.Executors;


/**
 * 设置工作群组Activity
 *
 * @author slp
 * @date 2018/3/19
 */
public class SetWorkGroupActivity extends BaseActivity {

    private SwipeMenuListView groupListView;
    protected List<Group> grouplist;
    private ChatRoomAdapter groupAdapter;
    private TextView tv_total;
    private Group deleteGroup;
    private final String TAG = "ChatRoomActivity";
    private ProgressDialog progressDialog;
    private TextView tvWorkGroup;
    private RelativeLayout rlWorkgroup;
    //    private SwipeMenuCreator creator;
    private AsyncTask<Void, Void, List<Group>> asyncTask;

    private Group mWorkGroup;
    private String userId;
    private String mWorkGroupId;
    private ImageView ivWorkAvator;
    private TextView tvWorkName;

    private String setWorkurl = EnvironmentVariable.getProperty("setWorkGroup");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set_work_group);
        Log.i(TAG, "onCreate: " + setWorkurl);
        grouplist = new ArrayList<Group>();

        tvWorkGroup = (TextView) findViewById(R.id.tv_work_group);
        rlWorkgroup = (RelativeLayout) findViewById(R.id.rl_work_group);
        ivWorkAvator = (ImageView) findViewById(R.id.iv_avatar1);
        tvWorkName = (TextView) findViewById(R.id.tv_name);

        groupListView = (SwipeMenuListView) findViewById(R.id.groupListView);
        groupListView.setIsNeedIntercept(true);

        userId = EnvironmentVariable.getUserID();
        if (EnvironmentVariable.getProperty(userId + "workgroup") == null
                || "".equals(EnvironmentVariable.getProperty(userId + "workgroup"))) {
//            ToastUtil.showToast(this, "请设置工作群");
            new AlertDialog.Builder(this)
                    .setMessage(ResStringUtil.getString(R.string.wrchatview_not_set_default_group))
                    .setPositiveButton(R.string.common_text_confirm, null)
                    .show();
        } else {
            mWorkGroupId = EnvironmentVariable.getProperty(userId + "workgroup");
            mWorkGroup = WeChatDBManager.getInstance().getGroup(Integer.parseInt(mWorkGroupId), false);
            LXGlideImageLoader.getInstance().showGroupAvatar(this, ivWorkAvator, mWorkGroup.getAvatar());
            tvWorkName.setText(mWorkGroup.getGroupName());
            tvWorkGroup.setVisibility(View.VISIBLE);
            rlWorkgroup.setVisibility(View.VISIBLE);
        }

        View headerView = LayoutInflater.from(this).inflate(
                R.layout.header_set_work_group, null);
        View footerView = LayoutInflater.from(this).inflate(
                R.layout.item_mychatroom_footer, null);
        tv_total = (TextView) footerView.findViewById(R.id.tv_total);
        tv_total.setText(String.valueOf(grouplist.size()) + ResStringUtil.getString(R.string.wrchatview_group_chat));

        groupAdapter = new ChatRoomAdapter(this, grouplist);
        groupListView.addHeaderView(headerView);
        groupListView.addFooterView(footerView);
        groupListView.setAdapter(groupAdapter);

        groupListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                //如果点击第一个和最后一个，取消点击事件
                if (i == grouplist.size() + 1 || i == 0) {
                    return;
                }
                // 进入群聊
                final int position = i - 1;

                Log.i(TAG, "点击的item-position：" + position);
//                EnvironmentVariable.setProperty("currentChatUserId", String.valueOf(groupAdapter
//                        .getItem(position).getGroupId()));
//                Intent intent = new Intent(SetWorkGroupActivity.this, ChatActivity.class);
//                intent.putExtra("id", groupAdapter.getItem(position).getGroupId());
//                intent.putExtra("chattype", StructFactory.TO_USER_TYPE_GROUP);
//                startActivity(intent);
                // finish();
                mWorkGroup = grouplist.get(position);
                //将设置的工作群号存到env中
                new AlertDialog.Builder(SetWorkGroupActivity.this)
                        .setTitle(R.string.wrchatview_prompt)
                        .setMessage(ResStringUtil.getString(R.string.wrchatview_set) + mWorkGroup.getGroupName() + ResStringUtil.getString(R.string.wrchatview_default_group))
                        .setNegativeButton(R.string.common_text_cancel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        })
                        .setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                setWorkGroupUrl(String.valueOf(mWorkGroup.getGroupId()));
                                EnvironmentVariable.setProperty(userId + "workgroup", String.valueOf(mWorkGroup.getGroupId()));

                                LXGlideImageLoader.getInstance().showGroupAvatar(SetWorkGroupActivity.this, ivWorkAvator, mWorkGroup.getAvatar());
                                tvWorkName.setText(mWorkGroup.getGroupName());
                                tvWorkGroup.setVisibility(View.VISIBLE);
                                rlWorkgroup.setVisibility(View.VISIBLE);

                            }
                        }).show();

            }
        });


        //标题
        TextView tvTitle = (TextView) this.findViewById(R.id.tv_title);
        tvTitle.setText(R.string.wrchatview_work_group);
        //加号按钮
        ImageView iv_add = (ImageView) this.findViewById(R.id.iv_add);
        iv_add.setVisibility(View.INVISIBLE);
        ImageView iv_search = (ImageView) this.findViewById(R.id.iv_search);
    }

    @Override
    public void onResume() {
        super.onResume();
        loadDataByAsync();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }


    /**
     * 返回
     *
     * @param view
     */
    @Override
    public void back(View view) {
        finish();
    }

    private void dismissProgressDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
            progressDialog = null;
        }
    }

    private void showProgressDialog(String msg) {
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage(msg);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.show();
    }

    /**
     * 调接口设置工作群
     * @param groupId
     */
    private void setWorkGroupUrl(String groupId) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("userID", userId);
        hashMap.put("groupID", groupId);

        UniversalRequestManager.getInstance(this).requestAsyn("https://zyim.zyof.com.cn/ExtraInterface/setDefaultGroup", 1, hashMap, new UniversalRequestManager.ReqCallBack<Object>() {

            @Override
            public void onReqSuccess(Object result) {
                if("true".equals(result)){
                    Toast.makeText(SetWorkGroupActivity.this,R.string.chat_set_success,Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                Toast.makeText(SetWorkGroupActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
            }
        });
    }

    //数据库中读取列表数据
    private void loadDataByAsync() {
        asyncTask = new AsyncTask<Void, Void, List<Group>>() {

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

            @Override
            protected List<Group> doInBackground(Void... params) {
                List<Group> groups = WeChatDBManager.getInstance().getallGroupWithOutUsers();

                return groups;
            }

            @Override
            protected void onPostExecute(List<Group> result) {
                super.onPostExecute(result);
                dismissProgressDialog();
                grouplist.clear();
                grouplist.addAll(result);
                tv_total.setText(String.valueOf(grouplist.size()) + ResStringUtil.getString(R.string.wrchatview_group_chat));
                groupAdapter.notifyDataSetChanged();
            }

            @Override
            protected void onCancelled() {
                super.onCancelled();
                dismissProgressDialog();
            }
        };
        asyncTask.executeOnExecutor(Executors.newCachedThreadPool());

    }

}
