package org.jim.server.command.handler;

import org.apache.commons.collections4.CollectionUtils;
import org.jim.common.*;
import org.jim.common.cache.redis.JedisTemplate;
import org.jim.common.packets.*;
import org.jim.common.utils.ImKit;
import org.jim.common.utils.JsonKit;
import org.jim.server.command.AbstractCmdHandler;
import org.jim.server.enums.ServiceAccountOfflineTypeEnum;
import org.jim.server.enums.VisitTypeEnum;
import org.jim.server.model.ChatGroup;
import org.jim.server.model.VisitorDepartmentMiddle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.ChannelContext;

import java.util.List;

/**
 * 版本: [1.0]
 * 功能说明: 关闭请求cmd命令处理器
 * @author : WChao 创建时间: 2017年9月21日 下午3:33:23
 */
public class CloseReqHandler extends AbstractCmdHandler
{

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

	private static JedisTemplate jedisTemplate = null;

	private static final String GROUP_PROPERTY = " * ";

	private static final String CURRENT_SYSTEM_ALL_USER_ID = "CURRENT_SYSTEM_ALL_USER_ID";

	static {
		try {
			jedisTemplate = JedisTemplate.me();
		} catch (Exception e) {
			logger.info("JedisTemplate初始化失败!");
			e.printStackTrace();
		}
	}

	@Override
	public ImPacket handler(ImPacket packet, ChannelContext channelContext) throws Exception
	{
		CloseReqBody closeReqBody = null;
		try{
			closeReqBody = JsonKit.toBean(packet.getBody(),CloseReqBody.class);
		}catch (Exception e) {
			//关闭请求消息格式不正确
			return ImKit.ConvertRespPacket(new RespBody(Command.COMMAND_CLOSE_REQ, ImStatus.C10020), channelContext);
		}
		logger.info("执行关闭请求cmd命令处理器,移除客服容器中的客服...");
		if(closeReqBody == null || closeReqBody.getUserid() == null){
			ImSessionContext imSessionContext = (ImSessionContext)channelContext.getAttribute();
			Client client = imSessionContext.getClient();
			if( null != client){
				disposeUserData(client.getUser());
			}
			ImAio.remove(channelContext, "收到关闭请求");
		}else{
			String userId = closeReqBody.getUserid();
			disposeUserData(ImAio.getUser(userId));
			ImAio.remove(userId, "收到关闭请求!");
		}
		return ImKit.ConvertRespPacket(new RespBody(Command.COMMAND_CLOSE_REQ, ImStatus.C10021), channelContext);
	}

	/**
	 * 处理用户离线后的数据操作
	 * @param user
	 * @return {@link }
	 * @author Darren
	 * @date 2020/2/16 10:52
	 */
	private void disposeUserData(User user){
		if( null != user ){
			String visitType = user.getVisitType();
			String[] userIdArray = {user.getId()};
			if( VisitTypeEnum.SERVICEACCOUNT.getKey().equals(visitType) ){
				//移除客服容器中的 客服
				String serviceAccountContainerKey
						=  user.getExtras().getString("companyId") + ImConst.SEPARATOR
						+ user.getExtras().getString("departmentId") + ImConst.SEPARATOR
						+ VisitTypeEnum.SERVICEACCOUNT.getKey() ;
				jedisTemplate.hashDel(serviceAccountContainerKey,userIdArray);
				//判断 客服是否具有查看当前部门下 全部客服通话的权限 如果有移除
				if( Boolean.valueOf(user.getExtras().getString("hasViewAllServiceAccount")) ){
					String adminContainerKey = user.getExtras().getString("companyId")
							+ ImConst.SEPARATOR + user.getExtras().getString("departmentId")
							+ ImConst.SEPARATOR +  ImConst.ADMIN ;
					jedisTemplate.listRemove(adminContainerKey,0,user.getId());
				}
				List<ChatGroup> chatGroups = ChatGroup.dao.find(this.createSelectGroupSql(user));
				if( CollectionUtils.isNotEmpty(chatGroups) ){
					for (ChatGroup chatGroup : chatGroups) {
						//客服是否是离线状态 1: 是 0: 否
						chatGroup.set("service_account_type", ServiceAccountOfflineTypeEnum.OFF_LINE.getKey()).update();
					}
				}
			}
			if( VisitTypeEnum.VISITOR.getKey().equals(visitType) ){
				//修改 sw_visitor_department_middle 表中的 online状态; '用户状态 1:已下线 0:在线'
				VisitorDepartmentMiddle.dao.findById(user.getId()).set("online",1).update();
			}
			jedisTemplate.hashDel(CURRENT_SYSTEM_ALL_USER_ID,userIdArray);
		}
	}

	private String createSelectGroupSql(User user){
		StringBuilder sql = new StringBuilder();
		sql
				.append(" select ")
				.append(GROUP_PROPERTY)
				.append(" from sw_group where 1 = 1 ")
				.append(" and company_id = " + user.getExtras().getString("companyId"))
				.append(" and department_id = " + user.getExtras().getString("departmentId"))
				.append(
						" and service_account_role_department_middle_id = "
								+ user.getId()
				);
		return sql.toString();
	}

	@Override
	public Command command() {
		return Command.COMMAND_CLOSE_REQ;
	}
}
