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

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.WindowManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.MsgServiceObserve;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.CustomNotification;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.ydl.ydlcommon.utils.log.AliYunLogConfig;
import com.ydl.ydlcommon.utils.log.AliYunRichLogsHelper;
import com.yidianling.common.tools.ToastUtil;
import com.yidianling.im.R;
import com.yidianling.im.api.bean.IMRegisterObserverCustomNotificationCallBack;
import com.yidianling.im.bean.ServiceBean;
import com.yidianling.im.bridge.P2PCustomActionHandlerImpl;
import com.yidianling.im.config.constants.ImConstants;
import com.yidianling.im.helper.ImObserversHelper;
import com.yidianling.im.session.SessionHelper;
import com.yidianling.nimbase.api.model.session.SessionCustomization;
import com.yidianling.nimbase.api.model.user.UserInfoObserver;
import com.yidianling.nimbase.business.session.constant.Extras;
import com.yidianling.nimbase.common.ui.recyclerview.adapter.BaseFetchLoadAdapter;
import com.yidianling.nimbase.common.util.log.LogUtil;
import com.yidianling.uikit.api.NimUIKit;
import com.yidianling.uikit.business.session.fragment.YDLMessageFragment;
import com.yidianling.uikit.custom.bridge.ActionHandlerStorage;
import com.yidianling.uikit.custom.bridge.IP2PCustomActionHandler;

import org.jetbrains.annotations.NotNull;

import java.util.List;


/**
 * 点对点聊天界面
 * <p/>
 * Created by huangjun on 2015/2/1.
 */
public class YDLP2PMessageActivity extends YDLBaseMessageActivity {

    private boolean isResume = false;
    private int screenWidth;
    private int screenHeight;
    protected YDLMessageFragment messageFragment;
    private boolean isChangeDoctor = false;
    String oldName="";

    /**
     * @param context
     * @param contactId     对方id
     * @param customization 界面定制
     * @param anchor
     * @param l
     */
    public static void start(Context context, String contactId, SessionCustomization customization, IMMessage anchor, IP2PCustomActionHandler l) {
        Intent intent = new Intent();
        intent.putExtra(Extras.EXTRA_ACCOUNT, contactId);
        intent.putExtra(Extras.EXTRA_CUSTOMIZATION, customization);

        if (ActionHandlerStorage.getL(contactId) != null) {
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        } else if (contactId.equals(ImConstants.KEFUXIAOYI)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        }

        ActionHandlerStorage.setL(contactId, l);

        if (anchor != null) {
            intent.putExtra(Extras.EXTRA_ANCHOR, anchor);
        }
        intent.setClass(context, YDLP2PMessageActivity.class);
        context.startActivity(intent);
    }

