package com.huimv.produce.produce.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.huimv.common.utils.Result;
import com.huimv.common.utils.ResultCode;
import com.huimv.produce.produce.entity.ProdWeightDayEntity;
import com.huimv.produce.produce.entity.ProdWeightDetailsEntity;
import com.huimv.produce.produce.repo.*;
import com.huimv.produce.produce.service.IWeight;
import com.huimv.produce.produce.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.*;

/**
 * @Project : huimv.shiwan
 * @Package : com.huimv.biosafety.uface.controller
 * @Description : TODO
 * @Version : 1.0
 * @Author : ZhuoNing
 * @Create : 2020-12-25
 **/
@Service
@Slf4j
public class WeightImpl implements IWeight {
    @Autowired
    private ProdDayWeightRepo dayWeightRepo;
    @Autowired
    private ProdBatchWeightRepo batchWeightRepo;
    @Autowired
    private ProdWeightRepo weightRepo;
    @Autowired
    private DateUtil dateUtil;
    @Resource
    private RestTemplate restTemplate;
    @Autowired
    private ProdWeightDetailsRepo prodWeightDetailsRepo;
    @Autowired
    private ProdWeightDayRepo prodWeightDayRepo;
    @Value("${weight.http}")
    private String weightHttp;
    @Value("${weight.path}")
    private String weightPath;

    @Override
    public Result getEggWeightDetails(String todayDate) throws ParseException {
//        String url = "http://39.171.45.196:9200/egg/getWeightDetails?date=2022-06-10";
//        String url = "http://39.171.45.196:9200/egg/getWeightDetails";

        // 获取今天数据
        if(StringUtils.isBlank(todayDate)){
            todayDate = new DateUtil().getTodayDateText();
        }
        String url = weightHttp + weightPath + "?date=" + todayDate;
        System.out.println("url=" + url);
        String result = restTemplate.getForObject(url, String.class);
        JSONArray resultJa = JSONArray.parseArray(result);

        // 保存每天明细
        saveWeightDetails(resultJa, todayDate);

        // 保存汇总每天总重
        saveDayWeight(resultJa, todayDate);

        return new Result(ResultCode.SUCCESS);
    }

    @Override
    public Result autoGenerateDayWeight() throws ParseException {
//        String url = "http://39.171.45.196:9200/egg/getWeightDetails?date=2022-06-10";
//        String url = "http://39.171.45.196:9200/egg/getWeightDetails";

        // 获取今天数据
        String todayDate = new DateUtil().getTodayDateText();
        String url = weightHttp + weightPath + "?date=" + todayDate;
        System.out.println("url=" + url);
        String result = restTemplate.getForObject(url, String.class);
        JSONArray resultJa = JSONArray.parseArray(result);
        log.info("接口返回数量=" + resultJa.size());

        // 保存每天明细
        saveWeightDetails(resultJa, todayDate);

        // 保存汇总每天总重
        saveDayWeight(resultJa, todayDate);

        return new Result(ResultCode.SUCCESS);
    }



