package com.huimv.apiservice.service.impl;


import cn.hutool.core.collection.CollectionUtil;
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.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 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 Map<String, Object> getPigInfoByEarTagNo(String pigEarTagNo) {

        checkPigEarTagNo(pigEarTagNo);

        Map<String, Object> result = new LinkedHashMap<>(16);
        List<Map<String, Object>> temperature = new ArrayList<>();
        List<Map<String, Object>> feedingStatus = new ArrayList<>();
        List<Map<String, Object>> sleepStatus = new ArrayList<>();
        List<Map<String, Object>> sportStatus = new ArrayList<>();
        result.put("temperature", temperature);
        result.put("feedingStatus", feedingStatus);

        boolean health = baseMapper.selectHealthStatus(pigEarTagNo);
        result.put("healthStatus", health ? "健康" : "不健康");
        result.put("sleepStatus", sleepStatus);
        result.put("sportStatus", sportStatus);


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


        //java代码对集合排序
        //CollectionUtil.sort(animalHeatEntityList,(o1, o2) -> o2.getCollectTime().compareTo(o1.getCollectTime()));

        //体温数据sql构建和查询
        LambdaQueryWrapper<AnimalHeatEntity> temperatureLambdaQuery = Wrappers.lambdaQuery();
        temperatureLambdaQuery.eq(AnimalHeatEntity::getEartag, pigEarTagNo)
                .eq(AnimalHeatEntity::getNowDate, today)
                .orderByDesc(AnimalHeatEntity::getId);
        List<AnimalHeatEntity> animalHeatEntityList = animalHeatDao.selectList(temperatureLambdaQuery);

        //体温数据
        if (CollectionUtil.isNotEmpty(animalHeatEntityList)) {
            for (AnimalHeatEntity animalHeatEntity : animalHeatEntityList) {
                Map<String, Object> dataMap = new LinkedHashMap<>(16);
                dataMap.put("collectTime", DateUtil.format(animalHeatEntity.getCollectTime(), "yyyy-MM-dd HH:mm:ss"));
                dataMap.put("temperature", animalHeatEntity.getTemperature());
                temperature.add(dataMap);
            }
        }

        //健康状态数据sql构建及查询
        //TODO 健康状态数据库查询
        //模拟数据
        //Map<String, Object> healthData1 = new HashMap<>();
        //healthData1.put(DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss"), "健康");
        //Map<String, Object> healthData2 = new HashMap<>();
        //healthData2.put(DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss"), "亚健康");
        //healthStatus.add(healthData1);
        //healthStatus.add(healthData2);

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

        //采食状态数据
        if (CollectionUtil.isNotEmpty(eatTimeEntityList)) {
            for (EatTimeEntity eatTimeEntity : eatTimeEntityList) {
                Map<String, Object> dataMap = new LinkedHashMap<>(16);
                dataMap.put("collectTime", DateUtil.format(eatTimeEntity.getCollectTime(), "yyyy-MM-dd HH:mm:ss"));
                dataMap.put("feedCount", eatTimeEntity.getEatCount());
                feedingStatus.add(dataMap);
            }
        }

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

        //睡眠状态数据
        if (CollectionUtil.isNotEmpty(sleepStatusEntityList)) {
            for (SleepStatusEntity sleepStatusEntity : sleepStatusEntityList) {
                Map<String, Object> dataMap = new LinkedHashMap<>(16);
                dataMap.put("sleepStartTime", sleepStatusEntity.getSleepTime());
                dataMap.put("duration", sleepStatusEntity.getSleepCount());
                sleepStatus.add(dataMap);
            }
        }

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

        //运动状态数据
        if (CollectionUtil.isNotEmpty(sportTimeEntityList)) {
            for (SportTimeEntity sportTimeEntity : sportTimeEntityList) {
                Map<String, Object> dataMap = new LinkedHashMap<>(16);
                dataMap.put("collectTime", sportTimeEntity.getCollectTime());
                dataMap.put("sportCount", sportTimeEntity.getSportCount());
                sportStatus.add(dataMap);
            }
        }

        return result;
    }


    @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) {

//        if (StringUtils.isEmpty(breedName)) {
//            throw new RRException("品种名称不能为空!", 1001);
//        }

        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)
                    .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)
                .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, true)
                .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);
        }
    }

}
