package xiaoqu.home.open.task;

import java.util.Date;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

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

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import xiaoqu.home.open.entity.XxlJobInfo;
import xiaoqu.home.open.model.db1.User;
import xiaoqu.home.open.model.db1.UserDistrictAttendance;
import xiaoqu.home.open.model.db1.UserRest;
import xiaoqu.home.open.model.db2.ChangeLog;
import xiaoqu.home.open.model.db2.RestRecord;
import xiaoqu.home.open.model.db2.TaskDistrictParam;
import xiaoqu.home.open.publicBean.AttendanceStatusMessage;
import xiaoqu.home.open.service.db1.UserDistrictAttendanceService;
import xiaoqu.home.open.service.db1.UserRestService;
import xiaoqu.home.open.service.db1.UserService;
import xiaoqu.home.open.service.db2.ChangeLogService;
import xiaoqu.home.open.service.db2.RestRecordService;
import xiaoqu.home.open.service.db2.TaskDistrictParamService;
import xiaoqu.home.open.utils.DateToConverter;
import xiaoqu.home.open.utils.WrapperUtils;
import xiaoqu.home.open.utils.XxlJobUtil;

@Component
@Slf4j(topic = "task")
public class UserRestTask {
    @Autowired
    private UserRestService userRestService;

    @Autowired
    private UserService userService;
    @Autowired
    XxlJobUtil XxlJobUtil;
    @Autowired
    private ChangeLogService changeLogService;
    @Autowired
    private UserDistrictAttendanceService userDistrictAttendanceService;
    @Autowired
    private TaskDistrictParamService taskDistrictParamService;
    @Autowired
    private RestRecordService restRecordService;
    
	@Resource(name = "redisTemplate5")
	private RedisTemplate<String, String> redisTemplate;
	@Resource(name = "redisTemplate4")
	private RedisTemplate<String, String> redisTemplate4;