    /**
     * @Method : saveDayWeight
     * @Description :
     * @Params : [resultJa, todayDate]
     * @Return : void
     * @Author : ZhuoNing
     * @Date : 2022/7/2
     * @Time : 4:08
     */
    private void saveDayWeight(JSONArray resultJa, String todayDate) throws ParseException {
        JSONArray purchaseJa = new JSONArray();
        JSONArray salesJa = new JSONArray();
        JSONArray otherJa = new JSONArray();
        for (int a = 0; a < resultJa.size(); a++) {
            JSONObject resultJo = resultJa.getJSONObject(a);
            if (resultJo.getString("poundType").equalsIgnoreCase("Purchase")) {
                purchaseJa.add(resultJo);
            } else if (resultJo.getString("poundType").equalsIgnoreCase("Sales")) {
                salesJa.add(resultJo);
            } else {
                otherJa.add(resultJo);
            }
        }
        //
        List<ProdWeightDayEntity> ProdWeightDayEntityList = getDayWeightList(todayDate);
        prodWeightDayRepo.deleteAll(ProdWeightDayEntityList);

        // 添加采购每日汇总
        if(purchaseJa.size()>0){
            BigDecimal grossTotalPurchaseBg = new BigDecimal("0");
            BigDecimal tareTotalPurchaseBg = new BigDecimal("0");
            BigDecimal netTotalPurchaseBg = new BigDecimal("0");
            for (int a = 0; a < purchaseJa.size(); a++) {
                JSONObject purchaseJo = purchaseJa.getJSONObject(a);
                BigDecimal gw = purchaseJo.getBigDecimal("grossWeight");
                if (gw == null) {
                    gw = new BigDecimal("0");
                }
                grossTotalPurchaseBg = grossTotalPurchaseBg.add(gw);
                BigDecimal tw = purchaseJo.getBigDecimal("tareWeight");
                if (tw == null) {
                    tw = new BigDecimal("0");
                }
                tareTotalPurchaseBg = tareTotalPurchaseBg.add(tw);
                BigDecimal nw = purchaseJo.getBigDecimal("netWeight");
                if (nw == null) {
                    nw = new BigDecimal("0");
                }
                netTotalPurchaseBg = netTotalPurchaseBg.add(nw);
            }
            ProdWeightDayEntity purchaseWeightDayEntity = new ProdWeightDayEntity();
            purchaseWeightDayEntity.setAddDate(new java.sql.Date(dateUtil.parseDate(todayDate).getTime()));
            purchaseWeightDayEntity.setGrossWeight(grossTotalPurchaseBg.floatValue());
            purchaseWeightDayEntity.setTareWeight(tareTotalPurchaseBg.floatValue());
            purchaseWeightDayEntity.setNetWeight(netTotalPurchaseBg.floatValue());
            purchaseWeightDayEntity.setPoundType("Purchase");
            prodWeightDayRepo.save(purchaseWeightDayEntity);
        }

        // 添加销售每日汇总
        if(salesJa.size()>0){
            BigDecimal grossTotalSalesBg = new BigDecimal("0");
            BigDecimal tareTotalSalesBg = new BigDecimal("0");
            BigDecimal netTotalSalesBg = new BigDecimal("0");
            for (int a = 0; a < salesJa.size(); a++) {
                JSONObject salesJo = salesJa.getJSONObject(a);
                BigDecimal gw = salesJo.getBigDecimal("grossWeight");
                if (gw == null) {
                    gw = new BigDecimal("0");
                }
                grossTotalSalesBg = grossTotalSalesBg.add(gw);
                BigDecimal tw = salesJo.getBigDecimal("tareWeight");
                if (tw == null) {
                    tw = new BigDecimal("0");
                }
                tareTotalSalesBg = tareTotalSalesBg.add(tw);
                BigDecimal nw = salesJo.getBigDecimal("netWeight");
                if (nw == null) {
                    nw = new BigDecimal("0");
                }
                netTotalSalesBg = netTotalSalesBg.add(nw);
            }
            ProdWeightDayEntity salesWeightDayEntity = new ProdWeightDayEntity();
            salesWeightDayEntity.setAddDate(new java.sql.Date(dateUtil.parseDate(todayDate).getTime()));
            salesWeightDayEntity.setGrossWeight(grossTotalSalesBg.floatValue());
            salesWeightDayEntity.setTareWeight(tareTotalSalesBg.floatValue());
            salesWeightDayEntity.setNetWeight(netTotalSalesBg.floatValue());
            salesWeightDayEntity.setPoundType("Sales");
            prodWeightDayRepo.save(salesWeightDayEntity);
        }
    }

    //
    private List<ProdWeightDayEntity> getDayWeightList(String todayDate) {
        return prodWeightDayRepo.getDayWeightList(todayDate);
    }

