package com.huimv.apiservice.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huimv.apiservice.dao.PigDao;
import com.huimv.apiservice.dao.YearPigHistoryImgDao;
import com.huimv.apiservice.entity.YearPigBaseEntity;
import com.huimv.apiservice.dao.*;
import com.huimv.apiservice.entity.*;
import com.huimv.apiservice.entity.vo.*;
import com.huimv.apiservice.service.PigService;
import com.huimv.common.exception.RRException;
import com.huimv.common.utils.PageUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 业务层
 * </p>
 *
 * @author yinhao
 * @date 2021/5/8 17:22
 */
@Service
public class PigServiceImpl extends ServiceImpl<PigDao, YearPigBaseEntity> implements PigService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private AnimalHeatDao animalHeatDao;

    @Autowired
    private EatTimeDao eatTimeDao;

    @Autowired
    private PeriodDao periodDao;

    @Autowired
    private IndoorEnvironmentDao indoorEnvironmentDao;

    @Autowired
    private OutdoorEnvironmentDao outdoorEnvironmentDao;

    @Autowired
    private YearPigHistoryImgDao yearPigHistoryImgDao;

    @Autowired
    private SleepStatusDao sleepStatusDao;

    @Autowired
    private SportTimeDao sportTimeDao;

    @Override
    public PigHealthStatusVo getPigInfoByEarTagNo(String pigEarTagNo) {

        //耳标检查
        checkPigEarTagNo(pigEarTagNo);

        //当前时间节点
        DateTime currentTime = DateUtil.date();

//        String lastGetDataTime = (String) redisTemplate.opsForHash().get("offset_record", "getPigInfo");
//        redisTemplate.opsForHash().put("offset_record", "getPigInfo",currentTime.toString());

        PigHealthStatusVo pigHealthStatusVo = new PigHealthStatusVo();
        boolean health = baseMapper.selectHealthStatus(pigEarTagNo);
        pigHealthStatusVo.setHealthStatus(health ? "健康" : "不健康");

        //公用时间 -> 当前日期
        String today = DateUtil.format(currentTime, "yyyy-MM-dd");

        //体温数据sql构建和查询
        LambdaQueryWrapper<AnimalHeatEntity> temperatureLambdaQuery = Wrappers.lambdaQuery();
        temperatureLambdaQuery.eq(AnimalHeatEntity::getEartag, pigEarTagNo)
                .eq(AnimalHeatEntity::getNowDate, today)
                .eq(AnimalHeatEntity::getDeleted, 0)
                .orderByDesc(AnimalHeatEntity::getId);
        List<AnimalHeatVo> animalHeatVoList = animalHeatDao.selectAnimalHeatVoList(temperatureLambdaQuery);
        pigHealthStatusVo.setTemperature(animalHeatVoList);

        //采食状态数据sql构建及查询
        LambdaQueryWrapper<EatTimeEntity> eatTimeLambdaQuery = Wrappers.lambdaQuery();
        eatTimeLambdaQuery.eq(EatTimeEntity::getEartag, pigEarTagNo)
                .eq(EatTimeEntity::getNowDate, today)
                .eq(EatTimeEntity::getDeleted, 0)
                .orderByDesc(EatTimeEntity::getId);
        List<EatTimeVo> eatTimeVoList = eatTimeDao.selectEatTimeVoList(eatTimeLambdaQuery);
        pigHealthStatusVo.setFeedingStatus(eatTimeVoList);

        //睡眠状态数据sql构建及查询
        LambdaQueryWrapper<SleepStatusEntity> sleepStatusLambdaQuery = Wrappers.lambdaQuery();
        sleepStatusLambdaQuery.eq(SleepStatusEntity::getEartag, pigEarTagNo)
                .eq(SleepStatusEntity::getNowDate, today)
                .eq(SleepStatusEntity::getDeleted, 0)
                .orderByDesc(SleepStatusEntity::getId);
        List<SleepStatusVo> sleepStatusVoList = sleepStatusDao.selectSleepStatusVoList(sleepStatusLambdaQuery);
        pigHealthStatusVo.setSleepStatus(sleepStatusVoList);

        //运动状态数据sql构建及查询
        LambdaQueryWrapper<SportTimeEntity> sportStatusLambdaQuery = Wrappers.lambdaQuery();
        sportStatusLambdaQuery.eq(SportTimeEntity::getEartag, pigEarTagNo)
                .eq(SportTimeEntity::getNowDate, today)
                .eq(SportTimeEntity::getDeleted, 0)
                .orderByDesc(SportTimeEntity::getId);
        List<SportTimeVo> sportTimeVoList = sportTimeDao.selectSportTimeVoList(sportStatusLambdaQuery);
        pigHealthStatusVo.setSportStatus(sportTimeVoList);

        return pigHealthStatusVo;
    }


    @Override
    public PigImageVo getImageByEarTagNo(String pigEarTagNo) {

        checkPigEarTagNo(pigEarTagNo);

        PigImageVo pigImageVo = new PigImageVo();

        pigImageVo.setPigEarTagNo(pigEarTagNo);
        List<String> images = yearPigHistoryImgDao.getLatestImgByPigEarTagNo(pigEarTagNo);
        if (CollectionUtil.isNotEmpty(images)) {
            //String encodeImg = Base64.encode(img);
            pigImageVo.setImages(images);
        }
        return pigImageVo;
    }


    @Override
    public PageUtils getPageByBreedAndFence(String breedName, Integer currentPage, Integer pageSize, String period) {

        Integer count = baseMapper.selectCount(Wrappers.<YearPigBaseEntity>lambdaQuery().eq(YearPigBaseEntity::getBreed, breedName));
        if (count <= 0) {
            throw new RRException("品种名称不存在,请检查!", 1001);
        }

        Integer periodId = null;
        if (StringUtils.isNotEmpty(period)) {
            periodId = periodDao.selectIdByPeriodNumber(period);
            if (periodId == null) {
                throw new RRException("栏期编号不存在,请检查!", 1001);
            }
        }


        IPage<PigBaseVo> page = new Page<>(currentPage, pageSize);
        IPage<PigBaseVo> pigBaseVoList = baseMapper.selectPagePigBaseVoByBreedName(page, breedName, periodId);

        return new PageUtils(pigBaseVoList);
    }

    @Override
    public EnvVo getIndoorEnv(String pigEarTagNo) {

        String today = DateUtil.format(DateUtil.date(), "yyyy-MM-dd");

        LambdaQueryWrapper<YearPigBaseEntity> pigBaseLambdaQuery = Wrappers.lambdaQuery();
        pigBaseLambdaQuery.eq(YearPigBaseEntity::getEartag, pigEarTagNo);
        YearPigBaseEntity yearPigBaseEntity = baseMapper.selectOne(pigBaseLambdaQuery);
        if (yearPigBaseEntity == null) {
            throw new RRException("耳标信息不存在,请检查!", 1001);
        }

        EnvVo envVo = new EnvVo();
        envVo.setPigEarTagNo(pigEarTagNo);
        envVo.setDate(today);
        List<IndoorEnvVo> indoorEnvVoList = new ArrayList<>();
        envVo.setIndoorEnvList(indoorEnvVoList);
        List<OutdoorEnvVo> outdoorEnvVoList = new ArrayList<>();
        envVo.setOutdoorEnvList(outdoorEnvVoList);

        Integer pigstyId = yearPigBaseEntity.getPigstyId();
        if (pigstyId != null) {
            LambdaQueryWrapper<IndoorEnvironmentEntity> indoorEnvLambdaQuery = Wrappers.lambdaQuery();
            indoorEnvLambdaQuery.eq(IndoorEnvironmentEntity::getPigstyId, pigstyId)
                    .eq(IndoorEnvironmentEntity::getDate, today)
                    .le(IndoorEnvironmentEntity::getCollectTime, new Date())
                    .orderByDesc(IndoorEnvironmentEntity::getId);
            List<IndoorEnvironmentEntity> indoorEnvironmentEntityList = indoorEnvironmentDao.selectList(indoorEnvLambdaQuery);

            if (CollectionUtil.isNotEmpty(indoorEnvironmentEntityList)) {
                for (IndoorEnvironmentEntity indoorEnvironmentEntity : indoorEnvironmentEntityList) {
                    IndoorEnvVo indoorEnvVo = new IndoorEnvVo();
                    indoorEnvVo.setCollectTime(indoorEnvironmentEntity.getCollectTime());
                    indoorEnvVo.setTemperature(indoorEnvironmentEntity.getTemperature());
                    indoorEnvVo.setHumidity(indoorEnvironmentEntity.getHumidity());
                    indoorEnvVo.setGas(indoorEnvironmentEntity.getGas());
                    indoorEnvVoList.add(indoorEnvVo);
                }
            }
        }

        LambdaQueryWrapper<OutdoorEnvironmentEntity> outdoorEnvLambdaQuery = Wrappers.lambdaQuery();
        outdoorEnvLambdaQuery.eq(OutdoorEnvironmentEntity::getDate, today)
                .le(OutdoorEnvironmentEntity::getCollectTime, new Date())
                .orderByDesc(OutdoorEnvironmentEntity::getId);
        List<OutdoorEnvironmentEntity> outdoorEnvironmentEntityList = outdoorEnvironmentDao.selectList(outdoorEnvLambdaQuery);
        if (CollectionUtil.isNotEmpty(outdoorEnvironmentEntityList)) {
            for (OutdoorEnvironmentEntity outdoorEnvironmentEntity : outdoorEnvironmentEntityList) {
                OutdoorEnvVo outdoorEnvVo = new OutdoorEnvVo();
                outdoorEnvVo.setCollectTime(outdoorEnvironmentEntity.getCollectTime());
                outdoorEnvVo.setTemperature(outdoorEnvironmentEntity.getTemperature());
                outdoorEnvVo.setHumidity(outdoorEnvironmentEntity.getHumidity());
                outdoorEnvVo.setGas(outdoorEnvironmentEntity.getGas());
                outdoorEnvVoList.add(outdoorEnvVo);
            }
        }
        return envVo;
    }

    @Override
    public void adopt(String pigEarTagNo) {

        LambdaQueryWrapper<YearPigBaseEntity> eq = Wrappers.<YearPigBaseEntity>lambdaQuery().eq(YearPigBaseEntity::getEartag, pigEarTagNo);
        YearPigBaseEntity yearPigBaseEntity = baseMapper.selectOne(eq);
        if (yearPigBaseEntity == null) {
            throw new RRException("耳标信息不存在,请检查!", 1001);
        }
        if (yearPigBaseEntity.getFosterStatus()) {
            throw new RRException("本猪已被其他人认养!", 1001);
        }
        LambdaUpdateWrapper<YearPigBaseEntity> pigBaseLambdaUpdate = Wrappers.lambdaUpdate();
        pigBaseLambdaUpdate.eq(YearPigBaseEntity::getEartag, pigEarTagNo)
                .set(YearPigBaseEntity::getFosterStatus, true);

        update(pigBaseLambdaUpdate);
    }

    @Override
    public void outFence(String pigEarTagNo, Integer status) {

        checkPigEarTagNo(pigEarTagNo);

//        if (!status.equals(1) && !status.equals(2) && !status.equals(3)) {
//            throw new RRException("出栏状态有误,请检查!", 1001);
//        }
        LambdaQueryWrapper<YearPigBaseEntity> pigBaseLambdaQuery = Wrappers.lambdaQuery();
        pigBaseLambdaQuery.eq(YearPigBaseEntity::getEartag, pigEarTagNo);
        YearPigBaseEntity yearPigBaseEntity = baseMapper.selectOne(pigBaseLambdaQuery);
        Integer outFenceStatus = yearPigBaseEntity.getOutFenceStatus();
        if (outFenceStatus != null) {
            if (outFenceStatus.equals(1) || outFenceStatus.equals(2) || outFenceStatus.equals(3)) {
                throw new RRException("该猪已出栏,不可重复出栏!", 1001);
            }
        }

        LambdaUpdateWrapper<YearPigBaseEntity> pigBaseLambdaUpdate = Wrappers.lambdaUpdate();
        pigBaseLambdaUpdate.eq(YearPigBaseEntity::getEartag, pigEarTagNo)
                .set(YearPigBaseEntity::getDeleted, System.currentTimeMillis())
                .set(YearPigBaseEntity::getFosterStatus, false)
                .set(YearPigBaseEntity::getOutFenceTime, new Date())
                .set(YearPigBaseEntity::getOutFenceStatus, status);

        update(pigBaseLambdaUpdate);

    }

    /**
     * 公用检查耳标方法
     *
     * @param pigEarTagNo 耳标号
     */
    private void checkPigEarTagNo(String pigEarTagNo) {

        Integer count = baseMapper.selectCount(Wrappers.<YearPigBaseEntity>lambdaQuery().eq(YearPigBaseEntity::getEartag, pigEarTagNo));
        if (count <= 0) {
            throw new RRException("耳标信息不存在,请检查!", 1001);
        }
    }

}
