/*
 * 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.biz.modular.depotMapPage.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Service;
import vip.xiaonuo.biz.api.DictOptions.entity.DictOptionsVo;
import vip.xiaonuo.biz.api.DictOptions.param.DictOptionsParam;
import vip.xiaonuo.biz.api.DictOptions.service.DictOptionsService;
import vip.xiaonuo.biz.core.Const.BizStr;
import vip.xiaonuo.biz.modular.depotAlarm.entity.DepotAlarm;
import vip.xiaonuo.biz.modular.depotAlarm.entity.DepotAlarmAddCountGroupTypeVo;
import vip.xiaonuo.biz.modular.depotAlarm.param.DepotAlarmPageParam;
import vip.xiaonuo.biz.modular.depotAlarm.service.DepotAlarmService;
import vip.xiaonuo.biz.modular.depotGrain.entity.DepotGrain;
import vip.xiaonuo.biz.modular.depotGrain.param.DepotGrainPageParam;
import vip.xiaonuo.biz.modular.depotGrain.service.DepotGrainService;
import vip.xiaonuo.biz.modular.depotGrainInfo.entity.DepotGrainInfo;
import vip.xiaonuo.biz.modular.depotGrainInfo.param.DepotGrainInfoPageParam;
import vip.xiaonuo.biz.modular.depotGrainInfo.service.DepotGrainInfoService;
import vip.xiaonuo.biz.modular.depotLoanGrant.entity.DepotLoanGrant;
import vip.xiaonuo.biz.modular.depotLoanGrant.service.DepotLoanGrantService;
import vip.xiaonuo.biz.modular.depotLockBook.entity.DepotLockBook;
import vip.xiaonuo.biz.modular.depotLockBook.service.DepotLockBookService;
import vip.xiaonuo.biz.modular.depotMapPage.entity.*;
import vip.xiaonuo.biz.modular.depotMapPage.mapper.DepotMapPageMapper;
import vip.xiaonuo.biz.modular.depotMapPage.param.DepotMapPagePageParam;
import vip.xiaonuo.biz.modular.depotRepayOrder.entity.DepotRepayOrder;
import vip.xiaonuo.biz.modular.depotRepayOrder.service.DepotRepayOrderService;
import vip.xiaonuo.biz.modular.depotSampling.entity.DepotSampling;
import vip.xiaonuo.biz.modular.depotSampling.service.DepotSamplingService;
import vip.xiaonuo.biz.modular.depotTruckBook.entity.DepotTruckBook;
import vip.xiaonuo.biz.modular.depotTruckBook.service.DepotTruckBookService;
import vip.xiaonuo.biz.modular.depotTruckWeighPlug.entity.DepotTruckWeighPlug;
import vip.xiaonuo.biz.modular.depotTruckWeighPlug.service.DepotTruckWeighPlugService;
import vip.xiaonuo.biz.modular.depotWork.entity.DepotWork;
import vip.xiaonuo.biz.modular.depotWork.param.DepotWorkPageParam;
import vip.xiaonuo.biz.modular.depotWork.service.DepotWorkService;
import vip.xiaonuo.biz.modular.depotZoneFutures.service.DepotZoneFuturesService;
import vip.xiaonuo.biz.modular.depotZonePrice.entity.DepotZonePrice;
import vip.xiaonuo.biz.modular.depotZonePrice.service.DepotZonePriceService;
import vip.xiaonuo.common.util.BeanCopyUtil;
import vip.xiaonuo.common.util.BigDecimalUtil;
import vip.xiaonuo.common.util.DatesUtil;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 地图页信息表Service接口实现类
 *
 * @author xiang
 * @date 2023/09/20 09:09
 **/
@Service
public class DepotMapPageService extends ServiceImpl<DepotMapPageMapper, DepotMapPage> {

