/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.modular.feed.feedingfat.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.modular.base.pigpen.entity.BasePigpen;
import vip.xiaonuo.modular.base.pigpen.mapper.BasePigpenMapper;
import vip.xiaonuo.modular.bi.utils.DataUill;
import vip.xiaonuo.modular.feed.feedingenv.entity.FeedingEnv;
import vip.xiaonuo.modular.feed.feedingenv.mapper.FeedingEnvMapper;
import vip.xiaonuo.modular.feed.feedingfat.entity.FeedingFat;
import vip.xiaonuo.modular.feed.feedingfat.mapper.FeedingFatMapper;
import vip.xiaonuo.modular.feed.feedingfat.param.*;
import vip.xiaonuo.modular.feed.feedingfat.service.FeedingFatService;
import vip.xiaonuo.modular.feed.feedingfat.vo.*;
import vip.xiaonuo.modular.feed.feedinglist.entity.FeedingList;
import vip.xiaonuo.modular.feed.feedinglist.mapper.FeedingListMapper;
import vip.xiaonuo.modular.feed.feedinglist.vo.FeedingListVo;
import vip.xiaonuo.modular.feed.feedinglist.vo.FeedingListVo2;


import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 精准饲喂母猪采食Service接口实现类
 *
 * @author wang
 * @date 2023/12/28 09:22
 **/
@Service
public class FeedingFatServiceImpl extends ServiceImpl<FeedingFatMapper, FeedingFat> implements FeedingFatService {
    @Autowired
    private FeedingFatMapper fatMapper;
    @Autowired
    private FeedingEnvMapper envMapper;
    @Autowired
    private BasePigpenMapper pigpenMapper;
    @Autowired
    private FeedingListMapper feedingListMapper;


    @Override
    public FeedingFatVo listFat(FeedingFatAddParam feedingFatAddParam) {
        String orgId = feedingFatAddParam.getOrgId();
        String unitId = feedingFatAddParam.getUnitId();
        QueryWrapper<BasePigpen> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("org_id", orgId).eq("id", unitId);
        List<BasePigpen> basePigpens = pigpenMapper.selectList(queryWrapper);
        List<String> idList = new ArrayList<>();
        if (basePigpens.size() != 0) {
            basePigpens.forEach(item -> {
                idList.add(item.getId());
            });
        }
        QueryWrapper<FeedingEnv> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("org_id", orgId);
        if (idList.size() != 0) {
            queryWrapper1.in("unit_id", idList);
        }
        FeedingEnv feedingEnv = envMapper.selectOne(queryWrapper1);
//        List<String> unitList = new ArrayList<>();
//        envs.forEach(i->{
//            unitList.add(i.getDeviceCode());
//        });
        FeedingFatVo feed = fatMapper.getFeed(feedingEnv.getDeviceCode(), orgId);
        QueryWrapper<FeedingFat> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("device_code", feedingEnv.getDeviceCode()).eq("org_id", orgId)
                .orderByDesc("id").last(" limit 1");
        FeedingFat feedingFat = fatMapper.selectOne(queryWrapper2);
        feed.setRank(feedingFat.getRank());
        feed.setFatCount(Integer.parseInt(feedingEnv.getPigNum()));
        return feed;
    }

    @Override
    public IPage<FeedingFatVo> fatPage(FeedingFatPageParam feedingFatPageParam) {
        String orgId = feedingFatPageParam.getOrgId();
        Integer pageNum = feedingFatPageParam.getCurrent();
        Integer pageSize = feedingFatPageParam.getSize();
        String eartagNum = feedingFatPageParam.getEartagNum();
        String startDate = feedingFatPageParam.getStartDate();
        String endDate = feedingFatPageParam.getEndDate();
        QueryWrapper<FeedingFat> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("org_id", orgId)
                .like(StringUtils.isNotBlank(eartagNum), "eartag_num", eartagNum)
                .or().like(StringUtils.isNotBlank(eartagNum), "device_code", eartagNum)
                .between(StringUtils.isNotBlank(startDate), "create_time", startDate, endDate);
        Page<FeedingFat> page = new Page<>(pageNum, pageSize);
        IPage<FeedingFatVo> fatVoIPage = fatMapper.listFeedPage(page, queryWrapper);
        return fatVoIPage;
    }

