/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ifish.helper;

import com.ifish.Interceptor.IfishException;
import com.ifish.bean.LiveRoomPageInfo;
import com.ifish.bean.Tbl_Device_User;
import com.ifish.bean.Tbl_Live_Message;
import com.ifish.bean.Tbl_Live_Room;
import com.ifish.bean.Tbl_Live_Watch;
import com.ifish.bean.Tbl_User;
import com.ifish.enums.ResultEnum;
import com.ifish.mapper.Tbl_Live_Room_Mapper;
import com.ifish.util.IfishUtil;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

/**
 *
 * @author Administrator
 */
@Component
public class LiveRoomHelper implements LiveRoomHelperI {

    @Autowired
    private FastDFSClientI fastDFSClientI;

    @Autowired
    private Tbl_Live_Room_Mapper tbl_Live_Room_Mapper;

    @Autowired
    private UserHelperI userHelperI;

    @Autowired
    private DeviceHelperI deviceHelperI;

    @Autowired
    private RedisHelperI redisHelperI;

    @Autowired
    private RedisKeyHelperI redisKeyHelperI;

    /**
     * 新增直播间
     *
     * @param fileUpload
     * @param liveRoom
     */
    @Override
    public Object addLiveRoom(MultipartFile fileUpload, Tbl_Live_Room liveRoom) {
        try {
            if (liveRoom.getUserId() == null || liveRoom.getUserId() <= 0) {
                throw new IfishException(ResultEnum.error401);
            }
            if (StringUtils.isBlank(liveRoom.getRoomName()) || liveRoom.getRoomName().length() > 20) {
                throw new IfishException(ResultEnum.error401);
            }
            if (StringUtils.isBlank(liveRoom.getRoomDesc()) || liveRoom.getRoomDesc().length() > 70) {
                throw new IfishException(ResultEnum.error401);
            }
            if (StringUtils.isBlank(liveRoom.getRoomStatus()) || liveRoom.getRoomStatus().length() > 1) {
                throw new IfishException(ResultEnum.error401);
            }
            if (StringUtils.isBlank(liveRoom.getCameraId()) || liveRoom.getCameraId().length() > 20) {
                throw new IfishException(ResultEnum.error401);
            }
            if (fileUpload == null || fileUpload.getSize() > 1048576) {
                throw new IfishException(ResultEnum.warn205);
            }
            String file = fastDFSClientI.uploadFileToFastDFS(fileUpload);
            if (StringUtils.isNotBlank(file)) {
                liveRoom.setRoomImg(file);
            }

            //用户ID
            Integer userId = liveRoom.getUserId();
            Tbl_User user = userHelperI.getUserById(userId);
            if (user == null) {
                throw new IfishException(ResultEnum.error402);
            }
            //用户是否绑定摄像头
            String cameraId = liveRoom.getCameraId();
            Tbl_Device_User cameraUser = deviceHelperI.getDeviceUserByUserId_CameraId(userId, cameraId);

            if (cameraUser == null) {
                throw new IfishException(ResultEnum.error402);
            }
            //原来不是开启状态
            Boolean cameraChange = false;
            if (cameraUser.getIsLive().equals("0")) {
                cameraUser.setIsLive("1");
                cameraChange = true;
            }
            //新增直播间
            liveRoom.setCreateTime(new Date());
            liveRoom.setPopularityValue(0);
            int i = tbl_Live_Room_Mapper.insertLiveRoom(liveRoom);
            if (i > 0) {
                if (cameraChange) {
                    deviceHelperI.updateDeviceUser(cameraUser);
                }
                redisKeyHelperI.deleteRedisByTbl_Live_Room(liveRoom);
                Map map = new HashMap();
                map.put("cameraId", cameraId);
                map.put("isLive", cameraUser.getIsLive());
                map.put("roomId", liveRoom.getRoomId());
                map.put("roomImg", liveRoom.getRoomImg());
                return IfishUtil.returnJson(ResultEnum.success.getKey(), map);
            }
            return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
        } catch (Exception e) {
            return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
        }

    }

    /**
     * 根据直播间ID获取直播间详情
     *
     * @param roomId
     * @return
     */
    public Tbl_Live_Room getLive_RoomById(Integer roomId) throws Exception {
        Tbl_Live_Room live_Room = null;
        String key = redisKeyHelperI.getTbl_Live_RoomRedisKeyByRoomId(roomId);
        String redisString = redisHelperI.getRedis(key);
        if (StringUtils.isNotBlank(redisString)) {
            live_Room = (Tbl_Live_Room) IfishUtil.JsonToBean(redisString, Tbl_Live_Room.class);
        } else {
            live_Room = tbl_Live_Room_Mapper.getTbl_Live_RoomById(roomId);
            if (live_Room != null && live_Room.getRoomId() > 0) {
                redisHelperI.setRedis(key, IfishUtil.ObjectToJson(live_Room));
            }
        }
        return live_Room;
    }