    @Resource
    private DepotGrainService depotGrainService;
    @Resource
    private DepotLoanGrantService depotLoanGrantService;
    @Resource
    private DepotRepayOrderService depotRepayOrderService;
    @Resource
    private DepotTruckWeighPlugService depotTruckWeighPlugService;
    @Resource
    private DepotLockBookService depotLockBookService;
    @Resource
    private DepotTruckBookService depotTruckBookService;
    @Resource
    private DepotWorkService depotWorkService;
    @Resource
    private DepotGrainInfoService depotGrainInfoService;
    @Resource
    private DictOptionsService dictOptionsService;
    @Resource
    private DepotSamplingService depotSamplingService;
    @Resource
    private DepotAlarmService depotAlarmService;
    @Resource
    private DepotZonePriceService depotZonePriceService;
    @Resource
    private DepotZoneFuturesService depotZoneFuturesService;

    public Object page(DepotMapPagePageParam depotMapPagePageParam) {
        return null;
    }

    /**
     * 获取地图页信息_地区粮库数量列表
     *
     * @author xiang
     * @date 2023/09/20 09:09
     **/
    /*public List<MapZoneCountVo> mapZoneCount(String address) {
        List<MapZoneCountVo> vos = new ArrayList<>();
        //地区
        List<String> addressNames = dictOptionsService.dictOptions(new DictOptionsParam(address)).stream().map(DictOptionsVo::getLabel).distinct().collect(Collectors.toList());
        //粮库信息
        List<DepotGrainInfo> infos = depotGrainInfoService.list(new DepotGrainInfoPageParam(depotGrainService.lstOrgGrep()));
        for (String addressName : addressNames) {
            MapZoneCountVo vo = new MapZoneCountVo(addressName);
            vo.setValue(infos.stream().filter(info -> addressName.equals(info.getAddressCity()) || addressName.equals(info.getAddressCounty())).count());
            //if ("黑龙江省".equals(address) || vo.getValue() > 0)
            if (vo.getValue() > 0)
                vos.add(vo);
        }
        vos.sort(Comparator.comparing(MapZoneCountVo::getValue).reversed());
        return vos;
    }*/
    public List<MapZoneCountVo> mapZoneCount(String address) {
        List<MapZoneCountVo> vos = new ArrayList<>();
        //地区
        List<String> addressNames = dictOptionsService.dictOptions(new DictOptionsParam(address)).stream().map(DictOptionsVo::getLabel).distinct().collect(Collectors.toList());
        //粮库信息
        List<DepotGrainInfo> infos = depotGrainInfoService.list(new DepotGrainInfoPageParam(depotGrainService.lstOrgGrep()));
        for (String addressName : addressNames) {
            MapZoneCountVo vo = new MapZoneCountVo(addressName);
            //if ("黑龙江省".equals(address) || vo.getValue() > 0)
            for (DepotGrainInfo info : infos) {
                if (!addressName.equals(info.getAddressCity()) && !addressName.equals(info.getAddressCounty())) continue;
                vo.setValue(vo.getValue() + 1);
                vo.setLoanSum(BigDecimalUtil.addVal(vo.getLoanSum(), info.getLoanSum()));
                vo.setMortgageCount(BigDecimalUtil.addVal(vo.getMortgageCount(), info.getMortgageCount()));
                vo.setLoanInterest(BigDecimalUtil.addVal(vo.getLoanInterest(), info.getLoanInterest()));
            }
            if (vo.getValue() > 0)
                vos.add(vo);
        }
        return vos;
    }

    /**
     * 获取地图页信息_订单额统计
     *
     * @author xiang
     * @date 2023/09/20 09:09
     **/
    public OrderSumVo orderSum() {
        OrderSumVo vo = new OrderSumVo();
        List<DepotGrainInfo> infos = depotGrainInfoService.lst(new DepotGrainInfoPageParam(depotGrainService.lstOrgGrep()));
        for (DepotGrainInfo info : infos) {
            vo.setLoanSum(BigDecimalUtil.addVal(vo.getLoanSum(), info.getLoanSum()));
            vo.setMortgageCount(BigDecimalUtil.addVal(vo.getMortgageCount(), info.getMortgageCount()));
            vo.setLoanInterest(BigDecimalUtil.addVal(vo.getLoanInterest(), info.getLoanInterest()));
            vo.setLoanSumTotal(BigDecimalUtil.addVal(vo.getLoanSumTotal(), info.getLoanSumTotal()));
            vo.setRepaySumTotal(BigDecimalUtil.addVal(vo.getRepaySumTotal(), info.getRepaySumTotal()));
            vo.setMortgageCountTotal(BigDecimalUtil.addVal(vo.getMortgageCountTotal(), info.getMortgageCountTotal()));
        }
        return vo;
    }