    /**
     * @Method : saveWeightDetails
     * @Description :
     * @Params : [resultJa, todayDate]
     * @Return : void
     * @Author : ZhuoNing
     * @Date : 2022/7/2
     * @Time : 4:03
     */
    private void saveWeightDetails(JSONArray resultJa, String todayDate) throws ParseException {
        // 删除每天历史记录
        List<ProdWeightDetailsEntity> existEntityList = getTodayWeightDetails(todayDate);
        System.out.println("今天历史记录数量=" + existEntityList.size());
        prodWeightDetailsRepo.deleteAll(existEntityList);

        for (int a = 0; a < resultJa.size(); a++) {
            JSONObject dataJo = resultJa.getJSONObject(a);
            ProdWeightDetailsEntity prodWeightDetailsEntity = new ProdWeightDetailsEntity();
            prodWeightDetailsEntity.setSerialNumber(dataJo.getString("serialNumber"));
            prodWeightDetailsEntity.setCarNumber(dataJo.getString("carNumber"));
            prodWeightDetailsEntity.setPoundType(dataJo.getString("poundType"));
            prodWeightDetailsEntity.setConsigner(dataJo.getString("consigner"));
            prodWeightDetailsEntity.setConsignee(dataJo.getString("consignee"));
            prodWeightDetailsEntity.setVariety(dataJo.getString("variety"));
            prodWeightDetailsEntity.setSpecification(dataJo.getString("specification"));
            prodWeightDetailsEntity.setGrossWeight(dataJo.getBigDecimal("grossWeight"));
            prodWeightDetailsEntity.setTareWeight(dataJo.getBigDecimal("tareWeight"));
            prodWeightDetailsEntity.setNetWeight(dataJo.getBigDecimal("netWeight"));
            prodWeightDetailsEntity.setDeductionWeight(dataJo.getBigDecimal("deductionWeight"));
            prodWeightDetailsEntity.setActualWeight(dataJo.getBigDecimal("actualWeight"));
            prodWeightDetailsEntity.setPrice(dataJo.getBigDecimal("price"));
            prodWeightDetailsEntity.setMoney(dataJo.getBigDecimal("money"));
            prodWeightDetailsEntity.setWeighingTime(new java.sql.Date(new DateUtil().parseDateTime(dataJo.getString("weighingTime")).getTime()));
            prodWeightDetailsEntity.setWeighingType(dataJo.getString("weighingType"));
            prodWeightDetailsEntity.setAddDate(new Timestamp(new Date().getTime()));
            prodWeightDetailsEntity.setUnit1(dataJo.getString("unit1"));
            prodWeightDetailsRepo.save(prodWeightDetailsEntity);
        }
    }

    // 读取当天
    private List<ProdWeightDetailsEntity> getTodayWeightDetails(String todayDate) {
        List<ProdWeightDetailsEntity> list = prodWeightDetailsRepo.getWeightDetails(todayDate);
        return list;
    }

    private String todayUrl() throws ParseException {
        return weightHttp + weightPath + "?date=" + new DateUtil().getTodayDateText();
    }

    public String initUrl() {
        return weightHttp + weightPath;
    }

    /**
     * @Method : getDayWeight
     * @Description :
     * @Params : [farmId, startDate, endDate]
     * @Return : com.huimv.common.utils.Result
     * @Author : ZhuoNing
     * @Date : 2021/12/7
     * @Time : 13:58
     */
    @Override
    public Result getDayWeight(Integer farmId, String startDate, String endDate) {
        //
        List<ProdDayWeightEntity> dayWeightEntityList = dayWeightRepo.findByFarmIdAndStartAndEndDate(farmId, startDate, endDate);
        if (dayWeightEntityList.size() > 0) {
            BigDecimal totalBd = new BigDecimal(0);
            for (int a = 0; a < dayWeightEntityList.size(); a++) {
                ProdDayWeightEntity dayWeightEntity = dayWeightEntityList.get(a);
                totalBd = new BigDecimal(dayWeightEntity.getNetWeight()).add(totalBd);
            }
            JSONObject outJo = new JSONObject();
            outJo.put("total", totalBd.toString());
            outJo.put("weight", dayWeightEntityList);
            return new Result(ResultCode.SUCCESS, outJo);
        } else {
            return new Result(10001, "暂无数据.", false);
        }
    }

