package xiaoqu.home.open.service.db1.impl;

import xiaoqu.home.open.model.db1.UserDistrictAttendance;
import xiaoqu.home.open.mapper.db1.UserDistrictAttendanceMapper;
import xiaoqu.home.open.service.db1.UserDistrictAttendanceService;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户站点考勤 服务实现类
 * </p>
 *
 * @author wh
 * @since 2022-10-27
 */
@Service
public class UserDistrictAttendanceServiceImpl extends ServiceImpl<UserDistrictAttendanceMapper, UserDistrictAttendance> implements UserDistrictAttendanceService {
	@Resource(name = "redisTemplate4")
	private RedisTemplate<String, String> redisTemplate4;

	@Override
	public void updateMysqlAndReis(UserDistrictAttendance userDistrictAttendance) {
		updateById(userDistrictAttendance);
		userDistrictAttendance = getById(userDistrictAttendance.getId());
		redisTemplate4.opsForValue().set("entity:UserDistrictAttendance:" + userDistrictAttendance.getUserId() + "_" + userDistrictAttendance.getDistrictId(), JSON.toJSONString(userDistrictAttendance, SerializerFeature.WriteMapNullValue));
	}

	@Override
	public void saveMysqlAndReis(UserDistrictAttendance userDistrictAttendance) {
		save(userDistrictAttendance);
		redisTemplate4.opsForValue().set("entity:UserDistrictAttendance:" + userDistrictAttendance.getUserId() + "_" + userDistrictAttendance.getDistrictId(), JSON.toJSONString(userDistrictAttendance, SerializerFeature.WriteMapNullValue));
	}

	@Override
	public UserDistrictAttendance getUserDistrictAttendance(Long districtId, Long userId) {
		String key = "entity:UserDistrictAttendance:" + userId + "_" + districtId;
		String jsonString = redisTemplate4.opsForValue().get(key);
		UserDistrictAttendance userDistrictAttendance = null;
		if (jsonString != null) {
			userDistrictAttendance = JSON.parseObject(jsonString, UserDistrictAttendance.class);
		} else {
			QueryWrapper<UserDistrictAttendance> queryWrapper = new QueryWrapper<UserDistrictAttendance>();
			queryWrapper.eq("district_id", districtId);
			queryWrapper.eq("user_id", userId);
			userDistrictAttendance = getOne(queryWrapper);
			if (userDistrictAttendance == null) {
				userDistrictAttendance = new UserDistrictAttendance();
				userDistrictAttendance.setUserId(userId);
				userDistrictAttendance.setDistrictId(districtId);
				userDistrictAttendance.setWorkAtStatus(2);
				userDistrictAttendance.setWorkStatus(1);
				saveMysqlAndReis(userDistrictAttendance);
			}
		}
		return userDistrictAttendance;
	}

}