    /**
     * 根据房间ID查询直播间
     *
     * @param roomId
     * @return
     */
    public Tbl_Live_Room getTbl_Live_RoomById(Integer roomId) throws Exception {
        Tbl_Live_Room device = null;
        String key = redisKeyHelperI.getTbl_Live_RoomRedisKeyByRoomId(roomId);
        String redisString = redisHelperI.getRedis(key);
        if (StringUtils.isNotBlank(redisString)) {
            device = (Tbl_Live_Room) IfishUtil.JsonToBean(redisString, Tbl_Live_Room.class);
        } else {
            device = tbl_Live_Room_Mapper.getTbl_Live_RoomById(roomId);
            if (device != null && device.getRoomId() > 0) {
                redisHelperI.setRedis(key, IfishUtil.ObjectToJson(device));
            }
        }
        return device;
    }

    /**
     * 直播间点赞
     *
     * @param roomId
     * @param userId
     * @return
     */
    @Override
    public Object liveRoomsZan(Integer roomId, Integer userId) {
        try {
            //以前的方式，每人每个直播间只能点赞一次，这里不采用这种方式
//            //点赞和人气值不一样，人气值只此直播间点击数，点赞指观看此直播并点赞的人数
//            Tbl_Live_Room room = getTbl_Live_RoomById(roomId);
//            if (room == null) {
//                throw new IfishException(ResultEnum.error402);
//            }
//            Tbl_User user = userHelperI.getUserById(userId);
//            if (user == null) {
//                throw new IfishException(ResultEnum.error402);
//            }
//            //点赞数量
//            Integer zanNum = tbl_Live_Room_Mapper.getLiveRoomZanCountByRoomId(roomId);
//            //是否点过赞
//            int i = tbl_Live_Room_Mapper.IsZan(roomId, userId);
//            Map map = new HashMap();
//            //点赞过，取消点赞
//            if (i > 0) {
//                int j = tbl_Live_Room_Mapper.cancelZan(roomId, userId);
//                //成功取消
//                if (j > 0) {
//                    zanNum--;
//                    map.put("isZan", 0);
//                    map.put("zanNum", zanNum);
//                    return IfishUtil.returnJson(ResultEnum.success.getKey(), map);
//                }
//            } //没有点赞，点赞一次
//            else {
//                int j = tbl_Live_Room_Mapper.ImplementZan(roomId, userId);
//                if (j > 0) {
//                    zanNum++;
//                    map.put("isZan", 1);
//                    map.put("zanNum", zanNum);
//                    return IfishUtil.returnJson(ResultEnum.success.getKey(), map);
//                }
//            }
            Tbl_Live_Room live = getLive_RoomById(roomId);
            if (live != null) {
                if (live.getZanNum() != null && live.getZanNum() >= 0) {
                    live.setZanNum(live.getZanNum() + 1);
                } else {
                    live.setZanNum(1);
                }
                int i = tbl_Live_Room_Mapper.updateLiveRoom(live);
                if (i > 0) {
                    redisKeyHelperI.deleteRedisByTbl_Live_Room(live);
                    Map map = new HashMap();
                    map.put("isZan", 1);
                    map.put("zanNum", live.getZanNum());
                    return IfishUtil.returnJson(ResultEnum.success.getKey(), map);
                }
            }

        } catch (Exception e) {
            return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
        }
        return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
    }

