package com.yh.saas.plugin.yiliangyiyun.controller;


import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.winsea.svc.base.base.util.DateUtils;
import com.winsea.svc.base.security.util.AuthSecurityUtils;
import com.yh.saas.plugin.yiliangyiyun.entity.*;
import com.yh.saas.plugin.yiliangyiyun.entity.view.BiViewInfo;
import com.yh.saas.plugin.yiliangyiyun.mapper.ContractManagementInfoMapper;
import com.yh.saas.plugin.yiliangyiyun.mapper.WarehouseInOutInfoMapper;
import com.yh.saas.plugin.yiliangyiyun.mapper.WarehousePositionStorageInfoMapper;
import com.yh.saas.plugin.yiliangyiyun.service.*;
import com.yh.saas.plugin.yiliangyiyun.util.Const;
import com.yh.saas.plugin.yiliangyiyun.util.StringSizeUtil;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 导入 前端控制器
 * </p>
 *
 * @author Gongdc
 * @since 2021-08-30
 */
@RestController
@RequestMapping("/biInfoController")
public class BiInfoController {

    @Autowired
    private IContractManagementInfoService contractManagementInfoService;
    @Autowired
    private WarehouseInOutInfoMapper warehouseInOutInfoMapper;
    @Autowired
    private IWarehousePositionStorageInfoService warehousePositionStorageInfoService;
    @Autowired
    private IWarehouseInOutInfoService warehouseInOutInfoService;
    @Autowired
    private ITranTaskInfoService tranTaskInfoService;
    @Autowired
    private ITranCarInfoService tranCarInfoService;
    @Autowired
    private IContractProcessInfoService contractProcessInfoService;
    @Autowired
    private ICostManagementInfoService costManagementInfoService;
    @Autowired
    private IWarehousePositionInfoService warehousePositionInfoService;
    @Autowired
    private IWarehouseBaseInfoService warehouseBaseInfoService;
    @Autowired
    private WarehousePositionStorageInfoMapper warehousePositionStorageInfoMapper;
    @Autowired
    private IStockSaleReceiptReportService stockSaleReceiptReportService;
    @Autowired
    private IStockPurchaseReceiptReportService stockPurchaseReceiptReportService;
    private String companyId;
    @Autowired
    private CacheComponent cacheComponent;

    //清理所有Redis缓存
    @GetMapping("/clearCache")
    public void clearCache() {
        cacheComponent.delPrefixKey(Const.SELF_WAREHOUSE);
        cacheComponent.delPrefixKey(Const.ADMIN_WEIGHINGINFO);
        cacheComponent.delPrefixKey(Const.ADMIN_WEIGHINGINFO_NUM);
        cacheComponent.delPrefixKey(Const.ADMIN_CONTRACTINFO);
        cacheComponent.delPrefixKey(Const.ADMIN_BI_INFO);
    }

    /**
     * 查询
     *
     * @return
     */
    @GetMapping("/selectBiInfo")
    public List<BiViewInfo> selectBiInfo(String compId, String seachMoth) {
        List<BiViewInfo> listRedis = cacheComponent.getObjList(Const.ADMIN_BI_INFO, BiViewInfo.class);
        if (listRedis != null && listRedis.size() > 0) {
            return listRedis;
        }
        companyId = compId;
        List<BiViewInfo> biViewInfos = new ArrayList<>();
        // 销售合同   执行中的合同
        EntityWrapper<ContractManagementInfo> contractManagementInfoEntityWrapper = new EntityWrapper<ContractManagementInfo>();
        contractManagementInfoEntityWrapper.eq("status_flag", "1");
        contractManagementInfoEntityWrapper.eq("comp_id", compId);
        if (seachMoth != null) {
            if (!seachMoth.contains("-")) {
                contractManagementInfoEntityWrapper.and("YEAR(create_date)='" + seachMoth + "'");
            } else {
                contractManagementInfoEntityWrapper.like("create_date", seachMoth + "%");
            }
        }

        List<ContractManagementInfo> contractManagementInfos = contractManagementInfoService.selectList(contractManagementInfoEntityWrapper);
        // 执行中的所有合同-已完成量、待完成量   2  执行中的合同额  -已开票、待开票 3 已付款 未付款
        getCompletedAndNotQuantity(contractManagementInfos, biViewInfos);
        // 采购
        getBuyInfo(contractManagementInfos, biViewInfos);
        // 车辆
        getTranCount(biViewInfos, seachMoth);
        // 库存成本
        getCostCount(biViewInfos, seachMoth);
        // 库点流向
        getMapInfo(biViewInfos, seachMoth);
        // 收入支出毛利润
        getMoney(biViewInfos, seachMoth);

        cacheComponent.putRaw(Const.ADMIN_BI_INFO, JSONObject.toJSONString(biViewInfos), 60 * 60);
        return biViewInfos;
    }