    /**
     * 获取地图页信息_主流地价格列表
     *
     * @author xiang
     * @date 2023/09/20 09:09
     **/
    public List<DepotZonePriceVo> mainZonePrice() {
        List<DepotZonePrice> zonePrices = depotZonePriceService.lst(new DepotZonePrice());
        List<DepotZonePriceVo> vos = new ArrayList<>(zonePrices.size());
        zonePrices.forEach(one -> {
            if (one.getUpdateTime() == null)
                one.setUpdateTime(one.getCreateTime());
            vos.add(new DepotZonePriceVo(one.getZoneName(), one.getZonePrice(), one.getGrainGroup(), one.getUpdateTime()));
        });
        return vos;
    }

    /**
     * 获取地图页信息_地区交易额列表
     *
     * @author xiang
     * @date 2023/09/20 09:09
     **/
    public List<MapZoneSumVo> mapZoneSum(String address) {
        List<MapZoneSumVo> vos = new ArrayList<>();
        //粮库信息
        List<DepotGrainInfo> infos = depotGrainInfoService.lst(new DepotGrainInfoPageParam(depotGrainService.lstOrgGrep()));
        //地区
        List<String> addressNames = dictOptionsService.dictOptions(new DictOptionsParam(address)).stream().map(DictOptionsVo::getLabel).distinct().collect(Collectors.toList());
        for (String addressName : addressNames) {
            BigDecimal loanSum = BigDecimal.ZERO, loanInterest = BigDecimal.ZERO, lortgageCount = BigDecimal.ZERO;
            //统计总交易额
            for (DepotGrainInfo info : infos) {
                if (!Objects.equals(addressName, info.getAddressCity()) && !Objects.equals(addressName, info.getAddressCounty()))
                    continue;
                loanSum = BigDecimalUtil.addVal(loanSum, info.getLoanSum());
                loanInterest = BigDecimalUtil.addVal(loanInterest, info.getLoanInterest());
                lortgageCount = BigDecimalUtil.addVal(lortgageCount, info.getMortgageCount());
            }
            vos.add(new MapZoneSumVo(addressName, loanSum, lortgageCount, loanInterest));
        }
        return vos;
    }

    /**
     * 获取地图页信息_地区交易额弹框
     *
     * @author xiang
     * @date 2023/09/20 09:09
     **/
    public List<MapZoneSumGroupVo> mapZoneSumGroup(String address) {
        List<MapZoneSumGroupVo> vos = new ArrayList<>();
        //粮库信息
        List<DepotGrainInfo> infos = depotGrainInfoService.list(new DepotGrainInfoPageParam(depotGrainService.lstOrgGrep()));
        for (DepotGrainInfo info : infos) {
            if (!address.equals(info.getAddressCity()) && !address.equals(info.getAddressCounty())) continue;
            vos.add(new MapZoneSumGroupVo(info.getDepotGrainName(), info.getAddressCounty(), info.getLoanSum(), info.getMortgageCount()
                    , info.getLoanInterest(), info.getLoanSumTotal(), info.getMortgageCountTotal()));
        }
        vos.sort(Comparator.comparing(MapZoneSumGroupVo::getLoanInterest).reversed());
        return vos;
    }

    /**
     * 获取地图页信息_期货信息列表
     *
     * @author xiang
     * @date 2023/09/20 09:09
     **/
    public Object mapZoneFutures() {
        return BeanCopyUtil.copyListProperties(depotZoneFuturesService.lst(null), DepotMapFuturesVo::new);
    }