    /**
     * 直播间留言
     *
     * @param liveMessage
     * @return
     */
    @Override
    public Object leaveMessage(Tbl_Live_Message liveMessage) {
        try {
            Integer roomId = liveMessage.getRoomId();
            Integer userId = liveMessage.getUserId();
            String messageContent = new String(liveMessage.getMessageContent().getBytes("ISO-8859-1"), "UTF-8");
            liveMessage.setMessageContent(messageContent);
            if (roomId != null && userId != null && StringUtils.isNotBlank(messageContent)) {
                Tbl_Live_Room live_Room = getLive_RoomById(roomId);
                Tbl_User user = userHelperI.getUserById(userId);
                if (live_Room != null && user != null) {
                    liveMessage.setCreateTime(new Date());
                    int i = tbl_Live_Room_Mapper.insertLiveMessage(liveMessage);
                    if (i > 0) {
                        liveMessage.setUserName(user.getNickName());
                        liveMessage.setUserImg(user.getUserImg());
                    }
                    liveMessage.setUserName(user.getNickName());
                    liveMessage.setUserImg(user.getUserImg());
                    Integer asUserId = liveMessage.getAsUserId();
                    if (asUserId != null) {
                        Tbl_User asUser = userHelperI.getUserById(asUserId);
                        if (asUser != null) {
                            liveMessage.setAsUserName(asUser.getNickName());
                            if (!asUserId.equals(userId)) {
                                //发送云信消息给所@的用户
                                //neteaseIM.sendMsg(userId.toString(), asUserId.toString(), "来自爱鱼看看的回复:" + messageContent, "");
                            }
                        } else {
                            Integer roomUserId = live_Room.getUserId();
                            if (!roomUserId.equals(userId)) {
                                //发送云信消息给房主
                                //neteaseIM.sendMsg(userId.toString(), roomUserId.toString(), "来自爱鱼看看的留言:" + messageContent, "");
                            }
                        }
                    }
                    return IfishUtil.toJson(ResultEnum.success.getKey(), liveMessage);
                }
            }
            return IfishUtil.toJson(ResultEnum.fail101.getKey(), "");
        } catch (Exception e) {
            return IfishUtil.toJson(ResultEnum.fail101.getKey(), "");
        }
    }

    /**
     * 根据直播间ID获取直播间评论列表
     *
     * @param roomId
     * @return
     */
    @Override
    public Object getLeaveMessage(Integer firstResult, Integer pageSize, Integer roomId) {
        try {
            if (firstResult == null) {
                firstResult = 0;
            }
            if (pageSize == null) {
                pageSize = 10;
            }
            List<Map> list = null;
            String key = redisKeyHelperI.getTbl_Live_Message(firstResult, pageSize, roomId);
            String redisString = redisHelperI.getRedis(key);
            if (StringUtils.isNotBlank(redisString)) {
                list = (List<Map>) IfishUtil.JsonToList(redisString, Map.class);
            } else {
                list = tbl_Live_Room_Mapper.getLive_MessagesListByRoomId(roomId, firstResult, pageSize);
                if (list != null && list.size() > 0) {
                    redisHelperI.setRedis(key, IfishUtil.ObjectToJson(list));
                }
            }
            return IfishUtil.toJson(ResultEnum.success.getKey(), list);
        } catch (Exception e) {
        }
        return IfishUtil.toJson(ResultEnum.fail101.getKey(), "");
    }

