package com.huimv.admin.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huimv.admin.common.utils.DataUill;
import com.huimv.admin.common.utils.Result;
import com.huimv.admin.common.utils.ResultCode;
import com.huimv.admin.entity.*;
import com.huimv.admin.entity.vo.ProdStockVo;
import com.huimv.admin.mapper.*;
import com.huimv.admin.service.IProdStockService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import netscape.javascript.JSObject;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 存栏结构 服务实现类
 * </p>
 *
 * @author author
 * @since 2023-02-22
 */
@Service
public class ProdStockServiceImpl extends ServiceImpl<ProdStockMapper, ProdStock> implements IProdStockService {

    @Autowired
    private ProdStockMapper prodStockMapper;
    @Autowired
    private ProdProductionMapper productionMapper;
    @Autowired
    private ProdSaleMapper saleMapper;
    @Autowired
    private ProdCountMapper prodCountMapper;

    @Autowired
    private ProdYearOutPigMapper prodYearOutPigMapper;

    @Autowired
    private ProdMonthOutPigMapper prodMonthOutPigMapper;

    @Autowired
    private ProdWarningInfoMapper prodWarningInfoMapper;

    @Override
    public Result list(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String farmId = paramsMap.get("farmId");
        String displayType = paramsMap.get("displayType");
        if (StringUtils.isBlank(displayType)){
            displayType = "0";
        }
        QueryWrapper<ProdStock> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("farm_id", farmId);
        queryWrapper.eq("display_type",Integer.parseInt(displayType));
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //格式化时间
        //获取前12个月的第一天
        queryWrapper.ge("creat_time", DateUtil.offsetMonth(new Date(),-12));
        queryWrapper.orderByAsc("creat_time");
        List<ProdStock> prodStocks = prodStockMapper.listDay(queryWrapper);

        QueryWrapper<ProdStock> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("farm_id", farmId).orderByDesc("creat_time").last(" limit 1");
        queryWrapper1.eq("display_type",Integer.parseInt(displayType));
        ProdStock prodStock = prodStockMapper.selectOne(queryWrapper1);
        if (ObjectUtil.isEmpty(prodStock)){
            prodStock = new ProdStock();
            prodStock.setFarmId(Integer.valueOf(farmId));
            prodStock.setDisplayType(Integer.valueOf(displayType));
            prodStock.setZcl(0);
            prodStock.setYfzcl(0);
            prodStock.setByzcl(0);
            prodStock.setZzcl(0);
            prodStock.setBrmzcl(0);
            prodStock.setBrzcl(0);
            prodStock.setCreatTime(new Date());
            prodStock.setGzcl(0);
            prodStock.setHbzcl(0);
            prodStock.setKhzcl(0);
            prodStock.setMzcl(0);
            prodStock.setRszcl(0);
            prodStock.setSpzcl(0);
            prodStockMapper.insert(prodStock);
        }
        ProdStockVo prodStockVo = new ProdStockVo();
        prodStockVo.setCount(0);
        prodStockVo.setProdStock(prodStock);
        prodStockVo.setProdStocks(prodStocks);
        prodStockVo.setMzclTRate("0");
        prodStockVo.setGzclTRate("0");
        prodStockVo.setBrzclTRate("0");
        prodStockVo.setByzclTRate("0");
        prodStockVo.setYfzclRate("0");
        prodStockVo.setHbzclRate("0");
        prodStockVo.setRczclTRate("0");
        prodStockVo.setBrmzclRate("0");
        prodStockVo.setKhzclRate("0");
        prodStockVo.setSpzclRate("0");
        prodStockVo.setZclRate("0");
        prodStockVo.setZzclRate("0");
        Integer count = 0;
        if (ObjectUtil.isNotEmpty(prodStock)){
            count =prodStock.getMzcl() + prodStock.getGzcl() + prodStock.getBrzcl() + prodStock.getByzcl() + prodStock.getYfzcl() +
                    prodStock.getHbzcl() + prodStock.getRszcl() + prodStock.getBrmzcl() + prodStock.getKhzcl() + prodStock.getSpzcl()+prodStock.getZzcl();
            NumberFormat nt = NumberFormat.getPercentInstance();
            nt.setMinimumFractionDigits(2);
            prodStockVo.setCount(count);
            prodStockVo.setProdStock(prodStock);
            prodStockVo.setProdStocks(prodStocks);
            prodStockVo.setMzclTRate(nt.format((double)prodStock.getMzcl()/count));
            prodStockVo.setGzclTRate(nt.format((double) prodStock.getGzcl() / count));
            prodStockVo.setBrzclTRate(nt.format((double) prodStock.getBrzcl() / count));
            prodStockVo.setByzclTRate(nt.format((double) prodStock.getByzcl() / count));
            prodStockVo.setYfzclRate(nt.format((double) prodStock.getYfzcl() / count));
            prodStockVo.setHbzclRate(nt.format((double) prodStock.getHbzcl() / count));
            prodStockVo.setRczclTRate(nt.format((double) prodStock.getRszcl() / count));
            prodStockVo.setBrmzclRate(nt.format((double) prodStock.getBrmzcl() / count));
            prodStockVo.setKhzclRate(nt.format((double) prodStock.getKhzcl() / count));
            prodStockVo.setSpzclRate(nt.format((double) prodStock.getSpzcl() / count));

            prodStockVo.setZclRate(nt.format((double) prodStock.getZcl() / count));
            prodStockVo.setZzclRate(nt.format((double) prodStock.getZzcl() / count));
        }

        return new Result(ResultCode.SUCCESS,prodStockVo);
    }

