package com.zehong.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zehong.common.core.redis.RedisCache;
import com.zehong.common.exception.CustomException;
import com.zehong.common.utils.DateUtils;
import com.zehong.common.utils.SecurityUtils;
import com.zehong.common.utils.StringUtils;
import com.zehong.common.utils.http.HttpUtils;
import com.zehong.system.domain.TUserGps;
import com.zehong.system.domain.TWarningInfo;
import com.zehong.system.mapper.TUserGpsMapper;
import com.zehong.system.mapper.TWarningInfoMapper;
import com.zehong.system.service.ITWarningInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 警告提醒Service业务层处理
 * 
 * @author zehong
 * @date 2024-09-05
 */
@Service
public class TWarningInfoServiceImpl implements ITWarningInfoService 
{
    private static final Logger logger = LoggerFactory.getLogger(TWarningInfoServiceImpl.class);

    @Autowired
    private TWarningInfoMapper tWarningInfoMapper;

    @Resource
    private TUserGpsMapper tUserGpsMapper;

    @Value("${gps.moreDeviceTrack}")
    private String moreDeviceTrack;

    @Autowired
    private RedisCache redisCache;

    /**
     * 查询警告提醒
     * 
     * @param warningId 警告提醒ID
     * @return 警告提醒
     */
    @Override
    public TWarningInfo selectTWarningInfoById(Long warningId)
    {
        return tWarningInfoMapper.selectTWarningInfoById(warningId);
    }

    /**
     * 查询警告提醒列表
     * 
     * @param tWarningInfo 警告提醒
     * @return 警告提醒
     */
    @Override
    public List<TWarningInfo> selectTWarningInfoList(TWarningInfo tWarningInfo)
    {
        return tWarningInfoMapper.selectTWarningInfoList(tWarningInfo);
    }

    /**
     * 新增警告提醒
     * 
     * @param tWarningInfo 警告提醒
     * @return 结果
     */
    @Override
    public int insertTWarningInfo(TWarningInfo tWarningInfo)
    {
        return tWarningInfoMapper.insertTWarningInfo(tWarningInfo);
    }

    /**
     * 修改警告提醒
     * 
     * @param tWarningInfo 警告提醒
     * @return 结果
     */
    @Override
    public int updateTWarningInfo(TWarningInfo tWarningInfo)
    {
        tWarningInfo.setUpdateTime(DateUtils.getNowDate());
        return tWarningInfoMapper.updateTWarningInfo(tWarningInfo);
    }

    /**
     * 批量删除警告提醒
     * 
     * @param warningIds 需要删除的警告提醒ID
     * @return 结果
     */
    @Override
    public int deleteTWarningInfoByIds(Long[] warningIds)
    {
        return tWarningInfoMapper.deleteTWarningInfoByIds(warningIds);
    }

    /**
     * 删除警告提醒信息
     * 
     * @param warningId 警告提醒ID
     * @return 结果
     */
    @Override
    public int deleteTWarningInfoById(Long warningId)
    {
        return tWarningInfoMapper.deleteTWarningInfoById(warningId);
    }

    /**
     * 自动处理警告信息
     */
    @Override
    public void autoInsertWarningInfo(){
        //获取所有gps设备
        List<TUserGps> userGpsList = tUserGpsMapper.selectTUserGpsList(new TUserGps());
        String ids = userGpsList.stream().map(item -> item.getImei()).collect(Collectors.joining(","));
        if(StringUtils.isNotEmpty(ids)){
            String result = HttpUtils.sendGet(moreDeviceTrack,"ids=" + ids + "&mapType=gaode&key=20161222HLXTJDMW730XY");
            JSONObject resultJson = JSON.parseObject(result);
            if(StringUtils.isEmpty(result) && !"0".equals(resultJson.getString("state"))) throw new CustomException("获取gps接口错误:" + result);
            JSONArray gpsInfo = JSONObject.parseArray(resultJson.getString("devices"));
            //防止有人员与设备重复绑定遍历赋值
            gpsInfo.stream().forEach(deviceInfo ->{
                if(cacheWarningInfo(deviceInfo)){
                    String sn = ((JSONObject) deviceInfo).getString("sn");
                    List<TUserGps> matchUserGps = userGpsList.stream().filter(item -> item.getImei().equals(sn)).collect(Collectors.toList());
                    for(TUserGps user : matchUserGps){
                        logger.info(">>>>>>>>>sn>>>>>>>>>" + sn);
                        JSONObject cache = redisCache.getCacheMapValue("gpsCacheInfo",sn);
                        if(null != cache){
                            logger.info("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<cache>>>>>>>>>>>>>>>>>>>>>" + cache.toString());
                            String positionTime = cache.getString("positionTime");
                            //插入警告信息
                            TWarningInfo warningInfo = new TWarningInfo();
                            warningInfo.setUserId(user.getUserId());
                            warningInfo.setDeviceCode(sn);
                            warningInfo.setStopTime(DateUtils.parseDate(positionTime));
                            tWarningInfoMapper.insertTWarningInfo(warningInfo);
                            redisCache.redisTemplate.opsForHash().delete("gpsCacheInfo",sn);
                        }
                    }
                }

            });
        }

    }

    /**
     * 缓存警报信息
     * @param gpsPositionInfo gps信息
     * @return
     */
    private boolean cacheWarningInfo(Object gpsPositionInfo){
        String[] status = ((JSONObject)gpsPositionInfo).getString("status").split("-");
        String gpsCode = ((JSONObject)gpsPositionInfo).getString("sn");
        Object cache = redisCache.getCacheMapValue("gpsCacheInfo",gpsCode);
        if(null != cache) {
            Long interval = DateUtils.parseDate(((JSONObject)gpsPositionInfo).getString("positionTime")).getTime() - DateUtils.parseDate(((JSONObject)cache).getString("positionTime")).getTime();
            //0:未启用,1:运动,2:静止,3:离线
            if("2".equals(status[0]) && interval/1000/60 > 30){
                return true;
            }
            if("1".equals(status[0]) || "3".equals(status[0]) || "0".equals(status[0])){
                redisCache.redisTemplate.opsForHash().delete("gpsCacheInfo",gpsCode);
            }
            return false;
        }
        if ("2".equals(status[0]))redisCache.setCacheMapValue("gpsCacheInfo",gpsCode,gpsPositionInfo);
        return false;
    }


    /**
     * 解除警报
     * @param warningId 警报主键
     * @return
     */
    @Override
    public int freeWarningInfo(Long warningId){
        TWarningInfo warningInfo = tWarningInfoMapper.selectTWarningInfoById(warningId);
        TWarningInfo updateWarn = new TWarningInfo();
        updateWarn.setWarningId(warningId);
        updateWarn.setWarnStatus("1");
        updateWarn.setUpdateTime(new Date());
        updateWarn.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        int result = tWarningInfoMapper.updateTWarningInfo(updateWarn);
        if(result > 0) redisCache.redisTemplate.opsForHash().delete("gpsCacheInfo",warningInfo.getDeviceCode());
        return result;
    }


}
