package com.fjhx.common.service.on.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjhx.common.constant.SourceConstant;
import com.fjhx.common.entity.on.po.OnLineInfo;
import com.fjhx.common.entity.on.vo.OnLineInfoReturnData;
import com.fjhx.common.entity.on.vo.OnLineInfoVo;
import com.fjhx.common.mapper.on.OnLineInfoMapper;
import com.fjhx.common.service.on.OnLineInfoService;
import com.fjhx.socket.core.WebSocketServer;
import com.fjhx.socket.core.event.WebSocketOnMessageEvent;
import com.fjhx.socket.core.event.WebSocketOnOpenEvent;
import com.ruoyi.common.annotation.TenantIgnore;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;


/**
 * <p>
 * 在线时长信息 服务实现类
 * </p>
 *
 * @author
 * @since 2023-08-08
 */
@Service
public class OnLineInfoServiceImpl extends ServiceImpl<OnLineInfoMapper, OnLineInfo> implements OnLineInfoService {

    @Autowired
    private ISysDeptService sysDeptService;

    @Override
    public OnLineInfoReturnData onLineInfo() {
        Long userId = SecurityUtils.getUserId();


        //部门负责人：可查看负责部门/部门总监：可以查看对应部门及级联部门
        DynamicDataSourceContextHolder.push(SourceConstant.BASE);
        List<SysDept> deptList = sysDeptService.list(Wrappers.<SysDept>lambdaQuery()
                .eq(SysDept::getLeaderId, userId)
                .or()
                .eq(SysDept::getDirectorId, userId)
        );
        DynamicDataSourceContextHolder.poll();

        //递归获取子数据
        List<OnLineInfoReturnData.Dept> deptList1 = getDeptList(deptList, userId, 0);

        //返回数据
        OnLineInfoReturnData onLineInfoReturnData = new OnLineInfoReturnData();
        //我的在线时长
        BigDecimal divide = BigDecimal.valueOf(baseMapper.getOnLineTimeByUserId(userId)).divide(BigDecimal.valueOf(3600), 2, BigDecimal.ROUND_HALF_UP);
        onLineInfoReturnData.setOnLineTime(divide);
        //部门列表
        onLineInfoReturnData.setDeptList(deptList1);

        return onLineInfoReturnData;
    }

    List<OnLineInfoReturnData.Dept> getDeptList(List<SysDept> deptList, Long userId, Integer type) {
        List<OnLineInfoReturnData.Dept> deptList1 = new ArrayList<>();
        for (SysDept sysDept : deptList) {
            List<OnLineInfoReturnData.User> userList = new ArrayList<>();
            //获取用户列表
            List<OnLineInfoVo> onLineTimeByDeptIds = baseMapper.getOnLineTimeByDeptIds(Collections.singletonList(sysDept.getDeptId()));
            BigDecimal deptOnLineTime = BigDecimal.ZERO;
            for (OnLineInfoVo onLineTimeByDeptId : onLineTimeByDeptIds) {
                OnLineInfoReturnData.User user = new OnLineInfoReturnData.User();
                user.setUserName(onLineTimeByDeptId.getUserName());

                BigDecimal divide = BigDecimal.valueOf(onLineTimeByDeptId.getOnLineDuration()).divide(BigDecimal.valueOf(3600), 2, BigDecimal.ROUND_HALF_UP);
                user.setOnLineTime(divide);
                userList.add(user);

                deptOnLineTime = deptOnLineTime.add(divide);
            }

            OnLineInfoReturnData.Dept dept1 = new OnLineInfoReturnData.Dept();
            dept1.setDeptName(sysDept.getDeptName());
            dept1.setUserList(userList);
            dept1.setOnLineTime(deptOnLineTime);


            //如果部门总监是我 查询部门下的子部门(type=1是递归进来的需要查子部门)
            if (type == 1 || userId.equals(sysDept.getDirectorId())) {
                DynamicDataSourceContextHolder.push(SourceConstant.BASE);
                List<SysDept> deptList11 = sysDeptService.list(Wrappers.<SysDept>lambdaQuery().eq(SysDept::getParentId, sysDept.getDeptId()));
                DynamicDataSourceContextHolder.poll();
                //赋值子部门
                List<OnLineInfoReturnData.Dept> deptList2 = getDeptList(deptList11, userId, 1);
                dept1.setDeptList(deptList2);
                //计算子部门列表的时长和加到当前部门上
                BigDecimal onLineTimeCount = deptList2.stream().map(OnLineInfoReturnData.Dept::getOnLineTime).reduce(BigDecimal.ZERO, BigDecimal::add);
                dept1.setOnLineTime(dept1.getOnLineTime().add(onLineTimeCount));
            }

            //返回数据
            deptList1.add(dept1);
        }
        return deptList1;
    }

