package com.yidianling.uikit.business.session.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.nimlib.sdk.team.constant.TeamTypeEnum;
import com.netease.nimlib.sdk.team.model.Team;
import com.netease.nimlib.sdk.team.model.TeamMember;
import com.netease.nimlib.sdk.uinfo.UserService;
import com.yidianling.common.tools.ToastUtil;
import com.yidianling.im.R;
import com.yidianling.nimbase.api.model.SimpleCallback;
import com.yidianling.nimbase.api.model.contact.ContactChangedObserver;
import com.yidianling.nimbase.api.model.session.SessionCustomization;
import com.yidianling.nimbase.api.model.team.TeamDataChangedObserver;
import com.yidianling.nimbase.api.model.team.TeamMemberDataChangedObserver;
import com.yidianling.nimbase.business.preference.UserPreferences;
import com.yidianling.nimbase.business.session.constant.Extras;
import com.yidianling.uikit.api.NimUIKit;
import com.yidianling.uikit.business.session.fragment.YDLMessageFragment;
import com.yidianling.uikit.business.session.fragment.YDLTeamMessageFragment;
import com.yidianling.uikit.custom.bridge.ActionHandlerStorage;
import com.yidianling.uikit.custom.bridge.IP2PCustomActionHandler;
import com.yidianling.uikit.custom.widget.TitleBarBottom;

import java.util.ArrayList;
import java.util.List;

/**
 * 群聊界面
 * <p/>
 * Created by huangjun on 2015/3/5.
 */
public class YDLTeamMessageActivity extends YDLBaseMessageActivity {

    // model
    private Team team;

    private View invalidTeamTipView;

    private TextView invalidTeamTipText;

    private YDLTeamMessageFragment fragment;

    private Class<? extends Activity> backToClass;

