/*
 * 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.bean.Tbl_Activa_Code;
import com.ifish.bean.Tbl_Device;
import com.ifish.bean.Tbl_Device_Statistics;
import com.ifish.bean.Tbl_Device_User;
import com.ifish.bean.Tbl_User;
import com.ifish.enums.PushTypeEnum;
import com.ifish.enums.ResultEnum;
import com.ifish.mapper.Tbl_Device_Mapper;
import com.ifish.util.IfishUtil;
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;

/**
 *
 * @author Administrator
 */
@Component
public class DeviceHelper implements DeviceHelperI {

    @Autowired
    private RedisHelperI redisHelperI;

    @Autowired
    private RedisKeyHelperI redisKeyHelperI;

    @Autowired
    private Tbl_Device_Mapper tbl_Device_Mapper;

    @Autowired
    private UserHelperI userHelperI;

    /**
     * 根据用户Id获取绑定设备集合
     *
     * @param userId
     * @return
     */
    @Override
    public List<Tbl_Device_User> getDeviceUsersByUserId(Integer userId) throws Exception {
        List<Tbl_Device_User> deviceUserList = null;
        String key = redisKeyHelperI.getListTbl_Device_UserKeyByUserId(userId);
        String redisString = redisHelperI.getRedis(key);
        if (StringUtils.isNotBlank(redisString)) {
            deviceUserList = (List<Tbl_Device_User>) IfishUtil.JsonToList(redisString, Tbl_Device_User.class);
        } else {
            deviceUserList = tbl_Device_Mapper.getDeviceUsersByUserId(userId);
            if (deviceUserList != null && deviceUserList.size() > 0) {
                redisHelperI.setRedis(key, IfishUtil.ObjectToJson(deviceUserList));
            }
        }
        return deviceUserList;
    }

    /**
     * 根据用户ID和设备ID获取此设备和此用户的关系
     *
     * @param userId
     * @param deviceId
     * @return
     * @throws Exception
     */
    public Tbl_Device_User getDeviceUserByUserId_DeviceId(Integer userId, Integer deviceId) throws Exception {
        Tbl_Device_User device = null;
        String key = redisKeyHelperI.getTbl_Device_UserRedisKeyByDeviceIdAndUserId(userId, deviceId);
        String redisString = redisHelperI.getRedis(key);
        if (StringUtils.isNotBlank(redisString)) {
            device = (Tbl_Device_User) IfishUtil.JsonToBean(redisString, Tbl_Device_User.class);
        } else {
            device = tbl_Device_Mapper.getDeviceUsersByUserIdAndDeviceId(userId, deviceId);
            if (device != null && device.getDeviceId() > 0) {
                redisHelperI.setRedis(key, IfishUtil.ObjectToJson(device));
            }
        }
        return device;
    }

    /**
     * 根据用户ID和摄像头ID获取此摄像头和用户的关系
     *
     * @param userId
     * @param deviceId
     * @return
     * @throws Exception
     */
    @Override
    public Tbl_Device_User getDeviceUserByUserId_CameraId(Integer userId, String cameraId) throws Exception {
        Tbl_Device device = getDeviceByCameraId(cameraId);
        if (device == null) {
            return null;
        }
        return getDeviceUserByUserId_DeviceId(userId, device.getDeviceId());
    }

    /**
     * 根据设备Id获取设备详情
     *
     * @param deviceId
     * @return
     * @throws Exception
     */
    @Override
    public Tbl_Device getDeviceById(Integer deviceId) throws Exception {
        Tbl_Device device = null;
        String key = redisKeyHelperI.getTbl_DeviceRedisKeyByDeviceId(deviceId);
        String redisString = redisHelperI.getRedis(key);
        if (StringUtils.isNotBlank(redisString)) {
            device = (Tbl_Device) IfishUtil.JsonToBean(redisString, Tbl_Device.class);
        } else {
            device = tbl_Device_Mapper.getDeviceById(deviceId);
            if (device != null && device.getDeviceId() > 0) {
                redisHelperI.setRedis(key, IfishUtil.ObjectToJson(device));
            }
        }
        return device;
    }