    /**
     * 根据用户ID获取直播间信息
     *
     * @param userId
     * @return
     */
    @Override
    public Object getLiveRoomInfo(Integer roomId) {
        try {
            if (roomId != null) {
                //查找直播间信息
                Tbl_Live_Room curLiveRoom = getLive_RoomById(roomId);
                if (curLiveRoom != null) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("roomId", roomId);
                    map.put("userId", curLiveRoom.getUserId());
                    map.put("roomName", curLiveRoom.getRoomName());
                    map.put("roomDesc", curLiveRoom.getRoomDesc());
                    map.put("popularityValue", curLiveRoom.getPopularityValue());
                    map.put("roomStatus", curLiveRoom.getRoomStatus());
                    map.put("roomImg", curLiveRoom.getRoomImg());
                    map.put("createTime", curLiveRoom.getCreateTime());
                    return IfishUtil.toJson(ResultEnum.success.getKey(), map);
                }
            }
            return IfishUtil.toJson(ResultEnum.success.getKey(), "");
        } catch (Exception e) {
            return IfishUtil.toJson(ResultEnum.fail101.getKey(), "");
        }
    }

    /**
     * 根据条件查询直播间列表
     *
     * @param firstResult
     * @param pageSize
     * @param userId
     * @param orders
     * @return
     */
    @Override
    public Object getLiveRooms(Integer firstResult, Integer pageSize, String orders) {

        try {
            if (firstResult != null && pageSize != null) {
                Map<String, Object> returnMap = new HashMap<String, Object>();
                List<LiveRoomPageInfo> timeList = new ArrayList<LiveRoomPageInfo>();
                String key = redisKeyHelperI.getListTbl_Live_Room_RedisKey(firstResult, pageSize, orders);
                String redisString = redisHelperI.getRedis(key);
                if (StringUtils.isNotBlank(redisString)) {
                    timeList = (List<LiveRoomPageInfo>) IfishUtil.JsonToList(redisString, LiveRoomPageInfo.class);
                } else {
                    if (orders != null && orders.equals("2")) {
                        timeList = tbl_Live_Room_Mapper.getLiveRoomListByRenqi(pageSize, firstResult);
                    } else {
                        timeList = tbl_Live_Room_Mapper.getLiveRoomListByCreateTime(pageSize, firstResult);
                    }
                    if (timeList != null && timeList.size() > 0) {
                        redisHelperI.setRedis(key, IfishUtil.ObjectToJson(timeList));
                    }
                }

                Integer count = 0;
                key = redisKeyHelperI.getTbl_Live_Room_CountRedisKey();
                redisString = redisHelperI.getRedis(key);
                if (StringUtils.isNotBlank(redisString)) {
                    count = Integer.parseInt(redisString);
                } else {
                    count = tbl_Live_Room_Mapper.getLiveRoomListCount();
                    redisHelperI.setRedis(key, count.toString());
                }
                returnMap.put("orders", orders);
                returnMap.put("total", count);
                returnMap.put("liveRoomInfo", timeList);
                return IfishUtil.toJson(ResultEnum.success.getKey(), returnMap);
            }
            return IfishUtil.toJson(ResultEnum.fail101.getKey(), "");
        } catch (Exception e) {
            return IfishUtil.toJson(ResultEnum.fail101.getKey(), "");
        }

    }

    /**
     * 修改直播间
     *
     * @param fileUpload
     * @param liveRoom
     * @return
     */
    @Override
    public Object updateLiveRoom(MultipartFile fileUpload, Tbl_Live_Room liveRoom) {

        try {
            if (fileUpload != null && fileUpload.getSize() <= 1048576) {
                String file = fastDFSClientI.uploadFileToFastDFS(fileUpload);
                if (StringUtils.isNotBlank(file)) {
                    liveRoom.setRoomImg(file);
                }
            }
            int i = tbl_Live_Room_Mapper.updateLiveRoom(liveRoom);
            if (i > 0) {
                redisKeyHelperI.deleteRedisByTbl_Live_Room(liveRoom);
                Tbl_Live_Room live = getLive_RoomById(liveRoom.getRoomId());
                return IfishUtil.toJson(ResultEnum.success.getKey(), live);
            }
        } catch (Exception e) {
        }
        return IfishUtil.toJson(ResultEnum.fail101.getKey(), "");
    }

    /**
     * 直播间人气值加1
     *
     * @param roomId
     * @param userId
     * @return
     */
    @Override
    public Object popularityValue(Integer roomId, Integer userId) {
        try {
            if (roomId != null && userId != null) {
                //浏览直播间记录
                Tbl_Live_Watch browseRoom = tbl_Live_Room_Mapper.getTbl_Live_WatchByRoomIdAndUserId(roomId, userId);
                Date date = new Date();
                //新增浏览记录
                if (browseRoom != null) {
                    browseRoom.setUpdateTime(date);
                    tbl_Live_Room_Mapper.updateTbl_Live_Watch(browseRoom);
                } else {
                    //更新浏览记录
                    browseRoom = new Tbl_Live_Watch();
                    browseRoom.setRoomId(roomId);
                    browseRoom.setUserId(userId);
                    browseRoom.setUpdateTime(date);
                    browseRoom.setCreateTime(date);
                    tbl_Live_Room_Mapper.insertTbl_Live_Watch(browseRoom);
                }
                //查找直播间信息
                Tbl_Live_Room curLiveRoom = getLive_RoomById(roomId);
                if (curLiveRoom != null) {
                    Integer popularityValue = null;
                    if (curLiveRoom.getPopularityValue() == null) {
                        popularityValue = 0;
                    } else {
                        popularityValue = curLiveRoom.getPopularityValue();
                    }
                    //人气值加一
                    popularityValue++;
                    curLiveRoom.setPopularityValue(popularityValue);
                    tbl_Live_Room_Mapper.updateLiveRoomPopularityValue(curLiveRoom);
                    redisKeyHelperI.deleteRedisByTbl_Live_Room(curLiveRoom);
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("roomId", roomId);
                    map.put("popularityValue", popularityValue);
                    return IfishUtil.toJson(ResultEnum.success.getKey(), popularityValue);
                }
            }
        } catch (Exception e) {
        }
        return IfishUtil.toJson(ResultEnum.fail101.getKey(), "");
    }
}