    /**
     * 切换到客服界面
     */
    public static void startChangeDoctor(Context context, String contactId, SessionCustomization customization, IMMessage anchor, IP2PCustomActionHandler l) {
        Intent intent = new Intent();
        intent.putExtra(Extras.EXTRA_ACCOUNT, contactId);
        intent.putExtra(Extras.EXTRA_CUSTOMIZATION, customization);

        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

        ActionHandlerStorage.setL(contactId, l);

        if (anchor != null) {
            intent.putExtra(Extras.EXTRA_ANCHOR, anchor);
        }
        intent.setClass(context, YDLP2PMessageActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        // 如果isChangeDoctor为true表示切换客服
        if (isChangeDoctor) {
            messageFragment = (YDLMessageFragment) switchContent(switchServiceFragment(intent));
            isChangeDoctor = false;
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics displayMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(displayMetrics);
        screenWidth = displayMetrics.widthPixels;
        screenHeight = displayMetrics.heightPixels;
        if (ActionHandlerStorage.getL(sessionId) != null) {
            ActionHandlerStorage.getL(sessionId).clear(sessionId);
        }
        messageFragment = (YDLMessageFragment) switchContent(fragment());
        // 单聊特例话数据，包括个人信息，
        requestBuddyInfo();
        registerObservers(true);

        NIMClient.getService(MsgService.class).clearUnreadCount(sessionId, SessionTypeEnum.P2P);
        // 转客服通知监听
        ImObserversHelper.Companion.getInstance().setImCustomNotificationCallBack(new IMRegisterObserverCustomNotificationCallBack() {
            @Override
            public void onObserverCustomNotification(@NotNull String fromUid, @NotNull String toUid, @NotNull String content) {
                ServiceBean serviceBean = new Gson().fromJson(content, ServiceBean.class);
                // 切换到客服
                if (serviceBean != null && serviceBean.getData() != null&&serviceBean.getBusiness()!=null && serviceBean.getBusiness().equals("change_doctor")) {
                    isChangeDoctor = true;
                    String serviceUid = String.valueOf(serviceBean.getData().getToUid());
                    tb.setTitle(serviceBean.getData().getName());
                    YDLP2PMessageActivity.startChangeDoctor(YDLP2PMessageActivity.this, serviceUid, SessionHelper.getP2pCustomization(-1), null, new P2PCustomActionHandlerImpl(serviceUid, serviceBean.getData().getName(), serviceUid));
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        if (ActionHandlerStorage.getL(sessionId) != null) {
            ActionHandlerStorage.getL(sessionId).clear(sessionId);
        }
        registerObservers(false);

        super.onDestroy();
        AliYunRichLogsHelper.Companion.getInstance().sendRichLog(AliYunLogConfig.YUNXIN,"退出聊天页面");
    }

    @Override
    protected void onResume() {
        super.onResume();
        NIMClient.getService(MsgService.class).setChattingAccount(sessionId, SessionTypeEnum.P2P);
        isResume = true;

        //读取未发送的临时消息
        if (ActionHandlerStorage.getL(sessionId) != null) {
            if (messageFragment.getInputPanel().getInputContent() == null || messageFragment.getInputPanel().getInputContent().equals("")) {
                messageFragment.getInputPanel().setInputContent(ActionHandlerStorage.getL(sessionId).getImTempData(sessionId));
            }
            if (ActionHandlerStorage.needLoadNewMsg) {
                ((BaseFetchLoadAdapter.RequestFetchMoreListener) messageFragment.getMessageListPanelEx().getMessageLoder(null)).onFetchMoreRequested();
                ActionHandlerStorage.needLoadNewMsg = false;
            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        isResume = false;
    }

    private void requestBuddyInfo() {

        //        setTitle(UserInfoHelper.getUserTitleName(sessionId, SessionTypeEnum.P2P));
    }

    private void registerObservers(boolean register) {
        NimUIKit.getUserInfoObservable().registerObserver(userInfoObserver, register);
        NIMClient.getService(MsgServiceObserve.class).observeCustomNotification(commandObserver, register);

    }

    /**
     * 用户信息观察者
     */
    private UserInfoObserver userInfoObserver = new UserInfoObserver() {
        @Override
        public void onUserInfoChanged(List<String> accounts) {
            if (accounts.contains(sessionId)) {
                requestBuddyInfo();
            }
        }
    };

    /**
     * 命令消息接收观察者
     */
    Observer<CustomNotification> commandObserver = new Observer<CustomNotification>() {
        @Override
        public void onEvent(CustomNotification message) {
            if (!sessionId.equals(message.getSessionId()) || message.getSessionType() != SessionTypeEnum.P2P) {
                return;
            }
            showCommandMessage(message);
        }
    };

    protected void showCommandMessage(CustomNotification message) {
        if (!isResume) {
            return;
        }

        String content = message.getContent();
        try {
            JSONObject json = JSON.parseObject(content);
            int id = json.getIntValue("id");
            if (id == 1) {
                oldName= tb.getTitle();
                tb.setTitle("对方正在输入...");
            } else if (id==2){
                tb.setTitle(oldName);
            }

        } catch (Exception e) {

        }
    }

    @Override
    protected YDLMessageFragment fragment() {
        Bundle arguments = getIntent().getExtras();
        arguments.putSerializable(Extras.EXTRA_TYPE, SessionTypeEnum.P2P);
        if (messageFragment == null) {
            messageFragment = new YDLMessageFragment();
            messageFragment.setArguments(arguments);
            messageFragment.setContainerId(R.id.message_fragment_container);
        }
        return messageFragment;
    }

    /**
     * 切换到客服fragment
     *
     * @return
     */
    private YDLMessageFragment switchServiceFragment(Intent intent) {
        Bundle arguments = intent.getExtras();
        arguments.putSerializable(Extras.EXTRA_TYPE, SessionTypeEnum.P2P);
        messageFragment = new YDLMessageFragment();
        messageFragment.setArguments(arguments);
        messageFragment.setContainerId(R.id.message_fragment_container);
        return messageFragment;
    }

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

    @Override
    protected void initToolBar() {
        setToolBar(R.id.chat_tb);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (ActionHandlerStorage.getL(sessionId) != null) {
            ActionHandlerStorage.getL(sessionId).clear(sessionId);
        }
        NIMClient.getService(MsgService.class).setChattingAccount(MsgService.MSG_CHATTING_ACCOUNT_NONE, SessionTypeEnum.None);
        //清除对应ActionHandlerStorage的方法在这边进行调用
        //而不是在YDLBaseMessageActivity的onDestroy中调用是因为ondestroy调用时机不确定，会导致第二次打开同一个activity找不到ActionHandlerStorage
        if (isFinishing()) {
            //聊天返回时，检查是否有未发送内容，如果有则保存到ImTempData 临时map中，再次进入时读取
            if (messageFragment != null) {
                if (ActionHandlerStorage.getL(sessionId) != null)
                    ActionHandlerStorage.getL(sessionId).saveImTempData(sessionId, messageFragment.getInputPanel().getInputContent());
            }
            ActionHandlerStorage.recycleL(sessionId);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 45) {
            if (data != null) {
                IMMessage message = (IMMessage) data.getSerializableExtra("msg");
                LogUtil.d("TAG", "session id: " + sessionId);
                if (sessionId.equals(message.getSessionId()))
                    getYDLMessageFragment().getMessageListPanelEx().onMsgSend(message);
            }
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }
}