    /**
     * 根据摄像头ID从缓存中取得设备信息
     *
     * @param cameraId
     * @return
     * @throws Exception
     */
    @Override
    public Tbl_Device getDeviceByCameraId(String cameraId) throws Exception {
        Tbl_Device device = null;
        String key = redisKeyHelperI.getTbl_CameraRedisKeyByCameraId(cameraId);
        String redisString = redisHelperI.getRedis(key);
        if (StringUtils.isNotBlank(redisString)) {
            device = (Tbl_Device) IfishUtil.JsonToBean(redisString, Tbl_Device.class);
        } else {
            device = tbl_Device_Mapper.getDeviceByCameraId(cameraId);
            if (device != null && device.getDeviceId() > 0) {
                redisHelperI.setRedis(key, IfishUtil.ObjectToJson(device));
            }
        }
        return device;
    }

    /**
     * 根据设备mac地址获取设备详情
     *
     * @param macAddress
     * @return
     * @throws Exception
     */
    @Override
    public Tbl_Device getDeviceByMacAddress(String macAddress) throws Exception {
        Tbl_Device device = null;
        String key = redisKeyHelperI.getTbl_DeviceRedisKeyByMacAddress(macAddress);
        String redisString = redisHelperI.getRedis(key);
        if (StringUtils.isNotBlank(redisString)) {
            device = (Tbl_Device) IfishUtil.JsonToBean(redisString, Tbl_Device.class);
        } else {
            device = tbl_Device_Mapper.getDeviceByMacAddress(macAddress);
            if (device != null && device.getDeviceId() > 0) {
                redisHelperI.setRedis(key, IfishUtil.ObjectToJson(device));
            }
        }
        return device;
    }

    /**
     * 根据设备ID获取设备统计信息
     *
     * @param deviceId
     * @return
     * @throws Exception
     */
    public Tbl_Device_Statistics getDeviceStatisticsByDeviceId(Integer deviceId) throws Exception {
        Tbl_Device_Statistics device = null;
        String key = redisKeyHelperI.getTbl_Device_StatisticsRedisKeyByDeviceId(deviceId);
        String redisString = redisHelperI.getRedis(key);
        if (StringUtils.isNotBlank(redisString)) {
            device = (Tbl_Device_Statistics) IfishUtil.JsonToBean(redisString, Tbl_Device_Statistics.class);
        } else {
            device = tbl_Device_Mapper.getDevStatisticsByDeviceId(deviceId);
            if (device != null && device.getDeviceId() > 0) {
                redisHelperI.setRedis(key, IfishUtil.ObjectToJson(device));
            }
        }
        return device;
    }