    /**
     * 获取地图页信息_预约审批统计
     *
     * @author xiang
     * @date 2023/09/20 09:09
     **/
    public WaitApprovalCountVo waitApprovalSum() {
        List<String> depotIdLst = depotGrainService.lstOrgGrep();
        WaitApprovalCountVo vo = new WaitApprovalCountVo();
        //车辆审批
        vo.setTruckBookCount((long) depotTruckBookService.waitProcess(depotIdLst).size());
        //扦样确认
        vo.setSamplingCount((long) depotSamplingService.waitProcess(depotIdLst).size());
        //还款申请
        vo.setRepayCount((long) depotRepayOrderService.waitProcess(depotIdLst).size());
        //放款申请
        vo.setLoanCount((long) depotLoanGrantService.waitProcess(depotIdLst).size());
        //人工补单
        vo.setPlugCount((long) depotTruckWeighPlugService.waitProcess(depotIdLst).size());
        //门锁预约
        vo.setLockCount((long) depotLockBookService.waitProcess(depotIdLst).size());
        return vo;
    }

    /**
     * 获取地图页信息_预约审批列表
     *
     * @author xiang
     * @date 2023/09/20 09:09
     **/
    public List<WaitApprovalCountGroupVo> waitApprovalGroup() {
        List<String> depotIdLst = depotGrainService.lstOrgGrep();
        List<WaitApprovalCountGroupVo> vos = new ArrayList<>();
        //粮库
        List<DepotGrain> depotGrains = depotGrainService.lst(new DepotGrainPageParam(null, depotIdLst));
        //车辆审批
        List<DepotTruckBook> books = depotTruckBookService.waitProcess(depotIdLst);
        //扦样确认
        List<DepotSampling> samplings = depotSamplingService.waitProcess(depotIdLst);
        //还款申请
        List<DepotRepayOrder> orders = depotRepayOrderService.waitProcess(depotIdLst);
        //放款申请
        List<DepotLoanGrant> grants = depotLoanGrantService.waitProcess(depotIdLst);
        //人工补单
        List<DepotTruckWeighPlug> plugs = depotTruckWeighPlugService.waitProcess(depotIdLst);
        //门锁预约
        List<DepotLockBook> lockBooks = depotLockBookService.waitProcess(depotIdLst);
        for (DepotGrain depotGrain : depotGrains) {
            List<DepotTruckBook> booksGroup = books.stream().filter(one -> Objects.equals(one.getDepotId(), depotGrain.getDepotId())).collect(Collectors.toList());
            if (!booksGroup.isEmpty())
                vos.add(new WaitApprovalCountGroupVo(depotGrain.getDepotId()
                        , depotGrain.getDepotGrainName()
                        , "车辆审批"
                        , booksGroup.size()
                        , booksGroup.get(0).getCreateTime()));
            List<DepotSampling> samplingsGroup = samplings.stream().filter(one -> Objects.equals(one.getDepotId(), depotGrain.getDepotId())).collect(Collectors.toList());
            if (!samplingsGroup.isEmpty())
                vos.add(new WaitApprovalCountGroupVo(depotGrain.getDepotId()
                        , depotGrain.getDepotGrainName()
                        , "扦样确认"
                        , samplingsGroup.size()
                        , samplingsGroup.get(0).getCreateTime()));
            List<DepotRepayOrder> ordersGroup = orders.stream().filter(one -> Objects.equals(one.getDepotId(), depotGrain.getDepotId())).collect(Collectors.toList());
            if (!ordersGroup.isEmpty())
                vos.add(new WaitApprovalCountGroupVo(depotGrain.getDepotId()
                        , depotGrain.getDepotGrainName()
                        , "还款申请"
                        , ordersGroup.size()
                        , ordersGroup.get(0).getCreateTime()));
            List<DepotLoanGrant> grantsGroup = grants.stream().filter(one -> Objects.equals(one.getDepotId(), depotGrain.getDepotId())).collect(Collectors.toList());
            if (!grantsGroup.isEmpty())
                vos.add(new WaitApprovalCountGroupVo(depotGrain.getDepotId()
                        , depotGrain.getDepotGrainName()
                        , "放款申请"
                        , grantsGroup.size()
                        , grantsGroup.get(0).getCreateTime()));
            List<DepotTruckWeighPlug> plugsGroup = plugs.stream().filter(one -> Objects.equals(one.getDepotId(), depotGrain.getDepotId())).collect(Collectors.toList());
            if (!plugsGroup.isEmpty())
                vos.add(new WaitApprovalCountGroupVo(depotGrain.getDepotId()
                        , depotGrain.getDepotGrainName()
                        , "人工补单"
                        , plugsGroup.size()
                        , plugsGroup.get(0).getCreateTime()));
            List<DepotLockBook> lockBooksGroup = lockBooks.stream().filter(one -> Objects.equals(one.getDepotId(), depotGrain.getDepotId())).collect(Collectors.toList());
            if (!lockBooksGroup.isEmpty())
                vos.add(new WaitApprovalCountGroupVo(depotGrain.getDepotId()
                        , depotGrain.getDepotGrainName()
                        , "门锁预约"
                        , lockBooksGroup.size()
                        , lockBooksGroup.get(0).getCreateTime()));
        }
        vos.sort(Comparator.comparing(WaitApprovalCountGroupVo::getTitleCount).reversed());
        return vos;
    }