    @Override
    public Result listStockScreen(HttpServletRequest httpServletRequest, Map<String, String> paramaMap) {
        String farmId = paramaMap.get("farmId");
        String displayType = paramaMap.get("displayType");
        if (StringUtils.isBlank(displayType)){
            displayType = "0";
        }
        QueryWrapper<ProdStock> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("farm_id", farmId);
        queryWrapper.eq("display_type",Integer.parseInt(displayType));
        queryWrapper.orderByDesc("creat_time").last(" limit 1");
        ProdStock prodStock = prodStockMapper.selectOne(queryWrapper);
        JSONObject jsonObject = new JSONObject();

        QueryWrapper<ProdProduction> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("farm_id", farmId).orderByDesc("creat_time").last(" limit 1");
        ProdProduction prodProduction = productionMapper.selectOne(queryWrapper1);

        if (ObjectUtil.isEmpty(prodStock)) {
            jsonObject.put("yfcl", 0);
            jsonObject.put("bycl", 0);
        } else {
            jsonObject.put("yfcl", prodStock.getYfzcl());
            jsonObject.put("bycl", prodStock.getByzcl());
        }
        if (ObjectUtil.isEmpty(prodProduction)) {
            jsonObject.put("chl", 0);
        } else {
            jsonObject.put("chl", prodProduction.getBychl());
        }
        Date timesMonthmorning = DataUill.getTimesMonthmorning();
        QueryWrapper<ProdSale> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("display_type",Integer.parseInt(displayType));
        queryWrapper2.eq("farm_id", farmId).ge("creat_time", timesMonthmorning);
        Integer count = 0;
        List<ProdSale> prodSales = saleMapper.selectList(queryWrapper2);
        if (prodSales.size() == 0) {
            count = 0;
        } else {
            for (ProdSale prodSale : prodSales) {
                count = count + prodSale.getSaleQuantity();
            }
        }

        DateTime dateTime = DateUtil.beginOfYear(new Date());
        QueryWrapper<ProdSale> queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("farm_id", farmId).ge("creat_time",dateTime);
        queryWrapper3.eq("display_type",Integer.parseInt(displayType));
        Integer yearCount = 0;
        List<ProdSale> yearProdSales = saleMapper.selectList(queryWrapper3);
        if (yearProdSales.size() == 0) {
            yearCount = 0;
        } else {
            for (ProdSale prodSale : yearProdSales) {
                yearCount = yearCount + prodSale.getSaleQuantity();
            }
        }

        jsonObject.put("monthCount", count);
        jsonObject.put("yearCount", yearCount);
        return new Result(ResultCode.SUCCESS,jsonObject);
    }