    /**
     * 绑定设备
     *
     * @param userId
     * @param user
     * @param mackAddress
     * @return
     */
    @Override
    public Object bindDevice(Integer userId, String mackAddress) {

        try {
            Tbl_User tmpUser = userHelperI.getUserById(userId);
            //用户存在
            if (tmpUser != null) {
                //新增用户拥有设备
                Tbl_Device_User deviceUser = new Tbl_Device_User();
                Tbl_Device device = getDeviceByMacAddress(mackAddress);
                boolean bln = false;
                //设备存在
                if (device != null) {
                    //关联用户-设备
                    deviceUser.setUserId(tmpUser.getUserId());
                    deviceUser.setDeviceId(device.getDeviceId());
                    //已关联设备的其他用户,这里的用户ID查询条件是不等于<>
                    List<Tbl_Device_User> deviceUserList = tbl_Device_Mapper.getOtherDeviceUsersByOtherUserIdAndDeviceId(tmpUser.getUserId(), device.getDeviceId());
                    //是否已关联这里的用户ID查询是等于=
                    Tbl_Device_User tmpDdeviceUser = tbl_Device_Mapper.getDeviceUsersByUserIdAndDeviceId(tmpUser.getUserId(), device.getDeviceId());
                    //已关联
                    if (tmpDdeviceUser != null) {
                        //原先不是主控制，则删除其他用户关联关系
                        if (!tmpDdeviceUser.getIsMaster().equals("1")) {

                            for (Tbl_Device_User du : deviceUserList) {
                                Integer userid = du.getUserId();
                                Integer deviceId = du.getDeviceId();
                                Tbl_User tu = userHelperI.getUserById(userid);
                                if (tu != null) {
                                    String timestamp = IfishUtil.format(new Date());
                                    //基本参数
                                    Map<String, String> baseMap = new HashMap<String, String>();
                                    baseMap.put("title", PushTypeEnum.remove_device.getValue());
                                    baseMap.put("content", "你已于" + timestamp + "失去对“" + du.getShowName() + "”设备的控制权");
                                    baseMap.put("user_id", tu.getUserId().toString());
                                    baseMap.put("loginType", tu.getLoginType());
                                    //推送参数
                                    Map<String, String> pushMap = new HashMap<String, String>();
                                    pushMap.put("device_id", deviceId.toString());
                                    pushMap.put("device_name", du.getShowName());
                                    pushMap.put("timestamp", timestamp);
                                    pushMap.put("msg_type", PushTypeEnum.remove_device.getKey());
                                    //推送消息
                                    jPushNotifcation(baseMap, pushMap);
                                }
                                tbl_Device_Mapper.deleteDeviceUserById(du.getId());

                            }
                        }
                        //变更为主控
                        tmpDdeviceUser.setIsMaster("1");
                        Date date = new Date();
                        tmpDdeviceUser.setUpdateTime(date);
                        tmpDdeviceUser.setCreateTime(date);
                        tbl_Device_Mapper.updateTblDeviceUser(tmpDdeviceUser);

                        deviceUser.setShowName(tmpDdeviceUser.getShowName());
                        deviceUser.setIsMaster(tmpDdeviceUser.getIsMaster());
                    } //未绑定过
                    else {
                        //删除其他用户控制权
                        for (Tbl_Device_User du : deviceUserList) {
                            Integer userid = du.getUserId();
                            Integer deviceId = du.getDeviceId();
                            Tbl_User tu = userHelperI.getUserById(userid);
                            if (tu != null) {
                                String timestamp = IfishUtil.format(new Date());
                                //基本参数
                                Map<String, String> baseMap = new HashMap<String, String>();
                                baseMap.put("title", PushTypeEnum.remove_device.getValue());
                                baseMap.put("content", "你已于" + timestamp + "失去对“" + du.getShowName() + "”设备的控制权");
                                baseMap.put("user_id", tu.getUserId().toString());
                                baseMap.put("loginType", tu.getLoginType());
                                //推送参数
                                Map<String, String> pushMap = new HashMap<String, String>();
                                pushMap.put("device_id", deviceId.toString());
                                pushMap.put("device_name", du.getShowName());
                                pushMap.put("timestamp", timestamp);
                                pushMap.put("msg_type", PushTypeEnum.remove_device.getKey());
                                //推送消息
                                jPushNotifcation(baseMap, pushMap);
                            }
                            tbl_Device_Mapper.deleteDeviceUserById(du.getId());
                        }
                        //需要新增
                        bln = true;
                        //查询设备统计信息
                        Tbl_Device_Statistics ds = getDeviceStatisticsByDeviceId(device.getDeviceId());
                        //如果设备统计信息为空，新增
                        if (ds == null || ds.getId() <= 0) {
                            ds = new Tbl_Device_Statistics();
                            ds.setDeviceId(device.getDeviceId());
                            ds.setMacAddress(StringUtils.isBlank(device.getMacAddress()) ? null : device.getMacAddress());
                            ds.setLoginCount(1);
                            ds.setLoginTime(new Date());
                            ds.setFirstActivate(new Date());
                            ds.setCreateTime(new Date());
                            ds.setIsCharge("0");
                            ds.setHardwareType(StringUtils.isBlank(device.getHardwareType()) ? null : device.getHardwareType());
                            ds.setFactoryCode(StringUtils.isBlank(device.getFactoryCode()) ? null : device.getFactoryCode());
                            ds.setBrandCode(StringUtils.isBlank(device.getBrandCode()) ? null : device.getBrandCode());
                            tbl_Device_Mapper.insertDeviceStatistics(ds);
                        } else {
                            //修改设备统计信息
                            ds.setFirstActivate(new Date());
                            tbl_Device_Mapper.updateDeviceStatistics(ds);
                        }
                    }
                } //设备不存在
                else {
                    //新增设备信息
                    device = new Tbl_Device();
                    device.setIsBlacklist("1");
                    device.setMacAddress(mackAddress);
                    Date date = new Date();
                    device.setCreateTime(date);
                    int i = tbl_Device_Mapper.insertDevice(device);
                    if (i > 0) {
                        Tbl_Device_Statistics tds = new Tbl_Device_Statistics();
                        tds.setLoginCount(0);
                        tds.setMacAddress(mackAddress);
                        tds.setDeviceId(device.getDeviceId());
                        tds.setFirstActivate(date);
                        tds.setCreateDate(date);
                        tds.setCreateTime(date);
                        tbl_Device_Mapper.insertDeviceStatistics(tds);
                        bln = true;
                        deviceUser.setUserId(tmpUser.getUserId());
                        deviceUser.setDeviceId(device.getDeviceId());
                    }
                }
                //需要新增
                if (bln) {
                    //新增关联关系
                    deviceUser.setShowName("鱼缸" + (int) (Math.random() * 9000 + 1000));
                    deviceUser.setIsMaster("1");
                    Date date = new Date();
                    deviceUser.setUpdateTime(date);
                    deviceUser.setCreateTime(date);
                    tbl_Device_Mapper.insertDeviceUser(deviceUser);
                }
                //封装设备返回信息
                return IfishUtil.returnJson(ResultEnum.success.getKey(), userHelperI.getDeviceInfo(device, deviceUser));
            } else {
                return IfishUtil.returnJson(ResultEnum.warn202.getKey(), "");
            }
        } catch (Exception e) {
            return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
        }
    }

