package xiaoqu.home.open.task;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import xiaoqu.home.open.model.db1.District;
import xiaoqu.home.open.model.db1.User;
import xiaoqu.home.open.model.db1.UserDistrictAttendance;
import xiaoqu.home.open.model.db1.Watch;
import xiaoqu.home.open.model.db2.RestRecord;
import xiaoqu.home.open.mqtt.MqttPushClient;
import xiaoqu.home.open.publicBean.WatchShockAndVoiceMessage;
import xiaoqu.home.open.service.RedisService5;
import xiaoqu.home.open.service.db1.DistrictService;
import xiaoqu.home.open.service.db1.UserDistrictAttendanceService;
import xiaoqu.home.open.service.db1.UserService;
import xiaoqu.home.open.service.db1.WatchService;
import xiaoqu.home.open.service.db2.RestRecordService;
import xiaoqu.home.open.utils.WrapperUtils;

/**
 * xxl_job任务
 */
@Component
@Slf4j(topic = "Controller")
public class XxlJobTask {

	@Autowired
	private RedisService5 redisService5;
	@Autowired
	private DistrictService districtService;
	@Autowired
	private UserService userService;
	@Autowired
	private RestRecordService restRecordService;
	@Autowired
	private WatchService watchService;
	
	@Autowired
	private UserDistrictAttendanceService userDistrictAttendanceService;
	

	@Autowired
	private MqttPushClient mqttPushClient;
	
	/**
	 * 打卡倒计时
	 *
	 * @return
	 */
	@XxlJob("InitWatch")
	public void InitWatch() {
		QueryWrapper<Watch> wrapperWatch = WrapperUtils.getWrapper(false);
		wrapperWatch.eq("bind_status", 1);
		List<Watch> watchs = watchService.list(wrapperWatch);
		for (Watch watch : watchs) {
			WatchShockAndVoiceMessage watchShockAndVoiceMessage = new WatchShockAndVoiceMessage();
			watchShockAndVoiceMessage.setMessageType(8);
			watchShockAndVoiceMessage.setShockState(watch.getStockStatus());
			watchShockAndVoiceMessage.setVoiceState(watch.getVoiceStatus());
			watchShockAndVoiceMessage.setVoiceValue(watch.getVoiceValue());
			watchShockAndVoiceMessage.setImei(watch.getImei());
			watchShockAndVoiceMessage.setBlueWorkState(watch.getBlueWorkState());
			mqttPushClient.publish(1, true, watch.getImei(), JSON.toJSONString(watchShockAndVoiceMessage));
		}
	}

	/**
	 * 打卡倒计时
	 *
	 * @return
	 */
	@XxlJob("restCountDown")
	public void restCountDown() {
		Set<String> userIdSet = redisService5.rangeByScore("CleaningRestLastTime", 0, System.currentTimeMillis());
		if (userIdSet.size() > 0) {
			for (String userId_districtId : userIdSet) {
				redisService5.zRemove("CleaningRestLastTime", userId_districtId);// 移除监控
				String[] userIdAndDistrictId = userId_districtId.split("_");
				District district = districtService.getById(userIdAndDistrictId[1]);
				RestRecord restRecord = new RestRecord();
				restRecord.setAgentId(district.getAgentId());
				restRecord.setPropertyId(district.getPropertyId());
				restRecord.setDistrictId(district.getId());
				restRecord.setDistrictName(district.getDistrictName());
				restRecord.setPunchTime(new Date());
				restRecord.setCreateId(-99L);
				restRecord.setPunchType(1);
				restRecord.setGpsPositionAddress("");
				restRecord.setUserId(Long.parseLong(userIdAndDistrictId[0]));
				restRecord.setRestDate(DateUtil.format(new Date(), "yyyy-MM-dd"));
				User user = userService.getById(userIdAndDistrictId[0]);
				restRecord.setUserMobile(user.getMobile());
				restRecord.setUserName(user.getName());
				String currentDate = DateUtil.format(new Date(), "yyyy-MM-dd");
				QueryWrapper<RestRecord> queryWrapper = Wrappers.query();
				queryWrapper.eq("district_id", district.getId());
				queryWrapper.eq("user_id", user.getId());
				queryWrapper.eq("rest_date", currentDate);
				queryWrapper.last("limit 1");
				queryWrapper.orderByDesc("id");
				RestRecord temrestRecord = restRecordService.getOne(queryWrapper);
				if (temrestRecord != null && temrestRecord.getPunchType() == 1) {
					return;
				}
				Long temRestTime = DateUtil.between(new Date(), temrestRecord.getPunchTime(), DateUnit.SECOND);
				restRecord.setRestTime(temRestTime.intValue());
				restRecordService.save(restRecord);
				XxlJobHelper.log(user.getName() + "休息倒计时结束");
				log.info(user.getName() + "休息倒计时结束");
				String cleaningUpWorkAtStatus = redisService5.get("CleaningUpWorkAtStatus:" + user.getMobile());
				UserDistrictAttendance userDistrictAttendance = userDistrictAttendanceService.getUserDistrictAttendance(district.getId(), user.getId());
				if (cleaningUpWorkAtStatus == null) {
					userDistrictAttendance.setWorkAtStatus(Integer.parseInt(cleaningUpWorkAtStatus));

				} else {
					userDistrictAttendance.setWorkAtStatus(2);// 默认空闲
				}
				userDistrictAttendanceService.updateMysqlAndReis(userDistrictAttendance);
			}
		}

	}

}