    @Override
    public Result add(HttpServletRequest httpServletRequest, ProdStock prodStock) {
        prodStockMapper.insert(prodStock);
        return Result.SUCCESS();
    }

    @Override
    public Result listStockScreenHenglu(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {

        String farmId = paramsMap.get("farmId");
        String displayType = paramsMap.get("displayType");
        if (StringUtils.isBlank(displayType)){
            displayType = "0";
        }
        DateTime dateTime = DateUtil.offsetDay(new Date(), -8);

        List<ProdStock> prodStocks = prodStockMapper.selectList(new QueryWrapper<ProdStock>().eq("farm_id", farmId).eq("display_type", displayType).ge("creat_time", dateTime));
        ProdCount farm_id = prodCountMapper.selectOne(new QueryWrapper<ProdCount>().eq("farm_id", farmId));
        Map sjtjMap = new HashMap();
        sjtjMap.put("CLCH",100);
        sjtjMap.put("YFCH",100);
        sjtjMap.put("MRWLL",0);
        sjtjMap.put("RZZ",0);
        sjtjMap.put("SWPIG",0);

        Map zjjMap = new HashMap();
        zjjMap.put("BNLJ",0);
        zjjMap.put("YFCL",0);
        zjjMap.put("JRCL",0);
        zjjMap.put("JRJZ",0);


        Map endMap = new HashMap();
        endMap.put("CLBD",new ArrayList<>());
        ProdStock prodStock1 = new ProdStock();
        prodStock1.setDong1(0);
        prodStock1.setDong2(0);
        prodStock1.setDong3(0);
        prodStock1.setDong4(0);
        endMap.put("MCCL",prodStock1);
        endMap.put("SJTJ",sjtjMap);
        if (ObjectUtil.isNotEmpty(prodStocks)){
            ProdStock prodStock = prodStocks.get(prodStocks.size()-1);
            endMap.put("CLBD",prodStocks);
            endMap.put("MCCL",prodStock);
            if (ObjectUtil.isNotEmpty(farm_id)){
                sjtjMap.put("CLCH",prodStock.getCheng());
                sjtjMap.put("SWPIG",prodStock.getSiPig());
                sjtjMap.put("YFCH",farm_id.getYfchl());
                sjtjMap.put("MRWLL",farm_id.getMrwll());
                sjtjMap.put("RZZ",farm_id.getRzz());
            }
            endMap.put("SJTJ",sjtjMap);

            if (ObjectUtil.isNotEmpty(prodStock)){
                zjjMap.put("BNLJ",prodStock.getYearOutPig());
                zjjMap.put("YFCL",prodStock.getYfzcl());
                zjjMap.put("JRCL",prodStock.getOutPig());
                zjjMap.put("JRJZ",prodStock.getInPig());
            }

        }
        return new Result(ResultCode.SUCCESS,endMap);
    }

    @Override
    public Integer sumInPig(Integer farmId, DateTime beginOfMonth) {

        return  prodStockMapper.sumInPig(new QueryWrapper<ProdStock>().eq("farm_id",farmId).eq("display_type",0).ge("creat_time",beginOfMonth));
    }

    @Override
    public Integer sumOutPig(Integer farmId, DateTime beginOfMonth,DateTime endTime) {
//        return  prodStockMapper.sumOutPig(farmId,beginOfMonth.toString().substring(0,10),endTime.toString().substring(0,10));
        return  prodStockMapper.sumOutPig(new QueryWrapper<ProdStock>().eq("farm_id",farmId).eq("display_type",0).between("creat_time",beginOfMonth,endTime));
    }

    @Override
    public Result listStockScreenHengluDay(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String farmId = paramsMap.get("farmId");
        String displayType = paramsMap.get("displayType");
        String pageNum = paramsMap.get("pageNum");
        String pageSize = paramsMap.get("pageSize");
        if ("".equals(pageNum) || null == pageNum) {
            pageNum = "1";
        }
        if ("".equals(pageSize) || null == pageSize) {
            pageSize = "10";
        }
        if (StringUtils.isBlank(displayType)){
            displayType = "0";
        }
        Page<ProdStock> page = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));