    /**
     * @Method : getDayWeightLastNtimes
     * @Description :
     * @Params : [farmId, days]
     * @Return : com.huimv.common.utils.Result
     * @Author : ZhuoNing
     * @Date : 2021/12/7
     * @Time : 13:58
     */
    @Override
    public Result getDayWeightLastNtimes(Integer farmId, Integer days) {
        //
        List<ProdDayWeightEntity> dayWeightEntityList = dayWeightRepo.findByFarmIdAndDays(farmId, days);
        if (dayWeightEntityList.size() > 0) {
            //排序
            List outList = new ArrayList();
            for (int a = dayWeightEntityList.size() - 1; a >= 0; a--) {
                outList.add(dayWeightEntityList.get(a));
            }
            //计算总重
            BigDecimal totalBd = new BigDecimal(0);
            for (int a = 0; a < dayWeightEntityList.size(); a++) {
                ProdDayWeightEntity dayWeightEntity = dayWeightEntityList.get(a);
                totalBd = new BigDecimal(dayWeightEntity.getNetWeight()).add(totalBd);
            }
            JSONObject outJo = new JSONObject();
            outJo.put("total", totalBd.toString());
            outJo.put("weight", outList);
            return new Result(ResultCode.SUCCESS, outJo);
        } else {
            return new Result(10001, "暂无数据.", false);
        }
    }