    public static void start(Context context, String tid, SessionCustomization customization,
                             Class<? extends Activity> backToClass, IMMessage anchor, IP2PCustomActionHandler l) {
        Intent intent = new Intent();
        intent.putExtra(Extras.EXTRA_ACCOUNT, tid);
        intent.putExtra(Extras.EXTRA_CUSTOMIZATION, customization);
        intent.putExtra(Extras.EXTRA_BACK_TO_CLASS, backToClass);
        if (anchor != null) {
            intent.putExtra(Extras.EXTRA_ANCHOR, anchor);
        }

        ActionHandlerStorage.setL(tid,l);

        intent.setClass(context, YDLTeamMessageActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

        context.startActivity(intent);
    }

    protected void findViews() {
        invalidTeamTipView = findView(R.id.invalid_team_tip);
        invalidTeamTipText = findView(R.id.invalid_team_text);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e("hzs","-------------oncreate------------TeamMessageActivity");
        backToClass = (Class<? extends Activity>) getIntent().getSerializableExtra(Extras.EXTRA_BACK_TO_CLASS);

        findViews();

        initTip();

        registerTeamUpdateObserver(true);
        requestTeamInfo();
        //从服务器拉取资料
        NimUIKit.getTeamProvider().fetchTeamById(sessionId, new SimpleCallback<Team>() {
            @Override
            public void onResult(boolean success, Team result,int code) {
                if (success && result != null) {
                    updateTeamInfo(result);
                    //群信息更新成功 更新群用户信息
                    NimUIKit.getTeamProvider().fetchTeamMemberList(sessionId,new SimpleCallback<List<TeamMember>>(){

                        @Override
                        public void onResult(boolean success, List<TeamMember> result,int code) {
                            if (success){
                                List<String> list = new ArrayList<String>();

                                //更新群成员资料
                                for (TeamMember member : result){
                                    //如果当前用户信息为空则从服务器拉取
                                    if (NIMClient.getService(UserService.class).getUserInfo(member.getAccount())==null)
                                        list.add(member.getAccount());
                                }
                                //
                                Log.e("hzs","更新用户资料-----------");
                                if(list.size()==0)return;
                                //从云信服务器拉取用户信息
                                NIMClient.getService(UserService.class).fetchUserInfo(list);
                            }
                        }
                    });
                } else {
                    onRequestTeamInfoFailed();
                }
            }
        });

    }

    //如果是第一次进入此页面弹出查看历史记录的dialog
    private void initTip(){
        if (ActionHandlerStorage.getL(sessionId)!=null){
            ActionHandlerStorage.getL(sessionId).chatTeamHistoryTip(this);
        }
    }

    @Override
    protected void onDestroy() {
        registerTeamUpdateObserver(false);
        //聊天返回时，检查是否有未发送内容，如果有则保存到ImTempData 临时map中，再次进入时读取
        if (messageFragment !=null){
            if (messageFragment.getInputPanel().getInputContent().equals("@")){
                messageFragment.getInputPanel().setInputContent("");
            }
            if (ActionHandlerStorage.getL(sessionId)!=null){
                ActionHandlerStorage.getL(sessionId).saveImTempData(sessionId,messageFragment.getInputPanel().getInputContent());
            }
        }
        //销毁通信实例
//        ActionHandlerStorage.recycleL();

        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        requestTeamInfo();
        //如果从群聊中进入私聊，再回来，此时通信实例在私聊销毁时销毁，需要重新设置
//        if (IP2PCustomActionHandler==null){
//            ActionHandlerStorage.setL(IP2PCustomActionHandler);
//        }
        //读取未发送的临时消息
        if (ActionHandlerStorage.getL(sessionId)!=null){
            if (messageFragment.getInputPanel().getInputContent()==null || messageFragment.getInputPanel().getInputContent().equals("")){
                messageFragment.getInputPanel().setInputContent(ActionHandlerStorage.getL(sessionId).getImTempData(sessionId==null?"":sessionId));
            }
        }
    }

    /**
     * 请求群基本信息
     */
    private void requestTeamInfo() {
        Log.e("hzs","-------------请求群基本信息------------");
        // 请求群基本信息
        Team t = NimUIKit.getTeamProvider().getTeamById(sessionId);
        if (t != null) {
            updateTeamInfo(t);
        } else {
            NimUIKit.getTeamProvider().fetchTeamById(sessionId, new SimpleCallback<Team>() {
                @Override
                public void onResult(boolean success, Team result,int code) {
                    if (success && result != null) {
                        updateTeamInfo(result);
                        //群信息更新成功 更新群用户信息
                        NimUIKit.getTeamProvider().fetchTeamMemberList(sessionId,new SimpleCallback<List<TeamMember>>(){

                            @Override
                            public void onResult(boolean success, List<TeamMember> result,int code) {
                                if (success){
                                    //更新群成员资料
                                    for (TeamMember member : result)
                                        Log.e("hzs","群成员名称："+member.getTeamNick());
                                }
                            }
                        });
                    } else {
                        onRequestTeamInfoFailed();
                    }
                }
            });
        }
    }

    private void onRequestTeamInfoFailed() {
        ToastUtil.toastShort(YDLTeamMessageActivity.this, "获取群组信息失败!");
        finish();
    }

    /**
     * 更新群信息
     *
     * @param d
     */
    private void updateTeamInfo(final Team d) {
        if (d == null) {
            return;
        }

        team = d;
        fragment.setTeam(team);
        //暂时去掉群聊人数标题
//        setTitle(team == null ? sessionId : team.getName() + "(" + team.getMemberCount() + "人)");
        setTitle(team == null ? sessionId : team.getName() );

        invalidTeamTipText.setText(team.getType() == TeamTypeEnum.Normal ? R.string.im_normal_team_invalid_tip : R.string.im_team_invalid_tip);
        invalidTeamTipView.setVisibility(team.isMyTeam() ? View.GONE : View.VISIBLE);
    }

    /**
     * 注册群信息更新监听
     *
     * @param register
     */
    private void registerTeamUpdateObserver(boolean register) {
        NimUIKit.getTeamChangedObservable().registerTeamDataChangedObserver(teamDataChangedObserver,register);
        NimUIKit.getTeamChangedObservable().registerTeamMemberDataChangedObserver(teamMemberDataChangedObserver,register);
        NimUIKit.getContactChangedObservable().registerObserver(friendDataChangedObserver, register);
    }

    /**
     * 群资料变动通知和移除群的通知（包括自己退群和群被解散）
     */
    TeamDataChangedObserver teamDataChangedObserver = new TeamDataChangedObserver() {
        @Override
        public void onUpdateTeams(List<Team> teams) {
            if (team == null) {
                return;
            }
            for (Team t : teams) {
                if (t.getId().equals(team.getId())) {
                    updateTeamInfo(t);
                    break;
                }
            }
        }

        @Override
        public void onRemoveTeam(Team team) {
            if (team == null) {
                return;
            }
            if (team.getId().equals(YDLTeamMessageActivity.this.team.getId())) {
                updateTeamInfo(team);
            }
        }
    };

    /**
     * 群成员资料变动通知和移除群成员通知
     */
    TeamMemberDataChangedObserver teamMemberDataChangedObserver = new TeamMemberDataChangedObserver() {

        @Override
        public void onUpdateTeamMember(List<TeamMember> members) {
            fragment.refreshMessageList();
        }

        @Override
        public void onRemoveTeamMember(List<TeamMember> members) {

        }
    };

    ContactChangedObserver friendDataChangedObserver = new ContactChangedObserver() {
        @Override
        public void onAddedOrUpdatedFriends(List<String> accounts) {
            fragment.refreshMessageList();
        }

        @Override
        public void onDeletedFriends(List<String> accounts) {
            fragment.refreshMessageList();
        }

        @Override
        public void onAddUserToBlackList(List<String> account) {
            fragment.refreshMessageList();
        }

        @Override
        public void onRemoveUserFromBlackList(List<String> account) {
            fragment.refreshMessageList();
        }
    };

    @Override
    protected YDLTeamMessageFragment fragment() {
        // 添加fragment
        Bundle arguments = getIntent().getExtras();
        arguments.putSerializable(Extras.EXTRA_TYPE, SessionTypeEnum.Team);
        fragment = new YDLTeamMessageFragment();
        fragment.setArguments(arguments);
        fragment.setContainerId(R.id.message_fragment_container);
        return fragment;
    }

    @Override
    protected int getContentViewId() {
        return R.layout.im_ydl_nim_team_message_activity;
    }

    @Override
    protected void initToolBar() {
        tb = (TitleBarBottom) findViewById(R.id.titlebar);
        tb.setmMinTitleVisiable(View.GONE);
        if (!UserPreferences.isEarPhoneModeEnable()) {
            tb.setTitleRightDraw(null);
        } else {
            tb.setTitleRightDraw(getResources().getDrawable(R.drawable.im_erduoxiao));
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (backToClass != null) {
            Intent intent = new Intent();
            intent.setClass(this, backToClass);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            startActivity(intent);
            finish();
        }
    }
}