    /**
     * 获取地图页信息_预约审批弹框
     *
     * @author xiang
     * @date 2023/09/20 09:09
     **/
    public List<WaitApprovalListVo> waitApprovalList(String depotId, String type) {
        List<WaitApprovalListVo> vos = new ArrayList<>();
        List<String> depotIdLst = Strings.isBlank(depotId) ? depotGrainService.lstOrgGrep() : Arrays.asList(depotId);
        if ("车辆审批".equals(type)) {
            List<DepotTruckBook> books = depotTruckBookService.waitProcess(depotIdLst);
            depotGrainService.putDepotName(books);
            books.forEach(one -> {
                vos.add(new WaitApprovalListVo(type, one.getDepotGrainName()
                        , String.format("%s %s %s %s ", one.getDepotBizType(), one.getGrainGroup(), one.getGrainType(), one.getLicensePlate())
                        , DatesUtil.forDateTime(one.getCreateTime())));
            });
        } else if ("扦样确认".equals(type)) {
            List<DepotSampling> samplings = depotSamplingService.waitProcess(depotIdLst);
            depotGrainService.putDepotName(samplings);
            samplings.forEach(one -> {
                String msg = String.format(
                        "%s %s %s；水份(%s)：%s，容重：%s，不完善率：%s，霉变：%s，杂质：%s，单价(元/吨)：%s"
                        , one.getLicensePlate(), one.getGrainGroup(), one.getGrainType(), "%"
                        , one.getSamplingShuiFen() == null ? " " : one.getSamplingShuiFen()
                        , one.getSamplingRongZhong() == null ? " " : one.getSamplingRongZhong()
                        , one.getSamplingQueShao() == null ? " " : one.getSamplingQueShao()
                        , one.getSamplingMeiBian() == null ? " " : one.getSamplingMeiBian()
                        , one.getSamplingZaZhi() == null ? " " : one.getSamplingZaZhi()
                        , one.getSamplingPrice());
                vos.add(new WaitApprovalListVo(type, one.getDepotGrainName(), msg, DatesUtil.forDateTime(one.getCreateTime())));
            });
        } else if ("还款申请".equals(type)) {
            List<DepotRepayOrder> orders = depotRepayOrderService.waitProcess(depotIdLst);
            depotGrainService.putDepotName(orders);
            orders.forEach(one -> {
                vos.add(new WaitApprovalListVo(type, one.getDepotGrainName()
                        , String.format("%s 还款金额：%s；还款数量(吨)：%s", one.getGrainGroup(), one.getRepayAmount(), one.getRepayTonThis())
                        , DatesUtil.forDateTime(one.getCreateTime())));
            });
        } else if ("放款申请".equals(type)) {
            List<DepotLoanGrant> grants = depotLoanGrantService.waitProcess(depotIdLst);
            depotGrainService.putDepotName(grants);
            grants.forEach(one -> {
                vos.add(new WaitApprovalListVo(type, one.getDepotGrainName()
                        , String.format("%s 放款金额：%s；放款数量(吨)：%s；车量：%s", one.getGrainGroup(), one.getLoanAmount(), one.getOrderWeight(), one.getLoanTruckCount())
                        , DatesUtil.forDateTime(one.getCreateTime())));
            });
        } else if ("人工补单".equals(type)) {
            List<DepotTruckWeighPlug> plugs = depotTruckWeighPlugService.waitProcess(depotIdLst);
            depotGrainService.putDepotName(plugs);
            plugs.forEach(one -> {
                vos.add(new WaitApprovalListVo(type, one.getDepotGrainName()
                        , String.format("%s %s %s %s 净重(公斤)：%s；单价(元/吨)：%s"
                        , one.getDepotBizType(), one.getGrainGroup(), one.getGrainType(), one.getLicensePlate(), one.getNetWeight(), one.getUnitPrice())
                        , DatesUtil.forDateTime(one.getCreateTime())));
            });
        } else if ("门锁预约".equals(type)) {
            List<DepotLockBook> lockBooks = depotLockBookService.waitProcess(depotIdLst);
            depotGrainService.putDepotName(lockBooks);
            lockBooks.forEach(one -> {
                vos.add(new WaitApprovalListVo(type, one.getDepotGrainName()
                        , String.format("库位：%s；锁：%s；描述：%s"
                        , one.getShedName(), one.getLockName(), one.getRemark())
                        , DatesUtil.forDateTime(one.getCreateTime())));
            });
        }
        vos.sort(Comparator.comparing(WaitApprovalListVo::getCreateTime).reversed());
        return vos;
    }