    @Override
    public List<FeedingFatVo2> listDetail(FeedingFatEditParam feedingFatEditParam) {
        String orgId = feedingFatEditParam.getOrgId();
        String eartagNum = feedingFatEditParam.getEartagNum();
        String dataType = feedingFatEditParam.getDataType();//数据类型 1为采食 2为体温 3为活跃量 4为膘体
        String timeType = feedingFatEditParam.getTimeType();//时间类型 1为今日 2为本周 3为本月 4为自定义
        if ("".equals(timeType) || null == timeType) {
            timeType = "1";
        }
        List<FeedingFatVo2> list = new ArrayList<>();
        QueryWrapper<FeedingFat> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("org_id", orgId).eq("eartag_num", eartagNum);
        Date timesmorning = DataUill.getTimesmorning();
        DateTime dateTime = DateUtil.beginOfWeek(new Date());
        Date monthmorning = DataUill.getTimesMonthmorning();
        if ("1".equals(dataType)) {
            if ("1".equals(timeType)) {
                queryWrapper.ge("create_time", timesmorning).orderByAsc("create_time");
                List<FeedingFat> fats = fatMapper.selectList(queryWrapper);
                for (FeedingFat fat : fats) {
                    FeedingFatVo2 fatVo2 = new FeedingFatVo2();
                    fatVo2.setValue(fat.getFeedValue());
                    fatVo2.setCreateDate(fat.getCreateTime());
                    list.add(fatVo2);
                }
            } else if ("2".equals(timeType)) {
                queryWrapper.ge("create_time", dateTime);
                list = fatMapper.listFeedDetail(queryWrapper);
            } else if ("3".equals(timeType)) {
                queryWrapper.ge("create_time", monthmorning);
                list = fatMapper.listFeedDetail(queryWrapper);
            } else if ("4".equals(timeType)) {
                String startTime = feedingFatEditParam.getStartTime() + " 00:00:00";
                String endTime = feedingFatEditParam.getEndTime() + " 23:59:59";
                queryWrapper.between("create_time", startTime, endTime);
                list = fatMapper.listFeedDetail(queryWrapper);
            }
        }
        if ("2".equals(dataType)) {
            if ("1".equals(timeType)) {
                queryWrapper.ge("create_time", timesmorning).orderByAsc("create_time");
                List<FeedingFat> fats = fatMapper.selectList(queryWrapper);
                for (FeedingFat fat : fats) {
                    FeedingFatVo2 fatVo2 = new FeedingFatVo2();
                    fatVo2.setValue(fat.getTemp());
                    fatVo2.setCreateDate(fat.getCreateTime());
                    list.add(fatVo2);
                }
            } else if ("2".equals(timeType)) {
                queryWrapper.ge("create_time", dateTime);
                list = fatMapper.listTempDetail(queryWrapper);
            } else if ("3".equals(timeType)) {
                queryWrapper.ge("create_time", monthmorning);
                list = fatMapper.listTempDetail(queryWrapper);
            } else if ("4".equals(timeType)) {
                String startTime = feedingFatEditParam.getStartTime() + " 00:00:00";
                String endTime = feedingFatEditParam.getEndTime() + " 23:59:59";
                queryWrapper.between("create_time", startTime, endTime);
                list = fatMapper.listTempDetail(queryWrapper);
            }
        }
        if ("3".equals(dataType)) {
            if ("1".equals(timeType)) {
                queryWrapper.ge("create_time", timesmorning).orderByAsc("create_time");
                List<FeedingFat> fats = fatMapper.selectList(queryWrapper);
                for (FeedingFat fat : fats) {
                    FeedingFatVo2 fatVo2 = new FeedingFatVo2();
                    fatVo2.setValue(fat.getFeedAct());
                    fatVo2.setCreateDate(fat.getCreateTime());
                    list.add(fatVo2);
                }
            } else if ("2".equals(timeType)) {
                queryWrapper.ge("create_time", dateTime);
                list = fatMapper.listActDetail(queryWrapper);
            } else if ("3".equals(timeType)) {
                queryWrapper.ge("create_time", monthmorning);
                list = fatMapper.listActDetail(queryWrapper);
            } else if ("4".equals(timeType)) {
                String startTime = feedingFatEditParam.getStartTime() + " 00:00:00";
                String endTime = feedingFatEditParam.getEndTime() + " 23:59:59";
                queryWrapper.between("create_time", startTime, endTime);
                list = fatMapper.listActDetail(queryWrapper);
            }
        }
        if ("4".equals(dataType)) {
            if ("1".equals(timeType)) {
                queryWrapper.ge("create_time", timesmorning).orderByAsc("create_time");
                List<FeedingFat> fats = fatMapper.selectList(queryWrapper);
                for (FeedingFat fat : fats) {
                    FeedingFatVo2 fatVo2 = new FeedingFatVo2();
                    fatVo2.setValue(fat.getWeigthValue());
                    fatVo2.setCreateDate(fat.getCreateTime());
                    list.add(fatVo2);
                }
            } else if ("2".equals(timeType)) {
                queryWrapper.ge("create_time", dateTime);
                list = fatMapper.listWeightDetail(queryWrapper);
            } else if ("3".equals(timeType)) {
                queryWrapper.ge("create_time", monthmorning);
                list = fatMapper.listWeightDetail(queryWrapper);
            } else if ("4".equals(timeType)) {
                String startTime = feedingFatEditParam.getStartTime() + " 00:00:00";
                String endTime = feedingFatEditParam.getEndTime() + " 23:59:59";
                queryWrapper.between("create_time", startTime, endTime);
                list = fatMapper.listWeightDetail(queryWrapper);
            }
        }
        return list;
    }