    /**
     * 查询
     *
     * @return
     */
    @GetMapping("/selectBiInfoNew")
    public List<BiViewInfo> selectBiInfoNew(String compId, String seachMoth) {
        List<BiViewInfo> listRedis = cacheComponent.getObjList(Const.ADMIN_BI_INFO, BiViewInfo.class);
        if (listRedis != null && listRedis.size() > 0) {
            return listRedis;
        }
        companyId = compId;
        List<BiViewInfo> biViewInfos = new ArrayList<>();
        // 车辆
        getTranCount(biViewInfos, seachMoth);
        // 库存成本
        getCostCount(biViewInfos, seachMoth);
        // 库点流向
        getMapInfo(biViewInfos, seachMoth);
        // 出入库分布
        getInOutInfo(biViewInfos);
        // 合营比例
        getHeYing(biViewInfos);
        // 库存
        getWarehouseStorge(biViewInfos);
        // 合同
        getcontract(biViewInfos);
        // 在途
        getTranProess(biViewInfos);

        cacheComponent.putRaw(Const.ADMIN_BI_INFO, JSONObject.toJSONString(biViewInfos), 60 * 20);
        return biViewInfos;
    }


    /**
     * 合同
     *
     * @return
     */
    private List<BiViewInfo> getcontract(List<BiViewInfo> biViewInfos) {
        List<ContractManagementInfo> contractManagementInfoList = new ArrayList<>();
        BiViewInfo biViewInfoa = new BiViewInfo();
        List<ContractManagementInfo> contractManagementInfos = contractManagementInfoService.selectList(new EntityWrapper<ContractManagementInfo>()
                .eq("delete_flag", "0").eq("comp_id", companyId).orderBy("create_date", false));
        if (CollectionUtils.isNotEmpty(contractManagementInfos)) {
            for (int i = 0; i < 10; i++) {
                if (contractManagementInfos.size() < i) {
                    break;
                }
                contractManagementInfoList.add(contractManagementInfos.get(i));
            }

        }
        biViewInfoa.setBiType("合同");
        biViewInfoa.setContractManagementInfos(contractManagementInfoList);
        biViewInfos.add(biViewInfoa);
        return biViewInfos;
    }


    /**
     * 库存
     *
     * @return
     */
    private List<BiViewInfo> getWarehouseStorge(List<BiViewInfo> biViewInfos) {
        List<BiViewInfo> biViewInfoList = new ArrayList<>();
        BiViewInfo biViewInfoa = new BiViewInfo();

        // 查询库存
        List<WarehouseBaseInfo> warehouseBaseInfoList = warehouseBaseInfoService.selectList(new EntityWrapper<WarehouseBaseInfo>()
                .eq("delete_flag", "0").eq("comp_id", companyId).eq("warehouse_type", "1"));
        if (CollectionUtils.isNotEmpty(warehouseBaseInfoList)) {
            for (int i = 0; i < warehouseBaseInfoList.size(); i++) {
                BiViewInfo biViewInfo = new BiViewInfo();
                WarehouseBaseInfo warehouseBaseInfo = warehouseBaseInfoList.get(i);
                Double sum = warehousePositionStorageInfoMapper.selectSumWare(companyId, warehouseBaseInfo.getId());
                biViewInfo.setName(warehouseBaseInfo.getWarehouseName());
                biViewInfo.setWeight(sum);
                if(sum != null){
                    biViewInfoList.add(biViewInfo);
                }

            }

        }
        List<BiViewInfo> listSort = biViewInfoList.stream().sorted(Comparator.comparing(BiViewInfo::getWeight).reversed().thenComparing(BiViewInfo::getWeight)).collect(Collectors.toList());
        biViewInfoa.setBiType("库存");
        biViewInfoa.setBiViewInfoList(listSort.subList(0,10));
        biViewInfos.add(biViewInfoa);

        return biViewInfos;
    }

    /**
     * 合营比例
     *
     * @return
     */
    private List<BiViewInfo> getHeYing(List<BiViewInfo> biViewInfos) {
        List<BiViewInfo> biViewInfoList = new ArrayList<>();
        BiViewInfo biViewInfoa = new BiViewInfo();
        BiViewInfo biViewInfob = new BiViewInfo();
        BiViewInfo biViewInfoc = new BiViewInfo();
        Integer countWare = warehouseBaseInfoService.selectCount(new EntityWrapper<WarehouseBaseInfo>()
        .eq("comp_id",companyId).eq("delete_flag", "0").eq("warehouse_type","1"));
        // 查询仓库总数
        Integer count = warehousePositionInfoService.selectCount(new EntityWrapper<WarehousePositionInfo>()
                .eq("delete_flag", "0"));
        // 查询自由库数量
        List<WarehousePositionInfo> warehousePositionInfos = warehousePositionInfoService.selectList(new EntityWrapper<WarehousePositionInfo>()
                .eq("delete_flag", "0").like("bin_number", "合营").groupBy("base_id"));
        Integer count1 = warehousePositionInfos.size();
        biViewInfoa.setCount(String.valueOf(count1));
        biViewInfoa.setName("合营");
        biViewInfoa.setPercentage(String.valueOf(count1 / countWare * 100) + "%");
        biViewInfob.setCount(String.valueOf(countWare - count1));
        biViewInfob.setName("自有");
        biViewInfob.setPercentage(String.valueOf((countWare - count1) / countWare * 100) + "%");
        biViewInfoList.add(biViewInfoa);
        biViewInfoList.add(biViewInfob);
        biViewInfoc.setBiType("合营");
        biViewInfoc.setBiViewInfoList(biViewInfoList);
        biViewInfos.add(biViewInfoc);
        return biViewInfos;
    }