    /**
     * 用户连接websock监听
     */
    @EventListener
    @TenantIgnore
    public void webSocketOnOpenEvent(WebSocketOnOpenEvent webSocketOnOpenEvent) {
        WebSocketServer webSocketServer = webSocketOnOpenEvent.getWebSocketServer();
        Long userId = webSocketServer.getUserId();
        //记录上线时间
        DynamicDataSourceContextHolder.push(SourceConstant.COMMON);
        OnLineInfo onLineInfo = this.getOne(q -> q.eq(OnLineInfo::getUserId, userId).apply("DATE(on_line_date) = DATE(NOW())"));
        DynamicDataSourceContextHolder.poll();
        if (ObjectUtil.isEmpty(onLineInfo)) {
            onLineInfo = new OnLineInfo();
            onLineInfo.setOnLineDuration(0L);
            onLineInfo.setOnLineDate(new Date());
            onLineInfo.setUserId(userId);
            onLineInfo.setTenantId(webSocketServer.getTenantId());
        }
        onLineInfo.setLastOnlineTime(new Date());
        DynamicDataSourceContextHolder.push(SourceConstant.COMMON);
        this.saveOrUpdate(onLineInfo);
        DynamicDataSourceContextHolder.poll();
    }

    /**
     * 收到websock消息监听
     */
    @EventListener
    @TenantIgnore
    public void webSocketOnMessageEvent(WebSocketOnMessageEvent webSocketOnMessageEvent) {
        WebSocketServer webSocketServer = webSocketOnMessageEvent.getWebSocketServer();
        Long userId = webSocketServer.getUserId();

        String message = webSocketOnMessageEvent.getMessage();
        JSONObject json = JSONObject.parseObject(message);
        if (ObjectUtil.isNotEmpty(json.get("heartbeat"))) {
            //保存在线时长信息
            DynamicDataSourceContextHolder.push(SourceConstant.COMMON);
            OnLineInfo onLineInfo = this.getOne(q -> q.eq(OnLineInfo::getUserId, userId).apply("DATE(on_line_date) = DATE(NOW())"));
            DynamicDataSourceContextHolder.poll();
            if (ObjectUtil.isEmpty(onLineInfo)) {
                onLineInfo = new OnLineInfo();
                onLineInfo.setOnLineDuration(0L);
                onLineInfo.setOnLineDate(new Date());
                onLineInfo.setUserId(userId);
                onLineInfo.setTenantId(webSocketServer.getTenantId());
            }


            Long startTime = onLineInfo.getLastOnlineTime().getTime();
            Date endDate = new Date();
            //在线时长（秒）
            long onLineTime = (endDate.getTime() - startTime) / 1000;

            //记录在线时长
            onLineInfo.setOnLineDuration(onLineInfo.getOnLineDuration() + onLineTime);
            onLineInfo.setLastOnlineTime(endDate);
            DynamicDataSourceContextHolder.push(SourceConstant.COMMON);
            this.saveOrUpdate(onLineInfo);
            DynamicDataSourceContextHolder.poll();
        }
    }

}


