package xiaoqu.home.open.task;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.annotations.JsonAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import xiaoqu.home.open.entity.BeaconDevice;
import xiaoqu.home.open.model.db1.*;
import xiaoqu.home.open.service.RedisService5;
import xiaoqu.home.open.service.db1.*;
import xiaoqu.home.open.utils.DateToConverter;
import xiaoqu.home.open.utils.WrapperUtils;

import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class LocationTask {

    @Autowired
    private RedisTemplate<String, String> redisTemplate4;

    @Autowired
    private RedisService5 redisService5;

    @Autowired
    private WatchService watchService;

    @Autowired
    private BeaconService beaconService;

    @Autowired
    private UserLocationService userLocationService;
    @Autowired
    private ToiletService toiletService;
    @Autowired
    private PositionsService positionsService;
    @Autowired
    private UserTrajectoryService userTrajectoryService;

    /**
     *
     */
    @Scheduled(cron = "* * * * * ?")
    public void BleutoothLocationTask() {
        String bleutoothLocationQueue = redisTemplate4.opsForList().rightPop("BleutoothLocationQueue");
        while (bleutoothLocationQueue != null) {
            log.info("【BleutoothLocationTask】" + bleutoothLocationQueue);
            Date date = new Date();
            try {
                BeaconDevice beaconDevice = JSONObject.parseObject(bleutoothLocationQueue, BeaconDevice.class);
                QueryWrapper<Beacon> wrapperBeacon = WrapperUtils.getWrapper(false);
                wrapperBeacon.eq("mac", beaconDevice.getMac());
                Beacon beacon = beaconService.getOne(wrapperBeacon);
                Integer curRssi = beaconDevice.getRssi();
                Integer rssiThreshold = beacon.getRssiThreshold();
                //进入范围
                UserLocation userLocation = new UserLocation();
                userLocation.setUserId(beaconDevice.getUserId());

                userLocation.setAgentId(beacon.getAgentId());
                userLocation.setAgentName(beacon.getAgentName());
                userLocation.setPropertyId(beacon.getPropertyId());
                userLocation.setPropertyName(beacon.getPropertyName());
                userLocation.setDistrictId(beacon.getDistrictId());
                userLocation.setDistrictName(beacon.getDistrictName());
                userLocation.setBeaconMac(beacon.getMac());
                userLocation.setBeaconName(beacon.getName());
                userLocation.setSceneName(beacon.getSceneName());
                userLocation.setSceneId(beacon.getSceneId());
                userLocation.setSceneLevel(beacon.getSceneLevel());
                userLocation.setRssi(beaconDevice.getRssi().toString());
                userLocation.setBeaconId(beacon.getId());
                userLocation.setBroadcastInterval(beacon.getBroadcastInterval());
                userLocation.setTransRate(beacon.getTransRate());
                userLocation.setSuperiorGridName(beacon.getMultistageGridName());
                userLocation.setBeaconPower(beacon.getPower());
                userLocation.setCreateTime(date);
                if(beacon.getSceneId()!=null){
                    Toilet toilet = toiletService.getById(beacon.getSceneId());
                    if(beacon.getSceneLevel()==1){
                        if(toilet!=null){
                            userLocation.setMemo(toilet.getSuperiorGridName()+"->"+toilet.getName());
                        }
                    }else if(beacon.getSceneLevel()==2){
                        Positions positions = positionsService.getById(beacon.getSceneId());
                        if(positions!=null){
                            userLocation.setMemo(positions.getSuperiorGridName()+"->"+positions.getName());
                        }
                    }
                }
                QueryWrapper<Watch> wrapperWatch = WrapperUtils.getWrapper(false);
                wrapperWatch.eq("imei", beaconDevice.getImei());
                Watch watch = watchService.getOne(wrapperWatch);
                if (watch != null) {
                    userLocation.setWatchId(watch.getId());
                    userLocation.setWatchImei(beaconDevice.getImei());
                    userLocation.setWatchPower(watch.getWatchBattery());
                    userLocation.setUserName(watch.getUserName());
                    userLocation.setMobile(watch.getMobile());
                }
                userLocationService.save(userLocation);
                if (rssiThreshold == null) {
                    rssiThreshold = -90;
                }
                if (rssiThreshold <= curRssi) {

                    QueryWrapper<UserTrajectory> wrapperUserTrajectory = WrapperUtils.getWrapper(false);

                    wrapperUserTrajectory.eq("user_id", userLocation.getUserId());
//                    wrapperUserTrajectory.eq("scene_id", userLocation.getSceneId());
//                    wrapperUserTrajectory.eq("scene_level", userLocation.getSceneLevel());
                    wrapperUserTrajectory.eq("status", 0);
                    List<UserTrajectory> listUserTrajectory = userTrajectoryService.list(wrapperUserTrajectory);

                    if (listUserTrajectory.isEmpty()) {
                        setUserTrajectory(date, beacon, userLocation);
                    } else {
                        for (UserTrajectory userTrajectory : listUserTrajectory) {
                            int betweenTime = DateToConverter.daysBetween(userTrajectory.getModifyTime(), date, 2);

                            if (userTrajectory.getSceneId().longValue() == userLocation.getSceneId().longValue()) {
                                if(betweenTime<5){
                                    userTrajectory.setModifyTime(date);
                                    int daysBetween = DateToConverter.daysBetween(userTrajectory.getCreateTime(), userTrajectory.getModifyTime(), 2);
                                    userTrajectory.setResidenceTime(daysBetween * 60);
                                    userTrajectoryService.updateById(userTrajectory);
                                }else{

                                    userTrajectory.setDepartureTime(new Date());
                                    userTrajectory.setStatus(1);
                                    userTrajectoryService.updateById(userTrajectory);
                                    setUserTrajectory(date, beacon, userLocation);
                                }

                            } else {
//                                userTrajectory.setStatus(0);
                                userTrajectory.setModifyTime(date);
                                int daysBetween = DateToConverter.daysBetween(userTrajectory.getCreateTime(), userTrajectory.getModifyTime(), 2);
                                userTrajectory.setResidenceTime(daysBetween * 60);
                                userTrajectory.setDepartureTime(new Date());

                                userTrajectory.setStatus(1);
                                userTrajectoryService.updateById(userTrajectory);
                                setUserTrajectory(date, beacon, userLocation);
                                break;

                            }
                        }
                    }

                }
                bleutoothLocationQueue = redisTemplate4.opsForList().rightPop("BleutoothLocationQueue");
                log.info("【overdueTaskStatusTask】next:" + bleutoothLocationQueue);

            } catch (Exception e) {
                e.printStackTrace();
                log.error("【overdueTaskStatusTask】" + bleutoothLocationQueue);
                bleutoothLocationQueue = redisTemplate4.opsForList().rightPop("BleutoothLocationQueue");
                continue;
            }

        }


    }

    /**
     *
     */
    @Scheduled(cron = "* * * * * ?")
    public void OffDutyBleutoothLocationTask() {
        String json = redisTemplate4.opsForList().rightPop("OffDutyBleutoothLocationQueue");
        while (json != null) {
            log.info("【OffDutyBleutoothLocationTask】" + json);
            JSONObject jsonObject = JSONObject.parseObject(json);
            QueryWrapper<UserTrajectory> wrapperUserTrajectory = WrapperUtils.getWrapper(false);

            wrapperUserTrajectory.eq("user_id", jsonObject.getLong("userId"));
            wrapperUserTrajectory.eq("district_id", jsonObject.getLong("districtId"));
            wrapperUserTrajectory.eq("status", 0);
            List<UserTrajectory> listUserTrajectory = userTrajectoryService.list(wrapperUserTrajectory);
            for (UserTrajectory userTrajectory : listUserTrajectory) {
                userTrajectory.setModifyTime(new Date());
                userTrajectory.setDepartureTime(new Date());
                userTrajectory.setStatus(0);
                int daysBetween = DateToConverter.daysBetween(userTrajectory.getCreateTime(), userTrajectory.getModifyTime(), 2);
                userTrajectory.setResidenceTime(daysBetween * 60);
                userTrajectory.setStatus(1);
                userTrajectoryService.updateById(userTrajectory);
            }
            json = redisTemplate4.opsForList().rightPop("OffDutyBleutoothLocationQueue");

        }
    }

    private void setUserTrajectory(Date date, Beacon beacon, UserLocation userLocation) {
        UserTrajectory userTrajectory = new UserTrajectory();
        BeanUtils.copyProperties(userLocation, userTrajectory);
        userTrajectory.setId(null);
        userTrajectory.setCreateTime(date);
        userTrajectory.setResidenceTime(60);
        userTrajectory.setBeaconAreaPositionId(beacon.getBeaconAreaPositionId());
        userTrajectory.setCoordinateX(beacon.getCoordinateX());
        userTrajectory.setCoordinateY(beacon.getCoordinateY());
        userTrajectory.setStatus(0);
        //人员定位
        redisService5.set("Location:" + userLocation.getUserId(),DateToConverter.getFormattedDate(date,5)+"_"+beacon.getSceneName()+"_"+beacon.getBuildingId()+"_"+beacon.getFloorId());
        userTrajectoryService.save(userTrajectory);
    }

}