    /**
     * @Method : getWeightOnPage
     * @Description : 分页查询称重记录
     * @Params : [farmId, startDate, endDate, pageNo, pageSize]
     * @Return : com.huimv.common.utils.Result
     * @Author : ZhuoNing
     * @Date : 2021/12/7
     * @Time : 14:56
     */
    @Override
    public Result getWeightOnPage(Integer farmId, Date startDate, Date endDate, Integer pageNo, Integer pageSize) {
        Specification<ProdDayWeightEntity> sf = (Specification<ProdDayWeightEntity>) (root, criteriaQuery, criteriaBuilder) -> {
            //
            List<Predicate> predList = new ArrayList<>();
            if (null != farmId) {
                predList.add(criteriaBuilder.equal(root.get("farmId").as(Integer.class), farmId));
            }
            if (null != startDate) {
                predList.add(criteriaBuilder.greaterThanOrEqualTo(root.get("addTime").as(Date.class), startDate));
            }
            if (null != endDate) {
                predList.add(criteriaBuilder.lessThanOrEqualTo(root.get("addTime").as(Date.class), endDate));
            }
            //
            Predicate[] pred = new Predicate[predList.size()];
            Predicate and = criteriaBuilder.and(predList.toArray(pred));
            criteriaQuery.where(and);
            //
            List<Order> orders = new ArrayList<>();
            orders.add(criteriaBuilder.desc(root.get("id")));
            return criteriaQuery.orderBy(orders).getRestriction();
        };
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize);
//        return new Result(ResultCode.SUCCESS,applyRepo.listApply(pageable,applyId));
        return new Result(ResultCode.SUCCESS, dayWeightRepo.findAll(sf, pageable));
    }

    /**
     * @Method : getBatchWeightOnPage
     * @Description : 分页查询批次重量记录
     * @Params : [farmId, addTime, pageNo, pageSize]
     * @Return : com.huimv.common.utils.Result
     * @Author : ZhuoNing
     * @Date : 2021/12/7
     * @Time : 20:31
     */
    @Override
    public Result getBatchWeightOnPage(Integer farmId, Date addTime, Integer pageNo, Integer pageSize) {
        Specification<ProdBatchWeightEntity> sf = (Specification<ProdBatchWeightEntity>) (root, criteriaQuery, criteriaBuilder) -> {
            //
            List<Predicate> predList = new ArrayList<>();
            if (null != farmId) {
                predList.add(criteriaBuilder.equal(root.get("farmId").as(Integer.class), farmId));
            }
            if (null != addTime) {
                predList.add(criteriaBuilder.greaterThanOrEqualTo(root.get("addTime").as(Date.class), addTime));
            }
            //
            Predicate[] pred = new Predicate[predList.size()];
            Predicate and = criteriaBuilder.and(predList.toArray(pred));
            criteriaQuery.where(and);
            //
            List<Order> orders = new ArrayList<>();
            orders.add(criteriaBuilder.desc(root.get("id")));
            return criteriaQuery.orderBy(orders).getRestriction();
        };
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize);
        return new Result(ResultCode.SUCCESS, batchWeightRepo.findAll(sf, pageable));
    }

    /**
     * @Method : getBatchWeightOnPage
     * @Description :
     * @Params : [farmId, startDate, endDate, pageNo, pageSize]
     * @Return : com.huimv.common.utils.Result
     * @Author : ZhuoNing
     * @Date : 2021/12/7
     * @Time : 20:36
     */
    @Override
    public Result getBatchWeightOnPage(Integer farmId, Date startDate, Date endDate, Integer pageNo, Integer pageSize) throws ParseException {
        System.out.println("startDate 2>>" + startDate + " " + dateUtil.formatDateText(startDate));
        System.out.println("endDate 2>>" + endDate + " " + dateUtil.formatDateText(endDate));
        Specification<ProdBatchWeightEntity> sf = (Specification<ProdBatchWeightEntity>) (root, criteriaQuery, criteriaBuilder) -> {
            //
            List<Predicate> predList = new ArrayList<>();
            if (null != farmId) {
                predList.add(criteriaBuilder.equal(root.get("farmId").as(Integer.class), farmId));
            }
            if (null != startDate) {
                predList.add(criteriaBuilder.greaterThanOrEqualTo(root.get("addTime").as(Date.class), startDate));
            }
            if (null != endDate) {
                predList.add(criteriaBuilder.lessThanOrEqualTo(root.get("addTime").as(Date.class), endDate));
            }
//            //
            Predicate[] pred = new Predicate[predList.size()];
            Predicate and = criteriaBuilder.and(predList.toArray(pred));
            criteriaQuery.where(and);
            //
            List<Order> orders = new ArrayList<>();
            orders.add(criteriaBuilder.desc(root.get("id")));
            return criteriaQuery.orderBy(orders).getRestriction();
        };
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize);
        return new Result(ResultCode.SUCCESS, batchWeightRepo.findAll(sf, pageable));
    }

    /**
     * @Method : getBatchWeightOnPage2
     * @Description :
     * @Params : [farmId, startDate, endDate, pageNo, pageSize]
     * @Return : com.huimv.common.utils.Result
     * @Author : ZhuoNing
     * @Date : 2021/12/8
     * @Time : 10:43
     */
    @Override
    public Result getBatchWeightOnPage2(Integer farmId, Date startDate, Date endDate, Integer pageNo, Integer pageSize) throws ParseException {
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, Sort.Direction.DESC, "id");
        //
        return new Result(ResultCode.SUCCESS, batchWeightRepo.findByFarmIdAndStartDateAndEndDate(farmId, startDate, endDate, pageable));
    }

    /**
     * @Method : getEveryTimeWeightOnPage
     * @Description :
     * @Params : [farmId, startDate, endDate, pageNo, pageSize]
     * @Return : com.huimv.common.utils.Result
     * @Author : ZhuoNing
     * @Date : 2021/12/22
     * @Time : 19:41
     */
    @Override
    public Result getEveryTimeWeightOnPage(Integer farmId, Date startDate, Date endDate, Integer pageNo, Integer pageSize) throws ParseException {
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, Sort.Direction.DESC, "id");
        //
        return new Result(ResultCode.SUCCESS, weightRepo.findWeightByFarmIdAndStartDateAndEndDate(farmId, startDate, endDate, pageable));
    }

    @PersistenceContext
    EntityManager entityManager;

    @Override
    public Result getBatchWeightOnPage3(Integer farmId, Date startDate, Date endDate, Integer pageNo, Integer pageSize) {
        StringBuilder countSelectSql = new StringBuilder();
        countSelectSql.append("select count(*) from ProdBatchWeightEntity bw where 1=1 ");

        StringBuilder selectSql = new StringBuilder();
        selectSql.append("from ProdBatchWeightEntity bw where 1=1 ");

        Map<String, Object> params = new HashMap<>();
        StringBuilder whereSql = new StringBuilder();
        //farmId
        if (farmId != null) {
            whereSql.append(" and farmId=:farmId ");
            params.put("farmId", farmId);
        }
        //startDate
        if (startDate != null) {
            whereSql.append(" and addTime>=:startDate ");
            params.put("startDate", startDate);
        }
        //endDate
        if (endDate != null) {
            whereSql.append(" and addTime<=:endDate ");
            params.put("endDate", endDate);
        }
        //加入排序顺序
        whereSql.append(" ORDER BY id DESC");
        String countSql = new StringBuilder().append(countSelectSql).append(whereSql).toString();
        Query countQuery = this.entityManager.createQuery(countSql, Long.class);
        this.setParameters(countQuery, params);
        Long count = (Long) countQuery.getSingleResult();

        String querySql = new StringBuilder().append(selectSql).append(whereSql).toString();
        Query query = this.entityManager.createQuery(querySql, ProdBatchWeightEntity.class);
        this.setParameters(query, params);
        query.setFirstResult((pageNo - 1) * pageSize);
        query.setMaxResults(pageSize);
        List<ProdBatchWeightEntity> batchWeightList = query.getResultList();

//        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize);
        Page<ProdBatchWeightEntity> incomeDailyPage = new PageImpl<ProdBatchWeightEntity>(batchWeightList, pageable, count);

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

    private void setParameters(Query query, Map<String, Object> params) {
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            query.setParameter(entry.getKey(), entry.getValue());
        }
    }

    @Override
    public Result getBatchWeightOnPage4(Integer farmId, String startDate, String endDate, Integer pageNo, Integer pageSize) {
        StringBuilder countSelectSql = new StringBuilder();
        countSelectSql.append("select count(*) from prod_batch_weight bw where 1=1 ");

        StringBuilder selectSql = new StringBuilder();
        selectSql.append("from prod_batch_weight bw where 1=1 ");

        Map<String, Object> params = new HashMap<>();
        StringBuilder whereSql = new StringBuilder();
        //farmId
        if (farmId != null) {
            whereSql.append(" AND farm_id= :farmId");
            params.put("farmId", farmId);
        }
        //startDate
        if (startDate != null) {
            whereSql.append(" AND date_format(add_time,'%Y-%m-%d')>= :startDate ");
            params.put("startDate", startDate);
        }
        //endDate
        if (endDate != null) {
            whereSql.append(" AND date_format(add_time,'%Y-%m-%d')<= :endDate");
            params.put("endDate", endDate);
        }
        //加入排序顺序
        whereSql.append(" ORDER BY id DESC");
        String countSql = new StringBuilder().append(countSelectSql).append(whereSql).toString();
        Query countQuery = this.entityManager.createNativeQuery(countSql);
        this.setParameters(countQuery, params);
//        Long count = (Long) countQuery.getSingleResult();
        int size = countQuery.getResultList().size();
//        System.out.println("count>>"+count);
        System.out.println("size>>" + size);

        String querySql = new StringBuilder().append(selectSql).append(whereSql).toString();
        Query query = this.entityManager.createNativeQuery(querySql);
        this.setParameters(query, params);
        query.setFirstResult((pageNo - 1) * pageSize);
        query.setMaxResults(pageSize);
        List<ProdBatchWeightEntity> batchWeightList = query.getResultList();
//        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, Sort.Direction.DESC, "id");
//        Pageable pageable = PageRequest.of(pageNo - 1, pageSize);
//        Page<ProdBatchWeightEntity> incomeDailyPage = new PageImpl<ProdBatchWeightEntity>(batchWeightList, pageable);

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

    /**
     * @Method : getManyDayWeight
     * @Description :
     * @Params : [days, poundType]
     * @Return : com.huimv.common.utils.Result
     * @Author : ZhuoNing
     * @Date : 2022/7/2
     * @Time : 5:57
     */
    @Override
    public Result getManyDayWeight(Integer days, String poundType) {
        if (StringUtils.isBlank(poundType)) {
            poundType = "Sales";
        }
        //
        List<ProdWeightDayEntity> dayWeightList = prodWeightDayRepo.findDayWeight(days, poundType);
        List newList = new ArrayList();
        for (int a = dayWeightList.size() - 1; a >= 0; a--) {
            newList.add(dayWeightList.get(a));
        }
        return new Result(ResultCode.SUCCESS, newList);
    }

    /**
     * @Method : getWeightDetails
     * @Description :
     * @Params : [poundType, carNumber, consigner, consignee, variety, startDate, endDate, pageNo, pageSize]
     * @Return : com.huimv.common.utils.Result
     * @Author : ZhuoNing
     * @Date : 2022/7/2
     * @Time : 6:03
     */
    @Override
    public Result getWeightDetails(String poundType, String carNumber, String consigner, String consignee, String variety, Date startDate, Date endDate, Integer pageNo, Integer pageSize) {
//        .
        Specification<ProdWeightDetailsEntity> sf = (Specification<ProdWeightDetailsEntity>) (root, criteriaQuery, criteriaBuilder) -> {
            //
            List<Predicate> predList = new ArrayList<>();
            if (null != poundType) {
                predList.add(criteriaBuilder.equal(root.get("poundType").as(String.class), poundType));
            }
            if (null != carNumber) {
//                predList.add(criteriaBuilder.equal(root.get("carNumber").as(String.class), carNumber));
                predList.add(criteriaBuilder.like(root.get("carNumber").as(String.class), "%"+carNumber+"%"));
            }
            if (null != consigner) {
                predList.add(criteriaBuilder.like(root.get("consigner").as(String.class), "%"+consigner+"%"));
            }
            if (null != consignee) {
                predList.add(criteriaBuilder.like(root.get("consignee").as(String.class), "%"+consignee+"%"));
            }
            if (null != variety) {
                predList.add(criteriaBuilder.like(root.get("variety").as(String.class), "%"+variety+"%"));
            }
            if (null != startDate) {
                predList.add(criteriaBuilder.greaterThanOrEqualTo(root.get("weighingTime").as(Date.class), startDate));
            }
            if (null != endDate) {
                predList.add(criteriaBuilder.lessThanOrEqualTo(root.get("weighingTime").as(Date.class), endDate));
            }
            //
            Predicate[] pred = new Predicate[predList.size()];
            Predicate and = criteriaBuilder.and(predList.toArray(pred));
            criteriaQuery.where(and);
            //
            List<Order> orders = new ArrayList<>();
            orders.add(criteriaBuilder.desc(root.get("id")));
            return criteriaQuery.orderBy(orders).getRestriction();
        };
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize);
        return new Result(ResultCode.SUCCESS, prodWeightDetailsRepo.findAll(sf, pageable));
    }
}
