package com.cn.listener;

import org.jim.server.enums.MessageStateEnum;
import org.jim.server.model.ChatGroup;
import org.jim.common.ImAio;
import org.jim.common.ImPacket;
import org.jim.common.ImSessionContext;
import org.jim.common.cache.redis.JedisTemplate;
import org.jim.common.packets.*;
import org.jim.server.enums.ConsumerTypeEnum;
import org.jim.server.enums.GroupStateEnum;
import org.jim.server.enums.VisitTypeEnum;
import org.jim.server.listener.ImGroupListener;
import org.jim.server.model.Conversation;
import org.jim.server.model.GroupConversationMiddle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.ChannelContext;

import java.sql.Timestamp;

/**
 * @author Darren
 * @date 2020/2/6 15:53
 */
public class IMChatGroupListener extends ImGroupListener {

    private static Logger logger = LoggerFactory.getLogger(IMChatGroupListener.class);

    @Override
    public void onAfterUnbind(ChannelContext channelContext, String group) throws Exception {

        logger.info("解绑群组后,执行 onAfterUnbind() 方法...");
        ImSessionContext imSessionContext = (ImSessionContext)channelContext.getAttribute();
        ExitGroupNotifyRespBody exitGroupNotifyRespBody = new ExitGroupNotifyRespBody();
        exitGroupNotifyRespBody.setGroup(group);
        Client client = imSessionContext.getClient();
        if(client == null){
            return;
        }
        User clientUser = client.getUser();
        if(clientUser == null) {
            return;
        }
        //访问类型 (SERVICEACCOUNT 客服 / CUSTOMER 客户 / VISITOR 游客)
        String visitType = clientUser.getVisitType();
        if( !VisitTypeEnum.SERVICEACCOUNT.getKey().equals(visitType) ){
            ChatGroup chatGroup = ChatGroup.dao.findById(group);
            if( null != chatGroup ){
                //更改 group_state: 1 (群组离线状态 1: 离线 0: 在线)
                //更改 consumer_type: 1 (客户/游客 离线状态 1:离线 0:在线)
                chatGroup
                        .set("group_state", GroupStateEnum.OFF_LINE.getKey())
                        .set("consumer_type", ConsumerTypeEnum.OFF_LINE.getKey())
                        .update();

                if(MessageStateEnum.NO.getKey() == chatGroup.getInt("message_state")){
                    //群组状态 为 非留言状态
                    //修改 sw_conversation 表中的  end_time 和 conversation_lenth
                    StringBuilder sql = new StringBuilder();
                    sql.append(" select * from sw_group_conversation_middle where group_id = " + group)
                            .append(" order by create_time desc limit 1");
                    GroupConversationMiddle groupConversation = GroupConversationMiddle.dao.findFirst(sql.toString());
                    if( null != groupConversation ){
                        Conversation conversation = Conversation.dao.findById(groupConversation.getLong("conversation_id"));
                        Timestamp endTime = conversation.getTimestamp("end_time");
                        Integer conversationLenth = conversation.getInt("conversation_lenth");
                        if( null == endTime && null == conversationLenth ){
                            //需要更改会话结束时间 和 对话时长
                            long currentTimeMillis = System.currentTimeMillis();
                            //当前时间的格林威治时间 毫秒数
                            Timestamp currentTime = new Timestamp(currentTimeMillis);
                            Timestamp createTime = conversation.getTimestamp("create_time");
                            //会话创建时间的格林威治时间 毫秒数
                            long createTimeMillis = createTime.getTime();
                            if(currentTimeMillis > createTimeMillis){
                                conversation.set("end_time",currentTime)
                                            .set("conversation_lenth",Integer.valueOf( String.valueOf( (currentTimeMillis - createTimeMillis)/1000 )))
                                            .update();
                            }
                        }
                    }
                }
            }
        }

        User notifyUser = new User(clientUser.getId(),clientUser.getNick());
        exitGroupNotifyRespBody.setUser(notifyUser);

        RespBody respBody = new RespBody(Command.COMMAND_EXIT_GROUP_NOTIFY_RESP,exitGroupNotifyRespBody);
        ImPacket imPacket = new ImPacket(Command.COMMAND_EXIT_GROUP_NOTIFY_RESP, respBody.toByte());
        ImAio.sendToGroup(group, imPacket);
    }


}