    /**
     * 绑定摄像头
     *
     * @param userId
     * @param cameraId
     * @return
     */
    @Override
    public Object bindCamera(Integer userId, String cameraId) {
        try {
            Tbl_User user = userHelperI.getUserById(userId);
            Tbl_Device camera = getDeviceByCameraId(cameraId);
            //返回数据
            Map<String, Object> dataMap = new HashMap<String, Object>();
            //用户存在
            if (user != null) {
                //摄像头存在
                if (camera != null) {
                    //已关联摄像头的用户
                    List<Tbl_Device_User> CameraUserList = tbl_Device_Mapper.getDeviceUsersByDeviceId(camera.getDeviceId());
                    //删除摄像头与用户关系
                    for (Tbl_Device_User cu : CameraUserList) {
                        //删除摄像头和用户的关系
                        tbl_Device_Mapper.deleteDeviceUserById(cu.getId());
                    }
                } else {
                    //摄像头不存在
                    camera = new Tbl_Device();
                    camera.setCameraId(cameraId);
                    camera.setCreateTime(new Date());
                    camera.setIsCamera("1");
                    tbl_Device_Mapper.insertDevice(camera);
                }
                //建立关系
                Tbl_Device_User device_User = new Tbl_Device_User();
                device_User.setUserId(userId);
                device_User.setIsMaster("1");
                device_User.setIsLook("0");
                device_User.setIsLive("0");
                device_User.setDeviceId(camera.getDeviceId());
                device_User.setShowName("摄像头" + (int) (Math.random() * 900 + 100));
                device_User.setCreateTime(new Date());
                tbl_Device_Mapper.insertDeviceUser(device_User);
                //返回数据
                dataMap.put("cameraId", cameraId);
                dataMap.put("showName", device_User.getShowName());
                dataMap.put("isMaster", device_User.getIsMaster());
                dataMap.put("isLook", device_User.getIsLook());
                dataMap.put("isLive", device_User.getIsLive());
                dataMap.put("isActive", camera.getActiveCode() != null && !camera.getActiveCode().equals("") ? "1" : "0");
                return IfishUtil.returnJson(ResultEnum.success.getKey(), dataMap);
            } else {
                return IfishUtil.returnJson(ResultEnum.warn202.getKey(), "");
            }
        } catch (Exception e) {
            return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
        }
    }

    /**
     * 激活摄像头
     */
    @Override
    public Object activeCamera(String activeCode, String cameraId) {
        try {
            Tbl_Activa_Code activa_Code = tbl_Device_Mapper.getActiva_CodeByCode(activeCode);
            if (activa_Code != null) {
                if (activa_Code.getIsUsed().equals("1")) {
                    return IfishUtil.returnJson(ResultEnum.warn208.getKey(), "");
                } else {
                    Tbl_Device camera = tbl_Device_Mapper.getDeviceByCameraId(cameraId);
                    if (camera != null) {
                        if (StringUtils.isNotBlank(camera.getActiveCode())) {
                            return IfishUtil.returnJson(ResultEnum.success.getKey(), "");
                        } else {
                            Date date = new Date();
                            camera.setActiveCode(activeCode);
                            camera.setActiveTime(date);
                            camera.setUpdateTime(date);
                            int i = tbl_Device_Mapper.updateTbl_Device(camera);

                            activa_Code.setIsUsed("1");
                            tbl_Device_Mapper.updateTblActivaCodeIsUse(activeCode);
                            return IfishUtil.returnJson(ResultEnum.success.getKey(), "");
                        }
                    } else {
                        return IfishUtil.returnJson(ResultEnum.warn210.getKey(), "");
                    }
                }
            } else {
                return IfishUtil.returnJson(ResultEnum.warn209.getKey(), "");
            }
        } catch (Exception e) {
            return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
        }
    }

