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

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.nimlib.sdk.team.TeamService;
import com.netease.nimlib.sdk.team.constant.TeamMemberType;
import com.netease.nimlib.sdk.team.constant.TeamMessageNotifyTypeEnum;
import com.netease.nimlib.sdk.team.model.Team;
import com.netease.nimlib.sdk.team.model.TeamMember;
import com.ydl.ydlcommon.data.http.RxUtils;
import com.ydl.ydlcommon.ui.LoadingDialogFragment;
import com.ydl.ydlcommon.utils.NetworkParamsUtils;
import com.ydl.ydlcommon.utils.log.LogHelper;
import com.ydl.ydlcommon.utils.remind.HttpErrorUtils;
import com.ydl.ydlcommon.view.dialog.CommonDialog;
import com.ydl.ydlcommon.view.dialog.ListDialog;
import com.yidianling.common.tools.ToastUtil;
import com.yidianling.im.R;
import com.yidianling.im.bean.RemoveHistory;
import com.yidianling.im.event.ChatGroupStatusEvent;
import com.yidianling.im.http.ImRetrofitApi;
import com.yidianling.im.router.ImIn;
import com.yidianling.nimbase.impl.cache.TeamDataCache;
import com.yidianling.uikit.api.NimUIKit;
import com.yidianling.uikit.business.session.helper.MessageListPanelHelper;
import com.yidianling.uikit.custom.widget.TitleBarBottom;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by zhoujianghua on 2015/9/10.
 */
public class YDLTeamMessageFragment extends YDLMessageFragment {

    private Team team;


    @Override
    public boolean isAllowSendMessage(IMMessage message) {
        TeamMember teamMember= TeamDataCache.getInstance().getTeamMember(team.getId(), NimUIKit.getAccount());
        if (team == null || !team.isMyTeam()) {
            ToastUtil.toastShort(getActivity(), R.string.im_team_send_message_not_allow);
            return false;
        }else if (team !=null && team.isAllMute() && teamMember.getType()!= TeamMemberType.Owner && teamMember.getType()!=TeamMemberType.Manager){
            ToastUtil.toastShort("管理员开启了全员禁言哦～");
            return false;
        }
        return true;
    }

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

    @Override
    public boolean sendMessage(IMMessage message) {
        if (!isAllowSendMessage(message)) {
            return false;
        }
        //如果自己是管理员 发送消息时带上主讲人标志
        Map<String,Object> map = new HashMap<String,Object>();
        TeamMember teamMember= TeamDataCache.getInstance().getTeamMember(sessionId,NimUIKit.getAccount());
        if (teamMember!=null && teamMember.getType()== TeamMemberType.Manager){
            map.put("owner","1");
            message.setRemoteExtension(map);
        }
        return super.sendMessage(message);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        titleBar.setOnRightTextClick(new TitleBarBottom.OnTitleBarTextClick() {
            @Override
            public void onClick(View view, boolean isActive) {

                List<String> list = new ArrayList<>();
                int notifyType = NIMClient.getService(TeamService.class).queryTeamBlock(sessionId).getMessageNotifyType().getValue(); // 群消息提醒

//                if (ImConstants.KEFUXIAOYI.equals(toChatUsername) || "4108805".equals(toChatUsername)) {
//                    list.add("历史聊天记录");
//                    list.add("客服热线");
//                } else {
//                if (notifyType==0){
//                    list.add("关闭群消息提醒");
//                }else{
//                    list.add("开启群消息提醒");
//                }
                list.add("投诉反馈");
//
//                    list.add("历史聊天记录");
//                    list.add("删除聊天记录");
//                }
                list.add("删除聊天记录");
                ListDialog.Builder dialog = new ListDialog.Builder(getContext(), list, 0, team.getName());
                list.add("取消");
                dialog.create().show();

                dialog.SetOnItemClickLister(new ListDialog.Builder.OnItemClickLister() {
                    @Override
                    public void onItemClick(Dialog dialog, View view, int position) {
                        LogHelper.Companion.getInstance().writeLogSync(String.format("聊天界面：%s", list.get(position)));
                        switch (list.get(position)) {
                            case "开启群消息提醒":
                            case "关闭群消息提醒":
                                OpenCloseTeamMute(notifyType);
                                break;
                            case "投诉反馈":
                                ImIn.INSTANCE.feedBackIntent((Activity) getContext());
                                break;
                            case "返回首页":
                                ImIn.INSTANCE.mainIntent(getContext(), 0);
                                break;
                            case "客服热线":
//                                showCallDialog();
                                break;
                            case "历史聊天记录":
//                                historyMsg();
                                break;

                            case "删除聊天记录":
                                deleteChatHistory();
                                break;
                            case "ta的主页":
//                                showUserHome();
                                break;
                            case "取消":
                                break;
                        }
                        dialog.dismiss();
                    }

                    @Override
                    public void onItemLongClick(Dialog dialog, View view, int position) {

                    }
                });
            }
        });
    }

    private void OpenCloseTeamMute(int notifyType) {
        TeamMessageNotifyTypeEnum type = TeamMessageNotifyTypeEnum.All;
        if (notifyType ==0){
            type = TeamMessageNotifyTypeEnum.Mute;
        }
        NIMClient.getService(TeamService.class).muteTeam(team.getId(), type).setCallback(new RequestCallback<Void>() {
            @Override
            public void onSuccess(Void param) {
                ToastUtil.toastShort("成功");
                // 设置成功
            }

            @Override
            public void onFailed(int code) {
                ToastUtil.toastShort(code+"");
                // 设置失败
            }

            @Override
            public void onException(Throwable exception) {
                // 错误
            }
        });
    }

    public void onEventMainThread(ChatGroupStatusEvent event){
       getChatGroupMute();
    }
    //获取群聊是否全员禁言
    private void getChatGroupMute(){
        boolean mute = NIMClient.getService(TeamService.class).queryTeamBlock(sessionId).isAllMute();
        setGoneInput(mute);
    }

    public void setTeam(Team team) {
        Log.e("hzs","-------------setTeam------------TeammessageFragment");
        this.team = team;
    }
    /**
     * 删除聊天记录
     */
    private void deleteChatHistory() {
        CommonDialog dialog = CommonDialog.create(getContext());
        dialog.setMessage("确定删除与ta的聊天记录？");
        dialog.setCancelAble(true);
        dialog.setLeftOnclick("再考虑下", v -> dialog.dismiss());
        dialog.setRightClick("立即删除", v -> {
            ToastUtil.toastShort("聊天记录已删除");
            NIMClient.getService(MsgService.class).clearServerHistory(team.getId(),SessionTypeEnum.Team);
            MessageListPanelHelper.getInstance().notifyClearMessages(team.getId());
        });
        dialog.show();
    }
}