    @Override
    public FeedingFatMoveVo listFatMove(FeedingFatMoveParam fatMoveParam) {
        Date timesmorning = DataUill.getTimesmorning();
        QueryWrapper<FeedingFat> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("org_id", fatMoveParam.getOrgId());
        //全场
        FeedingFatMoveVo feedingFatMoveVo = fatMapper.listFatMove(queryWrapper);
        List<FeedingListVo> feedingListVos = feedingListMapper.listFeed(new QueryWrapper<FeedingList>()
                .eq("org_id", fatMoveParam.getOrgId()));
        feedingFatMoveVo.setFeedingName(feedingListVos);
        JSONArray jsonArray = new JSONArray();
        for (FeedingListVo feedingListVo : feedingListVos) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("feedName", feedingListVo.getUnitName());
            List<FeedingFatVo2> list = feedingListMapper.feedMove(new QueryWrapper<FeedingList>()
                    .eq("org_id", fatMoveParam.getOrgId()).
                    eq("unit_id", feedingListVo.getUnitId()).ge("create_time", timesmorning));
            jsonObject.put("value", list);
            jsonArray.add(jsonObject);
        }
        feedingFatMoveVo.setJsonArray(jsonArray);
        return feedingFatMoveVo;
    }

    @Override
    public FeedingFatMoveVo2 listFatByUnitId(FeedingFatMove2Param fatMove2Param) {
        Date timesmorning = DataUill.getTimesmorning();
        QueryWrapper<BasePigpen> basePigpenQueryWrapper = new QueryWrapper<>();
        basePigpenQueryWrapper.eq("org_id", fatMove2Param.getOrgId())
                .like("pids", fatMove2Param.getUnitId()).eq("type", 2);
        List<BasePigpen> basePigpens = pigpenMapper.selectList(basePigpenQueryWrapper);
        List<String> idList = new ArrayList<>();
        basePigpens.forEach(item->{
            idList.add(item.getId());
        });

        FeedingFatMoveVo2 vo2 = new FeedingFatMoveVo2();
        QueryWrapper<FeedingFat> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("org_id", fatMove2Param.getOrgId()).in("unit_id", idList)
                .ge("create_time", timesmorning);
        if ("1".equals(fatMove2Param.getType())) {
            FeedingFatMoveVo feedingFatMoveVo = fatMapper.listFatMove(queryWrapper);//今日采食和饮水
            List<FeedingFatVo2> list = fatMapper.listFeeding(queryWrapper);//采食
            List<FeedingFatVo2> list1 = fatMapper.listFeeding(queryWrapper);//饮水
            List<FeedingFatVo2> list2 = fatMapper.listFeeding(queryWrapper);//料肉比
            vo2.setTodayFeed(feedingFatMoveVo.getTodayFeed());
            vo2.setTodayWater(feedingFatMoveVo.getTodayWater());
            vo2.setFeedingList(list);
            vo2.setWaterList(list1);
            vo2.setBodyList(list2);
        }
        if ("2".equals(fatMove2Param.getType())) {
            FeedingFatMoveVo feedingFatMoveVo = fatMapper.listFatMove(queryWrapper);//今日采食和饮水
            Date monthmorning = DataUill.getTimesMonthmorning();
            QueryWrapper<FeedingFat> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("org_id", fatMove2Param.getOrgId()).in("unit_id", idList)
                    .ge("create_time", monthmorning);
            List<FeedingFatVo2> list = fatMapper.listMonthFeeding(queryWrapper1);
            List<FeedingFatVo2> list1 = fatMapper.listMonthWater(queryWrapper1);
            List<FeedingFatVo2> list2 = fatMapper.listMonthweigth(queryWrapper1);
            vo2.setTodayFeed(feedingFatMoveVo.getTodayFeed());
            vo2.setTodayWater(feedingFatMoveVo.getTodayWater());
            vo2.setFeedingList(list);
            vo2.setWaterList(list1);
            vo2.setBodyList(list2);
        }
        return vo2;
    }

    @Override
    public List<FeedingFatVo2> feedingDay(FeedingFatMoveParam fatMoveParam) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - 7);
        QueryWrapper<FeedingFat> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("org_id", fatMoveParam.getOrgId());
        List<FeedingFatVo2> list = fatMapper.listMonthFeeding(queryWrapper);
        return list;
    }

    @Override
    public List<FeedingFatScreenVo> feedScreen(FeedingFatScreenParam fatScreenParam) {
        String eartag = fatScreenParam.getEartag();
        Date yesterdaymorning = DataUill.getYesterdaymorning();
        Date timesmorning = DataUill.getTimesmorning();
        QueryWrapper<FeedingFat> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("org_id", fatScreenParam.getOrgId())
                .eq(StringUtils.isNotBlank(eartag), "eartag_num", eartag);
        if ("1".equals(fatScreenParam.getTimeType())) {
            queryWrapper.ge("create_time", timesmorning);
        }
        if ("2".equals(fatScreenParam.getTimeType())) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(yesterdaymorning);
            String endTime = format + " 23:59:59";
            queryWrapper.between("create_time", yesterdaymorning, endTime);
        }
        List<FeedingFatScreenVo> feedingFatScreenVos = fatMapper.feedingScreen(queryWrapper);
        return feedingFatScreenVos;
    }

    @Override
    public List<FeedingFatScreenVo> feedFatScreen(FeedingFatScreenParam fatScreenParam) {
        String eartag = fatScreenParam.getEartag();//为单元名称
        Date yesterdaymorning = DataUill.getYesterdaymorning();
        Date timesmorning = DataUill.getTimesmorning();
        QueryWrapper<FeedingFat> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("org_id", fatScreenParam.getOrgId())
                .eq(StringUtils.isNotBlank(eartag), "unit_name", eartag);
        if ("1".equals(fatScreenParam.getTimeType())) {
            queryWrapper.ge("create_time", timesmorning);
        }
        if ("2".equals(fatScreenParam.getTimeType())) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(yesterdaymorning);
            String endTime = format + " 23:59:59";
            queryWrapper.between("create_time", yesterdaymorning, endTime);
        }
        List<FeedingFatScreenVo> feedingFatScreenVos = fatMapper.feedingScreen(queryWrapper);
        return feedingFatScreenVos;
    }


}