    @XxlJob("userRestStartTask")
    public ReturnT<String> userRestStartTask() {
        String jobParam = XxlJobHelper.getJobParam();
        log.info("【userRestStartTask】计划起止" + jobParam);
        if (jobParam != null) {

            UserRest userRest = userRestService.getById(jobParam);
            UserDistrictAttendance userDistrictAttendance = userDistrictAttendanceService.getUserDistrictAttendance(userRest.getDistrictId(), userRest.getUserId());
            User user = userService.getById(userRest.getUserId());
            RestRecord restRecord = new RestRecord();
    		restRecord.setAgentId(userRest.getAgentId());
    		restRecord.setPropertyId(userRest.getPropertyId());
    		restRecord.setDistrictId(userRest.getDistrictId());
    		restRecord.setDistrictName(userRest.getDistrictName());
    		restRecord.setPunchTime(new Date());
    		restRecord.setPunchType(0);
    		restRecord.setGpsPositionAddress("自动休息");
    		restRecord.setUserId(userRest.getUserId());
    		restRecord.setRestDate(DateUtil.format(new Date(), "yyyy-MM-dd"));
    		restRecord.setUserMobile(user.getMobile());
    		restRecord.setUserName(userRest.getUserName());
    		restRecordService.save(restRecord);
    		
			TaskDistrictParam taskDistrictParam = taskDistrictParamService.getOne(new QueryWrapper<TaskDistrictParam>().eq("district_id", userRest.getDistrictId()));
			Integer restTime = 60;
			if (taskDistrictParam != null) {
				restTime = taskDistrictParam.getUserRestDuration();
			}
			String currentDate = DateUtil.format(new Date(), "yyyy-MM-dd");
			QueryWrapper<RestRecord> queryWrapper = WrapperUtils.getWrapper(false);
			queryWrapper.eq("district_id", userRest.getDistrictId());
			queryWrapper.eq("user_id", user.getId());
			queryWrapper.eq("rest_date", currentDate);
			queryWrapper.select("IFNULL(SUM(rest_time),0) restTime");
			Map<String, Object> sumMap = restRecordService.getMap(queryWrapper);
			Integer actrestTime = Integer.parseInt(sumMap.get("restTime") + "");
			Long tempCha = DateUtil.offset(new Date(), DateField.SECOND, restTime * 60 - actrestTime).getTime();
			redisTemplate.opsForZSet().add("CleaningRestLastTime", user.getId() + "_" + userRest.getDistrictId(), tempCha.doubleValue());
			AttendanceStatusMessage attendanceStatusMessage = new AttendanceStatusMessage();
			attendanceStatusMessage.setMessageType(5);
			attendanceStatusMessage.setUserId(userDistrictAttendance.getUserId());
			attendanceStatusMessage.setAction(0);
			redisTemplate4.opsForList().leftPush("AttendanceStatusMessage", JSON.toJSONString(attendanceStatusMessage));

			//记录原始状态
			redisTemplate.opsForValue().set("CleaningUpWorkAtStatus:" + user.getMobile(), userDistrictAttendance.getWorkAtStatus() + "");
			
            String workAtStatus = userDistrictAttendance.getWorkAtStatus().toString();
            userDistrictAttendance.setWorkAtStatus(3);
            userDistrictAttendance.setModifyTime(new Date());
            userDistrictAttendanceService.updateMysqlAndReis(userDistrictAttendance);
            //插入日志
            ChangeLog changeLog = new ChangeLog();
            changeLog.setCreateId(userRest.getUserId());
            changeLog.setCreateName(userRest.getUserName());
            changeLog.setCreateTime(new Date());
            changeLog.setTableName("User");
            changeLog.setContext(userRest.getDistrictName()+userRest.getUserName() + "开始休息,id:" + jobParam);
            changeLog.setActionType(1);
            changeLog.setSource(2);
            try {
                changeLogService.save(changeLog);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //插入下次计划
            createXxlJob(userRest, jobParam,0,workAtStatus);
            createXxlJob(userRest, jobParam,1,workAtStatus);

        }
        return ReturnT.SUCCESS;
    }


    private void createXxlJob(UserRest userRest, String jobParam, Integer type,String workAtStatus) {
        XxlJobInfo jobInfo2 = new XxlJobInfo();
        jobInfo2.setAddTime(new Date());
        jobInfo2.setAuthor("后台创建");
        jobInfo2.setExecutorBlockStrategy("SERIAL_EXECUTION");
        jobInfo2.setExecutorFailRetryCount(0);
        jobInfo2.setExecutorRouteStrategy("ROUND");// 轮训
        jobInfo2.setExecutorTimeout(3000);
        jobInfo2.setGlueRemark("GLUE代码初始化");
        jobInfo2.setGlueType("BEAN");
        jobInfo2.setScheduleType("CRON");
        jobInfo2.setMisfireStrategy("DO_NOTHING");
        jobInfo2.setTriggerStatus(1);

        //下次的开始休息
        if (type == 0) {

            String time = null;
            String curTimeStr = DateToConverter.getFormattedDate(new Date(), 0);
            Date date = DateToConverter.parseDate(curTimeStr + " " + userRest.getStartRestTime() + ":00", 5);
            Date curdate = new Date();
            if (curdate.getTime() < date.getTime()) {
                time = DateToConverter.getCron(date);
            } else {
                time = DateToConverter.getCron(DateToConverter.parseDate(DateToConverter.getDateAddOrSub(5, 1, date), 5));
            }
            jobInfo2.setExecutorParam(jobParam);
            jobInfo2.setExecutorHandler("userRestStartTask");
            jobInfo2.setScheduleConf(time);
            jobInfo2.setJobDesc("人员休息" + jobParam);
            //结束休息
        } else {
            jobInfo2.setExecutorParam(jobParam+"_"+workAtStatus);
            String time = null;
            String curTimeStr = DateToConverter.getFormattedDate(new Date(), 0);
            Date date = DateToConverter.parseDate(curTimeStr + " " + userRest.getEndRestTime() + ":00", 5);
            time = DateToConverter.getCron(date);
            jobInfo2.setExecutorHandler("userRestEndTask");
            jobInfo2.setScheduleConf(time);
            jobInfo2.setJobDesc("人员恢复" + jobParam);
        }
        String returns = XxlJobUtil.addAndStart(jobInfo2);
        log.info("【createXxlJob】" + jobParam+":"+returns);

    }


    @XxlJob("userRestEndTask")
    public ReturnT<String> userRestEndTask() {
        String jobParam = XxlJobHelper.getJobParam();
        log.info("【userRestEndTask】计划起止" + jobParam);
        if (jobParam != null) {
            String[] params = jobParam.split("_");
            UserRest userRest = userRestService.getById(params[0]);
            UserDistrictAttendance userDistrictAttendance = userDistrictAttendanceService.getUserDistrictAttendance(userRest.getDistrictId(), userRest.getUserId());
            User user = userService.getById(userRest.getUserId());
            RestRecord restRecord = new RestRecord();
    		restRecord.setAgentId(userRest.getAgentId());
    		restRecord.setPropertyId(userRest.getPropertyId());
    		restRecord.setDistrictId(userRest.getDistrictId());
    		restRecord.setDistrictName(userRest.getDistrictName());
    		restRecord.setPunchTime(new Date());
    		restRecord.setPunchType(1);
    		restRecord.setGpsPositionAddress("自动上班");
    		restRecord.setUserId(userRest.getUserId());
    		restRecord.setRestDate(DateUtil.format(new Date(), "yyyy-MM-dd"));
    		restRecord.setUserMobile(user.getMobile());
    		restRecord.setUserName(userRest.getUserName());
    		restRecordService.save(restRecord);
    		//手动休息没修改xxl的这个参数，所以用我原来的存储方式
//            String status = params[1];
//            Integer workAtStatus = Integer.valueOf(status);
//            if(workAtStatus!=3){
//                userDistrictAttendance.setWorkAtStatus(workAtStatus);
//
//            }else{
//                userDistrictAttendance.setWorkAtStatus(0);
//
//            }
//            userDistrictAttendance.setModifyTime(new Date());
//            userDistrictAttendanceService.updateMysqlAndReis(userDistrictAttendance);
            
            String cleaningUpWorkAtStatus = redisTemplate.opsForValue().get("CleaningUpWorkAtStatus:" + user.getMobile());
			if (cleaningUpWorkAtStatus == null) {
				userDistrictAttendance.setWorkAtStatus(Integer.parseInt(cleaningUpWorkAtStatus));

			} else {
				userDistrictAttendance.setWorkAtStatus(2);// 默认空闲
			}
			userDistrictAttendanceService.updateMysqlAndReis(userDistrictAttendance);
            
            String currentDate = DateUtil.format(new Date(), "yyyy-MM-dd");
			QueryWrapper<RestRecord> queryWrapper = WrapperUtils.getWrapper(false);
			queryWrapper.eq("district_id", userRest.getDistrictId());
			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) {
				Long temRestTime = DateUtil.between(new Date(), temrestRecord.getPunchTime(), DateUnit.SECOND);
				restRecord.setRestTime(temRestTime.intValue());
			} else {
				restRecord.setRestTime(0);
			}
			redisTemplate.opsForZSet().remove("CleaningRestLastTime", user.getId() + "_" + userRest.getDistrictId());
			AttendanceStatusMessage attendanceStatusMessage = new AttendanceStatusMessage();
			attendanceStatusMessage.setMessageType(5);
			attendanceStatusMessage.setUserId(userDistrictAttendance.getUserId());
			attendanceStatusMessage.setAction(1);
			redisTemplate4.opsForList().leftPush("AttendanceStatusMessage", JSON.toJSONString(attendanceStatusMessage));
            //插入日志
            ChangeLog changeLog = new ChangeLog();
            changeLog.setCreateId(userRest.getUserId());
            changeLog.setCreateName(userRest.getUserName());
            changeLog.setCreateTime(new Date());
            changeLog.setTableName("User");
            changeLog.setContext(userRest.getDistrictName()+userRest.getUserName() + "从休息恢复状态,id:" + jobParam);
            changeLog.setActionType(1);
            changeLog.setSource(2);
            try {
                changeLogService.save(changeLog);
            } catch (Exception e) {
                e.printStackTrace();
            }
            redisTemplate.opsForSet().add("RepeatTaskQueue", userRest.getDistrictId() + "");


        }
        return ReturnT.SUCCESS;

    }

}