    /**
     * 修改设备和用户的关系数据
     *
     * @param device
     * @param userId
     * @return
     */
    @Override
    public Object updateDeviceUser(Tbl_Device_User device) {

        try {
            Tbl_Device_User olDevice_User = getDeviceUserByUserId_DeviceId(device.getUserId(), device.getDeviceId());

            if (device != null) {
                if (olDevice_User != null) {
                    device.setId(olDevice_User.getId());
                    int i = tbl_Device_Mapper.updateTblDeviceUser(device);
                    if (i > 0) {
                        redisKeyHelperI.deleteRedisByTbl_Device_User(device);
                        Tbl_Device device1 = getDeviceById(device.getDeviceId());
                        return IfishUtil.returnJson(ResultEnum.success.getKey(), userHelperI.getDeviceInfo(device1, device));
                    }
                }
                return IfishUtil.returnJson(ResultEnum.warn207.getKey(), "");
            } else {
                return IfishUtil.returnJson(ResultEnum.warn207.getKey(), "");
            }
        } catch (Exception e) {
        }
        return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
    }

    /**
     * 修改摄像头信息
     *
     * @param cameraId
     * @param device_User
     * @return
     */
    @Override
    public Object updateCameraUser(Integer cameraId, Tbl_Device_User device_User) {
        try {
            Tbl_Device_User olDevice_User = getDeviceUserByUserId_CameraId(device_User.getUserId(), cameraId.toString());
            if (olDevice_User != null) {
                if (olDevice_User != null) {

                    device_User.setId(olDevice_User.getId());
                    int i = tbl_Device_Mapper.updateTblDeviceUser(device_User);
                    if (i > 0) {
                        redisKeyHelperI.deleteRedisByTbl_Device_User(device_User);
                        Map dataMap = new HashMap();
                        dataMap.put("cameraId", cameraId);
                        dataMap.put("showName", device_User.getShowName());
                        dataMap.put("isMaster", device_User.getIsMaster());
                        dataMap.put("isLook", device_User.getIsLook());
                        dataMap.put("isLive", device_User.getIsLive());
                        Tbl_Device camera = getDeviceById(olDevice_User.getDeviceId());
                        dataMap.put("isActive", camera.getActiveCode() != null && !camera.getActiveCode().equals("") ? "1" : "0");
                        return IfishUtil.returnJson(ResultEnum.success.getKey(), dataMap);
                    }
                }
                return IfishUtil.returnJson(ResultEnum.warn207.getKey(), "");
            } else {
                return IfishUtil.returnJson(ResultEnum.warn207.getKey(), "");
            }
        } catch (Exception e) {
        }
        return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
    }

    /**
     * 解除绑定设备
     *
     * @param deviceUser
     * @return
     */
    @Override
    public Object deleteDeviceUser(Tbl_Device_User deviceUser) {
        try {
            Tbl_Device_User device_User = getDeviceUserByUserId_DeviceId(deviceUser.getUserId(), deviceUser.getDeviceId());
            if (device_User != null) {
                int i = tbl_Device_Mapper.deleteDeviceUserById(device_User.getId());
                if (i > 0) {
                    redisKeyHelperI.deleteRedisByTbl_Device_User(device_User);
                    return IfishUtil.returnJson(ResultEnum.success.getKey(), "");
                }
            }
        } catch (Exception e) {
        }
        return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
    }

    /**
     * 删除绑定摄像头
     *
     * @param userId
     * @param cameraId
     * @return
     */
    @Override
    public Object deleteCameraUser(Integer userId, String cameraId) {
        try {
            Tbl_Device_User device_User = getDeviceUserByUserId_CameraId(userId, cameraId);
            if (device_User != null) {
                int i = tbl_Device_Mapper.deleteDeviceUserById(device_User.getId());
                if (i > 0) {
                    Tbl_Device device = getDeviceByCameraId(cameraId);
                    redisKeyHelperI.deleteRedisByTbl_Device(device);
                    redisKeyHelperI.deleteRedisByTbl_Device_User(device_User);
                    return IfishUtil.returnJson(ResultEnum.success.getKey(), "");
                }
            }
        } catch (Exception e) {
        }
        return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
    }

    /**
     * 极光推送
     *
     * @param userId
     */
    public boolean jPushNotifcation(Map<String, String> baseMap, Map<String, String> pushMap) {
        try {

        } catch (Exception e) {
            throw new RuntimeException();
        }
        return false;
    }
}