        return new Result(ResultCode.SUCCESS,this.page(page,new QueryWrapper<ProdStock>().eq("farm_id",farmId).eq("display_type",displayType).orderByDesc("creat_time")));
    }

    @Override
    public Result listStockScreenHengluYear(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {

        String farmId = paramsMap.get("farmId");
        String displayType = paramsMap.get("displayType");
        String pageNum = paramsMap.get("pageNum");
        String pageSize = paramsMap.get("pageSize");
        if ("".equals(pageNum) || null == pageNum) {
            pageNum = "1";
        }
        if ("".equals(pageSize) || null == pageSize) {
            pageSize = "10";
        }

        Page<ProdYearOutPig> page = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        return new Result(ResultCode.SUCCESS,prodYearOutPigMapper.selectPage(page,new QueryWrapper<ProdYearOutPig>().eq("farm_id",farmId).orderByDesc("creat_time")));
    }

    @Override
    public Result listWarning(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String farmId = paramsMap.get("farmId");
        List<ProdWarningInfo> prodWarningInfos = prodWarningInfoMapper.selectList(new QueryWrapper<ProdWarningInfo>().eq("farm_id", farmId).ge("date", DateUtil.offsetDay(new Date(), -8)).orderByDesc("date"));

        return new Result(ResultCode.SUCCESS,prodWarningInfos);
    }

    @Override
    public Result listStockScreenHengluMonth(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {

        String farmId = paramsMap.get("farmId");
        String displayType = paramsMap.get("displayType");
        String pageNum = paramsMap.get("pageNum");
        String pageSize = paramsMap.get("pageSize");
        if ("".equals(pageNum) || null == pageNum) {
            pageNum = "1";
        }
        if ("".equals(pageSize) || null == pageSize) {
            pageSize = "10";
        }

        Page<ProdMonthOutPig> page = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        return new Result(ResultCode.SUCCESS,prodMonthOutPigMapper.selectPage(page,new QueryWrapper<ProdMonthOutPig>().eq("farm_id",farmId).orderByDesc("date_time")));

    }

    @Override
    public Result listStockScreenHengluSale(HttpServletRequest httpServletRequest, Map<String, String> paramsMap) {
        String farmId = paramsMap.get("farmId");
        String type = paramsMap.get("type");
        String displayType = paramsMap.get("displayType");
        if (StringUtils.isBlank(displayType)){
            displayType = "0";
        }
        QueryWrapper<ProdSale> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("display_type",Integer.parseInt(displayType));
        queryWrapper.eq("farm_id", farmId);
        if (StringUtils.isBlank(type)) {
            type = "1";
        }
       // 1 月
        if ("1".equals(type)) {
            queryWrapper.ge("creat_time", DateUtil.offsetMonth(DateUtil.beginOfMonth(new Date()),-6));
            List<ProdSale> prodSales = saleMapper.listMonth(queryWrapper);
            return new Result(ResultCode.SUCCESS,prodSales);
        } else {
            queryWrapper.ge("creat_time", DateUtil.offsetDay(DateUtil.beginOfDay(new Date()),-7)).orderByAsc("creat_time");

            return new Result(ResultCode.SUCCESS, saleMapper.selectList(queryWrapper));
        }

    }


}