    /**
     * 库点流向
     *
     * @return
     */
    private List<BiViewInfo> getMapInfo(List<BiViewInfo> biViewInfos, String seachMoth) {
        List<BiViewInfo> biViewInfoList = new ArrayList<>();
        BiViewInfo biViewInfoa = new BiViewInfo();
        List<TranTaskInfo> tranTaskInfos = tranTaskInfoService.selectList(new EntityWrapper<TranTaskInfo>()
                .eq("comp_id", companyId));
        if (CollectionUtils.isNotEmpty(tranTaskInfos)) {
            for (int i = 0; i < tranTaskInfos.size(); i++) {
                TranTaskInfo tranTaskInfo = tranTaskInfos.get(i);
                if (StringUtils.isNotBlank(tranTaskInfo.getReceiveWarehouse())) {
                    if ("1".equals(tranTaskInfo.getTaskTypeKey())) {

                        BiViewInfo biViewInfo = new BiViewInfo();
                        WarehouseBaseInfo warehouseBaseInfo = warehouseBaseInfoService.selectOne(new EntityWrapper<WarehouseBaseInfo>()
                                .eq("comp_id", companyId)
                                .eq("warehouse_name", tranTaskInfo.getSendWarehouse()));
                        ContractManagementInfo contractManagementInfo = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                                .eq("contract_no", tranTaskInfo.getContractNo())
                                .eq("comp_id", companyId));
                        if (warehouseBaseInfo != null && contractManagementInfo != null) {
                            biViewInfo.setStartPlace(warehouseBaseInfo.getWarehousePositioning());
                            biViewInfo.setEndPlace(contractManagementInfo.getDeliveryLocation());
                            biViewInfo.setName(warehouseBaseInfo.getWarehouseName() + " → " + contractManagementInfo.getPlaceDelivery() + " ");
                            biViewInfoList.add(biViewInfo);
                        }

                    } else if ("4".equals(tranTaskInfo.getTaskTypeKey())) {
                        BiViewInfo biViewInfo = new BiViewInfo();
                        WarehouseBaseInfo warehouseBaseInfo = warehouseBaseInfoService.selectOne(new EntityWrapper<WarehouseBaseInfo>()
                                .eq("comp_id", companyId)
                                .eq("warehouse_name", tranTaskInfo.getSendWarehouse()));
                        WarehouseBaseInfo warehouseBaseInfo1 = warehouseBaseInfoService.selectOne(new EntityWrapper<WarehouseBaseInfo>()
                                .eq("comp_id", companyId)
                                .eq("warehouse_name", tranTaskInfo.getReceiveWarehouse()));
                        if (warehouseBaseInfo != null && warehouseBaseInfo1 != null) {
                            biViewInfo.setStartPlace(warehouseBaseInfo.getWarehousePositioning());
                            biViewInfo.setEndPlace(warehouseBaseInfo1.getWarehousePositioning());
                            biViewInfo.setName(warehouseBaseInfo.getWarehouseName() + " → " + warehouseBaseInfo1.getWarehouseName() + " ");
                            biViewInfoList.add(biViewInfo);
                        }
                    }

                }
            }
        }

        biViewInfoa.setBiType("10-库点流向分布");
        biViewInfoa.setBiViewInfoList(biViewInfoList);
        biViewInfos.add(biViewInfoa);