    /**
     * 获取地图页信息_报警统计
     *
     * @author xiang
     * @date 2023/09/19 16:23
     **/
    public DepotAlarmAddCountGroupTypeVo waitProcessSum() {
        return depotAlarmService.getAlarmAddCountGroupType(new DepotAlarmPageParam());
    }

    /**
     * 获取地图页信息_报警弹框
     *
     * @author xiang
     * @date 2023/09/19 16:23
     **/
    public Object waitProcessList(DepotAlarmPageParam param) {
        List<DepotAlarm> list = depotAlarmService.list(new DepotAlarmPageParam(param.getAlarmType(), BizStr.STATE_PROCESS_N));
        return BeanCopyUtil.copyListProperties(list, WaitProcessListVo::new);
    }

    /**
     * 获取地图页信息粮库出库入库
     *
     * @author xiang
     * @date 2023/09/20 09:09
     **/
    public List<WorkSumVo> workSum() {

        //出库入库记录
        List<DepotWork> works = depotWorkService.lst(new DepotWorkPageParam());
        List<String> depotIds = works.stream().map(DepotWork::getDepotId).distinct().collect(Collectors.toList());
        List<WorkSumVo> voList = new ArrayList<>(depotIds.size());

        for (String depotId : depotIds) {
            List<DepotWork> worksGroup = works.stream().filter(w -> Objects.equals(w.getDepotId(), depotId)).collect(Collectors.toList());
            if (worksGroup.isEmpty()) break;
            WorkSumVo vo = new WorkSumVo(worksGroup.get(0).getDepotGrainName());
            voList.add(vo);
            for (DepotWork work : worksGroup) {
                if (BizStr.KU_RU.equals(work.getDepotBizType())) {
                    vo.setInTonCount(BigDecimalUtil.addVal(work.getDepotTonCount(), vo.getInTonCount()));
                    vo.setInAmount(BigDecimalUtil.addVal(work.getOrderAmount(), vo.getInAmount()));
                } else if (BizStr.KU_CHU.equals(work.getDepotBizType())) {
                    vo.setOutTonCount(BigDecimalUtil.addVal(work.getDepotTonCount(), vo.getOutTonCount()));
                    vo.setOutAmount(BigDecimalUtil.addVal(work.getOrderAmount(), vo.getOutAmount()));
                }
            }
            vo.setSumTonCount(BigDecimalUtil.addVal(vo.getOutTonCount(), vo.getInTonCount()));
            vo.setSumAmount(BigDecimalUtil.addVal(vo.getOutAmount(), vo.getInAmount()));
        }

        return voList;
    }

}