        return biViewInfos;
    }

    /**
     * 获取收入、支出、毛利润
     *
     * @return
     */
    private List<BiViewInfo> getMoney(List<BiViewInfo> biViewInfos, String seachMoth) {

        return stockSaleReceiptReportService.getMoney(biViewInfos, seachMoth);
    }

    /**
     * 车辆  粮食储存总量
     *
     * @return
     */
    private List<BiViewInfo> getCostCount(List<BiViewInfo> biViewInfos, String seachMoth) {
        EntityWrapper<CostManagementInfo> costManagementInfoEntityWrapper = new EntityWrapper<CostManagementInfo>();
        costManagementInfoEntityWrapper.eq("comp_id", companyId);
//        if(seachMoth != null) {
//            if (!seachMoth.contains("-")) {
//                costManagementInfoEntityWrapper.and("YEAR(create_date)='" + seachMoth + "'");
//            } else {
//                costManagementInfoEntityWrapper.and("(YEAR(create_date)+\"-\"+MONTH(create_date))='" + seachMoth + "'");
//
//            }
//        }
//        List<CostManagementInfo> costManagementInfos = costManagementInfoService.selectList(costManagementInfoEntityWrapper);
        Double sumAct = warehousePositionStorageInfoService.selectSumStoreage(companyId);
        Double sumBuy = contractManagementInfoService.selectSumBuy(companyId);
        Double sumSale = contractManagementInfoService.selectSumSale(companyId);
//        if (CollectionUtils.isNotEmpty(costManagementInfos)) {
//            for (int i = 0; i < costManagementInfos.size(); i++) {
//                CostManagementInfo costManagementInfo = costManagementInfos.get(i);
//                sumTotal = sumTotal + costManagementInfo.getStorage();
//                sumCost = sumCost + (costManagementInfo.getStorage() * costManagementInfo.getCost());
//            }
//        }
        if (sumAct == null) {
            sumAct = 0d;
        }
        if (sumBuy == null) {
            sumBuy = 0d;
        }
        if (sumSale == null) {
            sumSale = 0d;
        }
        List<BiViewInfo> biViewInfoList = new ArrayList<>();
        BiViewInfo biViewInfo = new BiViewInfo();
        BiViewInfo biViewInfo1 = new BiViewInfo();
        BiViewInfo biViewInfo2 = new BiViewInfo();
        BiViewInfo biViewInfo0 = new BiViewInfo();
        biViewInfo.setBiType("8-库存成本");
        biViewInfo1.setName("实际库存");
        BigDecimal bg = new BigDecimal(sumAct);
        biViewInfo1.setCount(String.valueOf(bg));
        biViewInfo2.setName("采购待执行");
        bg = new BigDecimal(sumBuy);
        biViewInfo2.setCount(String.valueOf(bg));
        biViewInfo0.setName("销售待执行");
        bg = new BigDecimal(sumSale);
        biViewInfo0.setCount(String.valueOf(bg));
        biViewInfoList.add(biViewInfo1);
        biViewInfoList.add(biViewInfo2);
        biViewInfoList.add(biViewInfo0);
        biViewInfo.setBiViewInfoList(biViewInfoList);
        biViewInfos.add(biViewInfo);

        // 粮食储存总量
        EntityWrapper<CostManagementInfo> costManagementInfoEntityWrapper1 = new EntityWrapper<CostManagementInfo>();
        costManagementInfoEntityWrapper1.eq("comp_id", companyId);
        costManagementInfoEntityWrapper1.groupBy("goods_name_key");
//        if(seachMoth != null) {
//            if (!seachMoth.contains("-")) {
//                costManagementInfoEntityWrapper1.and("YEAR(create_date)='" + seachMoth + "'");
//            } else {
//                costManagementInfoEntityWrapper1.and("(YEAR(create_date)+\"-\"+MONTH(create_date))='" + seachMoth + "'");
//
//            }
//        }
        List<CostManagementInfo> costManagementInfoList = costManagementInfoService.selectList(costManagementInfoEntityWrapper1);
        BiViewInfo biViewInfo4 = new BiViewInfo();
        List<BiViewInfo> biViewInfos1 = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(costManagementInfoList)) {
            for (int i = 0; i < costManagementInfoList.size(); i++) {
                CostManagementInfo costManagementInfo = costManagementInfoList.get(i);
                BiViewInfo biViewInfo3 = new BiViewInfo();
                EntityWrapper<CostManagementInfo> costManagementInfoEntityWrapper2 = new EntityWrapper<CostManagementInfo>();
                costManagementInfoEntityWrapper2.eq("comp_id", companyId);
                costManagementInfoEntityWrapper2.eq("goods_name_key", costManagementInfo.getGoodsNameKey());
//                if(seachMoth != null) {
//                    if (!seachMoth.contains("-")) {
//                        costManagementInfoEntityWrapper1.and("YEAR(create_date)='" + seachMoth + "'");
//                    } else {
//                        costManagementInfoEntityWrapper1.and("(YEAR(create_date)+\"-\"+MONTH(create_date))='" + seachMoth + "'");
//
//                    }
//                }
                List<CostManagementInfo> costManagementInfoList1 = costManagementInfoService.selectList(costManagementInfoEntityWrapper2);
                Double weight = 0d;
                for (int j = 0; j < costManagementInfoList1.size(); j++) {
                    CostManagementInfo costManagementInfo1 = costManagementInfoList1.get(j);
                    weight = weight + costManagementInfo1.getStorage();
                }
                biViewInfo3.setName(costManagementInfo.getGoodsName());
                biViewInfo3.setCount(String.valueOf(weight));
                biViewInfos1.add(biViewInfo3);
            }
            biViewInfo4.setBiType("9-粮食总储存量");
            biViewInfo4.setBiViewInfoList(biViewInfos1);
            biViewInfos.add(biViewInfo4);
        }
        return biViewInfos;
    }


    /**
     * 在途
     *
     * @return
     */
    private List<BiViewInfo> getTranProess(List<BiViewInfo> biViewInfos) {
        List<BiViewInfo> biViewInfoList = new ArrayList<>();
        BiViewInfo biViewInfo = new BiViewInfo();
        // 今日装车
        List<TranCarInfo> tranCarInfos = tranCarInfoService.selectList(new EntityWrapper<TranCarInfo>()
                .eq("status_flag", "3")
                .eq("comp_id", companyId)
        .orderBy("create_date",false));
        List<TranCarInfo> tranCarInfoList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(tranCarInfos)) {
            for (int i = 0; i < tranCarInfos.size(); i++) {

                TranTaskInfo tranTaskInfo = tranTaskInfoService.selectById(tranCarInfos.get(i).getInfoId());
                tranCarInfos.get(i).setTranTaskInfos(tranTaskInfo);
                if(StringUtils.isNotBlank(tranTaskInfo.getStartArea())){

                    tranCarInfoList.add(tranCarInfos.get(i));
                }
                if(tranCarInfoList.size()>30){
                    break;
                }

            }
            biViewInfo.setTranCarInfos(tranCarInfoList);
        }

        biViewInfos.add(biViewInfo);

        return biViewInfos;
    }

    /**
     * 车辆
     *
     * @return
     */
    private List<BiViewInfo> getTranCount(List<BiViewInfo> biViewInfos, String seachMoth) {
        List<BiViewInfo> biViewInfoList = new ArrayList<>();
        // 今日装车
        int inCount = tranCarInfoService.selectCount(new EntityWrapper<TranCarInfo>()
                .eq("status_flag", "3")
                .eq("comp_id", companyId));
        //今日在途
//        int inAfterCount = tranCarInfoService.selectCount(new EntityWrapper<TranCarInfo>()
//                .eq("status_flag", "3")
//                .eq("comp_id", companyId)
//                .lt("update_date", DateUtil.formatDate(new Date(), DateUtils.DATE_FMT_YYYY_MM_DD)));
        int inAfterCount = warehouseInOutInfoService.selectCountCompany(companyId, "出库");
        //今日卸车
        int outCount = warehouseInOutInfoService.selectCountCompany(companyId, "入库");
//        int outCount1 = weighingManagementService.selectCount(new EntityWrapper<WeighingManagement>()
//                .le("status_flag", "3")
//                .eq("delete_flag", "0")
//                .eq("comp_id", companyId));
        BiViewInfo biViewInfo = new BiViewInfo();
        BiViewInfo biViewInfo1 = new BiViewInfo();
        BiViewInfo biViewInfo2 = new BiViewInfo();
        BiViewInfo biViewInfo3 = new BiViewInfo();
        biViewInfo.setBiType("7-车辆信息");
        biViewInfo1.setName("在途车辆");
        biViewInfo1.setCount(String.valueOf(inCount));
        biViewInfo2.setName("装货车辆");
        biViewInfo2.setCount(String.valueOf(inAfterCount));
        biViewInfo3.setName("卸货车辆");
        biViewInfo3.setCount(String.valueOf(outCount));
        biViewInfoList.add(biViewInfo1);
        biViewInfoList.add(biViewInfo2);
        biViewInfoList.add(biViewInfo3);
        biViewInfo.setBiViewInfoList(biViewInfoList);
        biViewInfos.add(biViewInfo);

        return biViewInfos;
    }

    /**
     * 出入库分布
     *
     * @return
     */
    private List<BiViewInfo> getInOutInfo(List<BiViewInfo> biViewInfos) {
        List<BiViewInfo> biViewInfoList = new ArrayList<>();
        BiViewInfo biViewInfo = new BiViewInfo();
        List<BiViewInfo> biViewInfoList1 = new ArrayList<>();
        BiViewInfo biViewInfo1 = new BiViewInfo();
        // 出库
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        for (int i = 1; i <= 12; i++) {
            String start = year + "-" + StringSizeUtil.stringSize(String.valueOf(i)) + "-" + "01" + " 00:00:00";
            String end = year + "-" + StringSizeUtil.stringSize(String.valueOf(i)) + "-" + "31" + " 23:59:59";
            Map<String, Object> pageView = new HashMap<>();
            pageView.put("start", start);
            pageView.put("end", end);
            pageView.put("type", "1");
            List<WarehouseInOutInfo> list = warehouseInOutInfoMapper.brokenLineStatisticalChartByYear(pageView);
            if (list.size() == 0) {
                Double money = 0D;
                BiViewInfo taskYearChartVo = new BiViewInfo();
                taskYearChartVo.setName(i + "月");
                taskYearChartVo.setCount(String.valueOf(money));
                taskYearChartVo.setBiType("出库");
                biViewInfoList.add(taskYearChartVo);
            } else {
                Double money = list.stream().collect(Collectors.summingDouble(WarehouseInOutInfo::getNetWeight));
                BiViewInfo taskYearChartVo = new BiViewInfo();
                taskYearChartVo.setName(i + "月");
                taskYearChartVo.setCount(String.valueOf(money));
                taskYearChartVo.setBiType("出库");
                biViewInfoList.add(taskYearChartVo);

            }
        }
        biViewInfo.setBiType("出库");
        biViewInfo.setBiViewInfoList(biViewInfoList);
        biViewInfos.add(biViewInfo);


        // 入库
        for (int i = 1; i <= 12; i++) {
            String start = year + "-" + StringSizeUtil.stringSize(String.valueOf(i)) + "-" + "01" + " 00:00:00";
            String end = year + "-" + StringSizeUtil.stringSize(String.valueOf(i)) + "-" + "31" + " 23:59:59";
            Map<String, Object> pageView = new HashMap<>();
            pageView.put("start", start);
            pageView.put("end", end);
            pageView.put("type", "2");
            List<WarehouseInOutInfo> list = warehouseInOutInfoMapper.brokenLineStatisticalChartByYear(pageView);
            if (list.size() == 0) {
                Double money = 0D;
                BiViewInfo taskYearChartVo = new BiViewInfo();
                taskYearChartVo.setName(i + "月");
                taskYearChartVo.setCount(String.valueOf(money));
                taskYearChartVo.setBiType("入库");
                biViewInfoList1.add(taskYearChartVo);
            } else {
                Double money = list.stream().collect(Collectors.summingDouble(WarehouseInOutInfo::getNetWeight));
                BiViewInfo taskYearChartVo = new BiViewInfo();
                taskYearChartVo.setName(i + "月");
                taskYearChartVo.setCount(String.valueOf(money));
                taskYearChartVo.setBiType("入库");
                biViewInfoList1.add(taskYearChartVo);

            }
        }
        biViewInfo1.setBiType("入库");
        biViewInfo1.setBiViewInfoList(biViewInfoList1);
        biViewInfos.add(biViewInfo1);

        return biViewInfos;
    }

    /**
     * 采购
     *
     * @return
     */
    private List<BiViewInfo> getBuyInfo(List<ContractManagementInfo> contractManagementInfos, List<BiViewInfo> biViewInfos) {
        // 采购合同总量
        Double sumTotal = 0d;
        // 采购合同完成量
        Double completedQuantity = 0d;
        // 采购合同总金额
        Double moneyTotal = 0.00;
        //采购合同已开发票金额
        Double invoicingTotal = 0.00;
        // 采购合同已回款金额
        Double payTotal = 0.00;
        for (int i = 0; i < contractManagementInfos.size(); i++) {
            ContractManagementInfo contractManagementInfo1 = contractManagementInfos.get(i);
            sumTotal = sumTotal + contractManagementInfo1.getWeight();
//            moneyTotal = moneyTotal + contractManagementInfo1.getTotalContractPrice();

            //现货自运采购合同
            if ("1".equals(contractManagementInfo1.getGoodsType()) && "1".equals(contractManagementInfo1.getDeliverType()) && "2".equals(contractManagementInfo1.getContractType())) {
                //定义出库量
                Double outWeight = 0.0d;
                //查询同名临时库出库量
                List<StockPurchaseReceiptReport> stockPurchaseReceiptReportList = stockPurchaseReceiptReportService.selectList(new EntityWrapper<StockPurchaseReceiptReport>()
                        .eq("warehouse_name", contractManagementInfo1.getContractNo())
                        .ge("status_flag", "1")
                        .eq("delete_flag", "0"));
                if (!CollectionUtils.isEmpty(stockPurchaseReceiptReportList)) {
                    for (StockPurchaseReceiptReport stockPurchaseReceiptReport : stockPurchaseReceiptReportList) {
                        outWeight = outWeight + stockPurchaseReceiptReport.getSettlementWeight();
                        moneyTotal += stockPurchaseReceiptReport.getAmountIngPayable();
                    }
                }
                //定义退库量
                Double returnWeight = 0.0d;
                //查询同名临时库出库量
                List<WarehouseInOutInfo> warehouseInOutInfoList1 = warehouseInOutInfoService.selectList(new EntityWrapper<WarehouseInOutInfo>()
                        .eq("warehouse_name", contractManagementInfo1.getContractNo())
                        .eq("in_out_type", "退库")
                        .eq("status_flag", "3")
                        .eq("delete_flag", "0"));
                if (!CollectionUtils.isEmpty(warehouseInOutInfoList1)) {
                    for (WarehouseInOutInfo warehouseInOutInfo : warehouseInOutInfoList1) {
                        returnWeight = returnWeight + Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight()));
                    }
                }
                sumTotal += outWeight - returnWeight;
            }
            //现货他运采购合同
            else if ("1".equals(contractManagementInfo1.getGoodsType()) && "2".equals(contractManagementInfo1.getDeliverType()) && "2".equals(contractManagementInfo1.getContractType())) {
                //定义出库量
                Double inWeight = 0.0d;
                //查询同合同编号入库量
                List<StockPurchaseReceiptReport> stockPurchaseReceiptReportList = stockPurchaseReceiptReportService.selectList(new EntityWrapper<StockPurchaseReceiptReport>()
                        .eq("contract_no", contractManagementInfo1.getContractNo())
                        .ge("status_flag", "1")
                        .eq("delete_flag", "0"));
                if (!CollectionUtils.isEmpty(stockPurchaseReceiptReportList)) {
                    for (StockPurchaseReceiptReport stockPurchaseReceiptReport : stockPurchaseReceiptReportList) {
                        inWeight = Double.valueOf(inWeight) + stockPurchaseReceiptReport.getSettlementWeight();
                    }
                }

                completedQuantity += inWeight;
            }
            // 查询已开票未开票
            ContractProcessInfo contractProcessInfo = contractProcessInfoService.selectOne(new EntityWrapper<ContractProcessInfo>().eq(ContractGoodsInfo.QueryFiles.CONTRACT_ID, contractManagementInfo1.getId()));
            invoicingTotal = invoicingTotal + (contractProcessInfo.getGoodsName() != null ? contractProcessInfo.getGoodsName() : 0.00);
            payTotal = payTotal + (contractProcessInfo.getMildewGrain() != null ? contractProcessInfo.getMildewGrain() : 0.00);
        }
        // 执行中的所有合同量求和-- 已完成量、待完成量
        BiViewInfo biViewInfo = new BiViewInfo();
        biViewInfo.setBiType("4-采购合同（已完成量、待完成量）");
        BigDecimal bg = new BigDecimal(sumTotal);
        biViewInfo.setTotal(String.valueOf(bg));
        List<BiViewInfo> biViewInfos1 = new ArrayList<>();
        BiViewInfo biViewInfo1 = new BiViewInfo();
        biViewInfo1.setName("已完成量");
        biViewInfo1.setCount(String.valueOf(completedQuantity));
        biViewInfo1.setPercentage(completedQuantity / sumTotal * 100 + "%");
        BiViewInfo biViewInfo2 = new BiViewInfo();
        biViewInfo2.setName("待完成量");
        biViewInfo2.setCount(String.valueOf(sumTotal - completedQuantity));
        biViewInfo2.setPercentage((sumTotal - completedQuantity) / sumTotal * 100 + "%");
        biViewInfos1.add(biViewInfo1);
        biViewInfos1.add(biViewInfo2);
        biViewInfo.setBiViewInfoList(biViewInfos1);
        biViewInfos.add(biViewInfo);

        // 执行中的合同额 -已开票、待开票
        BiViewInfo biViewInfoa = new BiViewInfo();
        biViewInfoa.setBiType("5-采购合同（已开票、待开票）");
        BigDecimal bg1 = new BigDecimal(moneyTotal);
        biViewInfoa.setTotal(String.valueOf(bg1));
        List<BiViewInfo> biViewInfosa1 = new ArrayList<>();
        BiViewInfo biViewInfoa1 = new BiViewInfo();
        biViewInfoa1.setName("已开票");
        BigDecimal bg12 = new BigDecimal(invoicingTotal);
        biViewInfoa1.setCount(String.valueOf(bg12));
        biViewInfoa1.setPercentage(invoicingTotal != 0 ? invoicingTotal / moneyTotal * 100 + "%" : 0 + "%");
        BiViewInfo biViewInfoa2 = new BiViewInfo();
        biViewInfoa2.setName("待开票");
        BigDecimal bg00 = new BigDecimal(moneyTotal - (invoicingTotal != null ? invoicingTotal : 0));
        biViewInfoa2.setCount(String.valueOf(bg00));
        biViewInfoa2.setPercentage((moneyTotal - (invoicingTotal != null ? invoicingTotal : 0)) / moneyTotal * 100 + "%");
        biViewInfosa1.add(biViewInfoa1);
        biViewInfosa1.add(biViewInfoa2);
        biViewInfoa.setBiViewInfoList(biViewInfosa1);
        biViewInfos.add(biViewInfoa);


        // 执行中的合同额 -已付款、待付款
        BiViewInfo biViewInfob = new BiViewInfo();
        biViewInfob.setBiType("6-采购合同（已回款、待回款）");
        biViewInfob.setTotal(String.valueOf(bg1));
        List<BiViewInfo> biViewInfosb1 = new ArrayList<>();
        BiViewInfo biViewInfob1 = new BiViewInfo();
        biViewInfob1.setName("已付款");
        BigDecimal bg45 = new BigDecimal(payTotal);
        biViewInfob1.setCount(String.valueOf(bg45));
        biViewInfob1.setPercentage(payTotal != 0 ? payTotal / moneyTotal * 100 + "%" : 0 + "%");
        BiViewInfo biViewInfob2 = new BiViewInfo();
        biViewInfob2.setName("待付款");
        BigDecimal bg4 = new BigDecimal(moneyTotal - (payTotal != null ? payTotal : 0));
        biViewInfob2.setCount(String.valueOf(bg4));
        biViewInfob2.setPercentage((moneyTotal - (payTotal != null ? payTotal : 0)) / moneyTotal * 100 + "%");
        biViewInfosb1.add(biViewInfob1);
        biViewInfosb1.add(biViewInfob2);
        biViewInfob.setBiViewInfoList(biViewInfosb1);
        biViewInfos.add(biViewInfob);
        return biViewInfos;
    }

    /**
     * 销售
     *
     * @return
     */
    private List<BiViewInfo> getCompletedAndNotQuantity(List<ContractManagementInfo> contractManagementInfos, List<BiViewInfo> biViewInfos) {
        // 销售合同总量
        Double sumTotal = 0d;
        // 销售合同完成量
        Double completedQuantity = 0d;
        // 销售合同总金额
        Double moneyTotal = 0.00;
        // 销售合同已开发票金额
        Double invoicingTotal = 0.00;
        // 销售合同已付款金额
        Double payTotal = 0.00;
        for (int i = 0; i < contractManagementInfos.size(); i++) {
            ContractManagementInfo contractManagementInfo1 = contractManagementInfos.get(i);
            if ("2".equals(contractManagementInfo1.getContractType())) {
                continue;
            }
            sumTotal = sumTotal + contractManagementInfo1.getWeight();
//            moneyTotal = moneyTotal + contractManagementInfo1.getTotalContractPrice();
            //定义出库量
            Double outWeight = 0.0d;
            //定义退库量
            Double returnWeight = 0.0d;

            Double payMoney = 0.0d;
            //查询同合同编号出库量
            List<StockSaleReceiptReport> stockSaleReceiptReportList = stockSaleReceiptReportService.selectList(new EntityWrapper<StockSaleReceiptReport>()
                    .eq("contract_no", contractManagementInfo1.getContractNo())
                    .eq("delete_flag", "0"));
            if (!CollectionUtils.isEmpty(stockSaleReceiptReportList)) {
                for (StockSaleReceiptReport stockSaleReceiptReport : stockSaleReceiptReportList) {
                    outWeight = outWeight + (stockSaleReceiptReport.getSettlementWeight() != null ? stockSaleReceiptReport.getSettlementWeight() : 0);
                    moneyTotal += (stockSaleReceiptReport.getAmountIngReceivable() != null ? stockSaleReceiptReport.getAmountIngReceivable() : 0);
                    payMoney += (stockSaleReceiptReport.getAmountEdReceivable() != null ? stockSaleReceiptReport.getAmountEdReceivable() : 0);
                }
            }
            //查询同合同编号出库量
            List<StockSaleReceiptReport> stockSaleReceiptReportList1 = stockSaleReceiptReportService.selectList(new EntityWrapper<StockSaleReceiptReport>()
                    .eq("contract_no", contractManagementInfo1.getContractNo())
                    .eq("return_flag", "1")
                    .ge("status_flag", "8")
                    .eq("delete_flag", "0"));
            if (!CollectionUtils.isEmpty(stockSaleReceiptReportList1)) {
                for (StockSaleReceiptReport stockSaleReceiptReport : stockSaleReceiptReportList1) {
                    returnWeight = returnWeight + stockSaleReceiptReport.getSettlementWeight();
                    payMoney -= stockSaleReceiptReport.getAmountEdReceivable();
                }
            }
            completedQuantity += outWeight - returnWeight;
            // 查询已开票未开票
            ContractProcessInfo contractProcessInfo = contractProcessInfoService.selectOne(new EntityWrapper<ContractProcessInfo>().eq(ContractGoodsInfo.QueryFiles.CONTRACT_ID, contractManagementInfo1.getId()));
            invoicingTotal = invoicingTotal + (contractProcessInfo.getGoodsName() != null ? contractProcessInfo.getGoodsName() : 0.00);
//            payTotal += payMoney;
            payTotal = payTotal + (contractProcessInfo.getMildewGrain() != null ? contractProcessInfo.getMildewGrain() : 0.00);
        }
        // 执行中的所有合同量求和-- 已完成量、待完成量
        BiViewInfo biViewInfo = new BiViewInfo();
        biViewInfo.setBiType("1-销售合同（已完成量、待完成量）");
        BigDecimal bg = new BigDecimal(sumTotal);
        biViewInfo.setTotal(String.valueOf(bg));
        List<BiViewInfo> biViewInfos1 = new ArrayList<>();
        BiViewInfo biViewInfo1 = new BiViewInfo();
        biViewInfo1.setName("已完成量");
        biViewInfo1.setCount(String.valueOf(completedQuantity));
        biViewInfo1.setPercentage(completedQuantity / sumTotal * 100 + "%");
        BiViewInfo biViewInfo2 = new BiViewInfo();
        biViewInfo2.setName("待完成量");
        biViewInfo2.setCount(String.valueOf(sumTotal - completedQuantity));
        biViewInfo2.setPercentage((sumTotal - completedQuantity) / sumTotal * 100 + "%");
        biViewInfos1.add(biViewInfo1);
        biViewInfos1.add(biViewInfo2);
        biViewInfo.setBiViewInfoList(biViewInfos1);
        biViewInfos.add(biViewInfo);

        // 执行中的合同额 -已开票、待开票
        BiViewInfo biViewInfoa = new BiViewInfo();
        biViewInfoa.setBiType("2-销售合同（已开票、待开票）");
        BigDecimal bg1 = new BigDecimal(moneyTotal);
        biViewInfoa.setTotal(String.valueOf(bg1));
        List<BiViewInfo> biViewInfosa1 = new ArrayList<>();
        BiViewInfo biViewInfoa1 = new BiViewInfo();
        biViewInfoa1.setName("已开票");
        BigDecimal bg45 = new BigDecimal(invoicingTotal);
        biViewInfoa1.setCount(String.valueOf(bg45));
        biViewInfoa1.setPercentage(invoicingTotal != 0 ? invoicingTotal / moneyTotal * 100 + "%" : 0 + "%");
        BiViewInfo biViewInfoa2 = new BiViewInfo();
        biViewInfoa2.setName("待开票");
        BigDecimal bg4 = new BigDecimal(moneyTotal - (invoicingTotal != null ? invoicingTotal : 0));
        biViewInfoa2.setCount(String.valueOf(bg4));
        biViewInfoa2.setPercentage((moneyTotal - (invoicingTotal != null ? invoicingTotal : 0)) / moneyTotal * 100 + "%");
        biViewInfosa1.add(biViewInfoa1);
        biViewInfosa1.add(biViewInfoa2);
        biViewInfoa.setBiViewInfoList(biViewInfosa1);
        biViewInfos.add(biViewInfoa);


        // 执行中的合同额 -已付款、待付款
        BiViewInfo biViewInfob = new BiViewInfo();
        biViewInfob.setBiType("3-销售合同（已付款、待付款）");
        biViewInfob.setTotal(String.valueOf(bg1));
        List<BiViewInfo> biViewInfosb1 = new ArrayList<>();
        BiViewInfo biViewInfob1 = new BiViewInfo();
        biViewInfob1.setName("已付款");
        BigDecimal bg9 = new BigDecimal(payTotal);
        biViewInfob1.setCount(String.valueOf(bg9));
        biViewInfob1.setPercentage(payTotal != 0 ? payTotal / moneyTotal * 100 + "%" : 0 + "%");
        BiViewInfo biViewInfob2 = new BiViewInfo();
        biViewInfob2.setName("待付款");
        BigDecimal bg6 = new BigDecimal(moneyTotal - (payTotal != null ? payTotal : 0));
        biViewInfob2.setCount(String.valueOf(bg6));
        biViewInfob2.setPercentage((moneyTotal - (payTotal != null ? payTotal : 0)) / moneyTotal * 100 + "%");
        biViewInfosb1.add(biViewInfob1);
        biViewInfosb1.add(biViewInfob2);
        biViewInfob.setBiViewInfoList(biViewInfosb1);
        biViewInfos.add(biViewInfob);
        return biViewInfos;
    }
}

