package com.zfire.mall.manager.logic.reserved;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zfire.mall.manager.bean.ExcelData;
import com.zfire.mall.manager.bean.admin.AdminUserCom;
import com.zfire.mall.manager.bean.invoice.InvoiceProjectVO;
import com.zfire.mall.manager.bean.k3.KingDeeMaterialBean;
import com.zfire.mall.manager.bean.k3.StockPositionStock;
import com.zfire.mall.manager.bean.listV2.dto.InvoiceProjectDTO;
import com.zfire.mall.manager.bean.reserved.*;
import com.zfire.mall.manager.commonmapper.InvoiceMapper;
import com.zfire.mall.manager.commonmapper.stock.ReservedMapper;
import com.zfire.mall.manager.enums.IsEnum;
import com.zfire.mall.manager.exception.RemoteServiceException;
import com.zfire.mall.manager.logic.common.CommonLogic;
import com.zfire.mall.manager.logic.customer.CustomerProductTypeLogic;
import com.zfire.mall.manager.logic.invoice.InvoiceLogic;
import com.zfire.mall.manager.logic.stock.StockCommonLogic;
import com.zfire.mall.manager.plus.entity.*;
import com.zfire.mall.manager.plus.service.*;
import com.zfire.mall.manager.zfire.bean.ZfireParamBean;
import com.zfire.mall.manager.zfire.util.FieldUtils;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 申请发货单
 *
 * @author change
 */
@Service
@Slf4j
public class ReservedLogic {

    @Autowired
    ReservedMapper reservedMapper;

    @Autowired
    ReservedOrderService reservedOrderService;


    @Autowired
    ReservedOrderItemService reservedOrderItemService;


    @Autowired
    StockCommonLogic stockCommonLogic;

    @Autowired
    CommonLogic commonLogic;

    @Autowired
    CustomerProductTypeLogic customerProductTypeLogic;

    @Autowired
    AdminUserService adminUserService;

    @Autowired
    KingDeeMaterialService kingDeeMaterialService;

    @Autowired
    KingDeeCustomerService kingDeeCustomerService;

    @Autowired
    RetailOrderService retailOrderService;


    @Autowired
    DisplaceOrderService displaceOrderService;

    @Autowired
    EnginOrderService enginOrderService;

    @Autowired
    InvoiceApplicationService invoiceApplicationService;

    @Autowired
    RetailOrderItemService retailOrderItemService;

    @Autowired
    DisplaceOrderItemService displaceOrderItemService;

    @Autowired
    EnginOrderItemService enginOrderItemService;

    @Autowired
    InvoiceMapper invoiceMapper;

    @Autowired
    SysDictService sysDictService;

    @Autowired
    InvoiceLogic invoiceLogic;

    @Autowired
    StockCorrespondService stockCorrespondService;

    @Autowired
    AdminWebsitService adminWebsitService;


    public IPage<ReservedBean> list(String createBy,String updateBy,String id, Integer status, String correspondId, String customerName, String orderId, String specification, String startTime, String endTime,
                                    String customerNumber, String materialCode, String materialName, Integer pageNum, Integer pageSize) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String customerId = adminUser.getIsCustomer() ? adminUser.getCustomerId() : "";

        IPage<ReservedBean> list = reservedMapper.list(new Page<>(pageNum, pageSize),createBy,updateBy, id, status, correspondId, customerName, orderId, specification, startTime, endTime
                , customerNumber, materialCode, materialName, customerId,adminUser.getAdminUserId());
        return list;
    }

    public ReservedDetail detail(String id) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        ReservedOrder reservedOrder = reservedOrderService.getById(id);
        ReservedDetail reservedDetail = BeanUtil.toBean(reservedOrder, ReservedDetail.class);

        List<ReservedOrderItem> list = reservedOrderItemService.lambdaQuery()
                .eq(adminUser.getIsCustomer(), ReservedOrderItem::getCustomerNumber, adminUser.getCustomerNumber())
                .eq(ReservedOrderItem::getReservedId, reservedDetail.getId())
                .list();

        reservedDetail.setReservedOrderItems(list);

        return reservedDetail;
    }

    @Transactional(rollbackFor = Exception.class)
    public void add(ReservedAdd reservedAdd) {

        AdminUserCom adminUser = commonLogic.getAdminUser();

        if (adminUser.getIsCustomer())
            throw new RemoteServiceException("经销商不可操作预留单");

        reservedAdd.setOrderTime(new Date());
        reservedOrderService.save(reservedAdd);

        //添加详细预留单
        List<ReservedOrderItem> reservedOrderItems = new ArrayList<>();
        for (ReservedOrderItem reservedOrderItem : reservedAdd.getReservedOrderItems()) {

 /*           if (!StringUtils.isEmpty(reservedOrderItem.getCorrespondId())) {
                ReservedOrderItem reservedOrder = reservedOrderItemService.lambdaQuery().eq(ReservedOrderItem::getOrderId, reservedOrderItem.getOrderId())
                        .eq(ReservedOrderItem::getCorrespondId, reservedOrderItem.getCorrespondId()).one();
                if (reservedOrder != null) {
                    reservedOrder.setReservedNum(reservedOrderItem.getReservedNum() + reservedOrder.getReservedNum());
                    reservedOrder.setStatus(1);
                    reservedOrder.updateById();
                    continue;
                }

            }
            if (StringUtils.isEmpty(reservedOrderItem.getCorrespondId())) {
                ReservedOrderItem one = reservedOrderItemService.lambdaQuery().eq(ReservedOrderItem::getOrderId, reservedOrderItem.getOrderId())
                        .isNull(ReservedOrderItem::getCorrespondId).one();
                if (one != null) {
                    one.setReservedNum(reservedOrderItem.getReservedNum() + one.getReservedNum());
                    one.setStatus(1);
                    one.updateById();
                    continue;
                }
            }*/
            reservedOrderItem.setOrderTime(new Date());
            if (reservedOrderItem.getReservedNum() == null)
                throw new RemoteServiceException("预留数量为空，请填写数量");

            if (StringUtils.isEmpty(reservedOrderItem.getCustomerId()))
                throw new RemoteServiceException("经销商为空");

            reservedOrderItem.setOldNum(reservedOrderItem.getReservedNum());
            reservedOrderItem.setReservedId(reservedAdd.getId());
            //增加预留单数量经销商
            if (reservedOrderItem.getStatus() == null || reservedOrderItem.getStatus().equals(1)) {
                stockCommonLogic.inventoryStockCustomer(reservedOrderItem.getMaterialId(), reservedOrderItem.getCustomerId(), reservedOrderItem.getReservedNum());
            }

            //添加零售订单的申请发货单详细
            if (!StringUtils.isEmpty(reservedOrderItem.getOrderType())) {
                if (reservedOrderItem.getOrderType().equals("RETAIL") || reservedOrderItem.getOrderType().equals("RETAIL_POLICY")) {
                    //检查订单可申请数量是否大于申请数量
                    //检查订单可申请数量是否大于申请数量
                    RetailOrderItem retailOrderItem = retailOrderItemService.getById(reservedOrderItem.getOrderId());
                    Integer integer = invoiceMapper.selectInvoice(reservedOrderItem.getOrderId());
                    Integer reservation = invoiceMapper.selectReserved(reservedOrderItem.getOrderId());
                    if (integer == null)
                        integer = 0;

                    Integer i = reservation + integer;
                    if (reservedOrderItem.getReservedNum() > retailOrderItem.getRefundableQty()-i)
                        throw new RemoteServiceException("当前申请数量大于可申请数量,可预留数量"+(retailOrderItem.getRefundableQty() - i));
                }
                //置换单存入申请发货单详细
                if (reservedOrderItem.getOrderType().equals("PERMU_RETAIL") || reservedOrderItem.getOrderType().equals("PERMU_RETAIL_POLICY")) {
                    //检查订单可申请数量是否大于申请数量
                    invoiceLogic.invoicePermuOrder(reservedOrderItem.getOrderId(), reservedOrderItem.getReservedNum());
                }

                //置换单存入申请发货单详细
                if (reservedOrderItem.getOrderType().equals("HOME") || reservedOrderItem.getOrderType().equals("TRADE")) {
                    //检查订单可申请数量是否大于申请数量
                    EnginOrderItem enginOrderItem = enginOrderItemService.getById(reservedOrderItem.getOrderId());
                    Integer integer = invoiceMapper.selectInvoice(reservedOrderItem.getOrderId());
                    Integer reservation = invoiceMapper.selectReserved(reservedOrderItem.getOrderId());
                    if (integer == null)
                        integer = 0;

                    Integer i = reservation + integer;
                    if (reservedOrderItem.getReservedNum() > enginOrderItem.getRefundableQty()-i)
                        throw new RemoteServiceException("当前申请数量大于可申请数量，可预留数量"+(enginOrderItem.getRefundableQty() - i));
                }

                //调拨单存入申请发货单详细
             /*   if (reservedOrderItem.getOrderType().equals("REQUISITION_RETAIL") || reservedOrderItem.getOrderType().equals("REQUISITION_RETAIL_POLICY")) {
                    //检查订单可申请数量是否大于申请数量
                    invoiceLogic.invoiceRequisitionOrder(reservedOrderItem.getOrderId(), reservedOrderItem.getReservedNum());

                }*/
            }

            KingDeeCustomer kingDeeCustomer = kingDeeCustomerService.getById(reservedOrderItem.getCustomerId());
            KingDeeMaterial kingDeeMaterialServiceById = kingDeeMaterialService.getById(reservedOrderItem.getMaterialId());
            reservedOrderItem.setMaterialCode(kingDeeMaterialServiceById.getNumber());
            reservedOrderItem.setCustomerNumber(kingDeeCustomer.getNumber());
            reservedOrderItem.setK3CategoryName(kingDeeMaterialServiceById.getCategoryName());
            reservedOrderItem.setK3CategoryId(kingDeeMaterialServiceById.getCategoryId());
            reservedOrderItems.add(reservedOrderItem);
        }
        reservedOrderItemService.saveBatch(reservedOrderItems);
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(String itemId, HttpServletRequest request) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        if (adminUser.getIsCustomer())
            throw new RemoteServiceException("经销商不可操作预留单");
        ReservedOrderItem byId = reservedOrderItemService.getById(itemId);
        byId.setStatus(0);
        byId.setClosureBy(adminUser.getNickName());
        byId.setClosureTime(new Date());
        byId.updateById();

        reservedOrderItemService.removeById(itemId);
        //减少预留单数量经销商
        stockCommonLogic.reduceStockCustomer(byId.getMaterialId(), byId.getCustomerId(), byId.getReservedNum());
    }

    public IPage<ReservedOrderBean> listOrder(String materialOldNumber, String correspondId, String
            customerName, String orderId, String specification, String mainName, String orderType,
                                              String customerNumber, String materialCode, String materialName, Integer pageNum, Integer pageSize) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String customerId = adminUser.getIsCustomer() ? adminUser.getCustomerId() : "";

        if (!StringUtils.isEmpty(orderType) &&  orderType.equals("RETAIL"))
            orderType = "1";
        else if (!StringUtils.isEmpty(orderType) &&  orderType.equals("RETAIL_POLICY"))
            orderType = "2";

        Integer count = reservedMapper.listOrderCount(materialOldNumber, customerName, orderId, specification, mainName, orderType, customerNumber
                , materialCode, materialName, customerId, adminUser.getServiceIds(), adminUser.getK3CategoryIds());


        IPage<ReservedOrderBean> reservedOrderIPage = reservedMapper.listOrder(new Page<>(pageNum, pageSize,count,false), materialOldNumber, customerName, orderId, specification, mainName, orderType, customerNumber
                , materialCode, materialName, customerId, adminUser.getServiceIds(), adminUser.getK3CategoryIds());

        reservedOrderIPage.setTotal(count);
        for (ReservedOrderBean record : reservedOrderIPage.getRecords()) {
            record.setOpenNumber(stockCommonLogic.stockOpendNumber(correspondId, record.getMaterialId()));
        }
        return reservedOrderIPage;
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateReserved(ReservedAdd reservedAdd, HttpServletRequest request) {
        reservedOrderService.updateById(reservedAdd);
        AdminUserCom adminUser = commonLogic.getAdminUser();
        if (adminUser.getIsCustomer())
            throw new RemoteServiceException("经销商不可操作预留单");
        for (ReservedOrderItem reservedOrderItem : reservedAdd.getReservedOrderItems()) {
            if (reservedOrderItem.getStatus().equals(0)){
                reservedOrderItem.setClosureTime(new Date());
                reservedOrderItem.setClosureBy(adminUser.getNickName());
            }
        }
        reservedOrderItemService.updateBatchById(reservedAdd.getReservedOrderItems());
        for (ReservedOrderItem reservedOrderItem : reservedAdd.getReservedOrderItems()) {




            //判断当前订单是否可以预留订单
            if (!StringUtils.isEmpty(reservedOrderItem.getOrderType())) {
                if (reservedOrderItem.getOrderType().equals("RETAIL") || reservedOrderItem.getOrderType().equals("RETAIL_POLICY")) {
                    //检查订单可申请数量是否大于申请数量
                    //检查订单可申请数量是否大于申请数量
                    RetailOrderItem retailOrderItem = retailOrderItemService.getById(reservedOrderItem.getOrderId());
                    Integer integer = invoiceMapper.selectInvoice(reservedOrderItem.getOrderId());
                    Integer reservation = invoiceMapper.selectReserved(reservedOrderItem.getOrderId());
                    if (integer == null)
                        integer = 0;

                    Integer i = reservation + integer;
                    if (reservedOrderItem.getReservedNum() > retailOrderItem.getRefundableQty() - i + reservedOrderItem.getReservedNum())
                        throw new RemoteServiceException("当前申请数量大于可申请数量，可预留数量" + (retailOrderItem.getRefundableQty() - i + reservedOrderItem.getReservedNum()));
                }
                //置换单存入申请发货单详细
                if (reservedOrderItem.getOrderType().equals("PERMU_RETAIL") || reservedOrderItem.getOrderType().equals("PERMU_RETAIL_POLICY")) {
                    //检查订单可申请数量是否大于申请数量
                    invoiceLogic.invoicePermuOrder(reservedOrderItem.getOrderId(), reservedOrderItem.getReservedNum());
                }

                //置换单存入申请发货单详细
                if (reservedOrderItem.getOrderType().equals("HOME") || reservedOrderItem.getOrderType().equals("TRADE")) {
                    //检查订单可申请数量是否大于申请数量
                    EnginOrderItem enginOrderItem = enginOrderItemService.getById(reservedOrderItem.getOrderId());
                    Integer integer = invoiceMapper.selectInvoice(reservedOrderItem.getOrderId());
                    Integer reservation = invoiceMapper.selectReserved(reservedOrderItem.getOrderId());
                    if (integer == null)
                        integer = 0;

                    Integer i = reservation + integer;
                    if (reservedOrderItem.getReservedNum() > enginOrderItem.getRefundableQty() - i + reservedOrderItem.getReservedNum())
                        throw new RemoteServiceException("当前申请数量大于可申请数量,可预留数量" + (enginOrderItem.getRefundableQty() - i + reservedOrderItem.getReservedNum()));
                }
                //增加预留单数量经销商
                if (reservedOrderItem.getStatus() == null || reservedOrderItem.getStatus().equals(1)) {
                    stockCommonLogic.inventoryStockCustomer(reservedOrderItem.getMaterialId(), reservedOrderItem.getCustomerId(), reservedOrderItem.getReservedNum());
                } else {
                    //减少预留单数量经销商
                    stockCommonLogic.reduceStockCustomer(reservedOrderItem.getMaterialId(), reservedOrderItem.getCustomerId(), reservedOrderItem.getReservedNum());
                }
            }
        }
    }

    /**
     * 预留单数据导出
     *
     * @param reservedBeans
     * @return
     */
    public ExcelData export(List<ReservedBean> reservedBeans) {
        String[] titles = new String[]{"预留单号", "预留日期", "销售订单号", "订单日期","预留仓库",
                "物料代码", "厂产品代码", "产品名称", "规格型号", "单位","原预留数量", "预留数量", "订单数量", "备注",
                "经销商编码", "经销商名称", "制表人", "制表日期", "修改人", "修改日期", "关闭人", "关闭日期"};
        List<List<Object>> rows = new ArrayList<>();
        for (ReservedBean reservedBean : reservedBeans) {
            List<Object> row = new ArrayList<>();
            row.add(reservedBean.getId());
            row.add(DateUtil.formatDate(reservedBean.getCreateTime()));
            row.add(reservedBean.getMainOrderId());
            row.add(DateUtil.formatDate(reservedBean.getOrderTime()));

            row.add(reservedBean.getCorrespondName());
            row.add(reservedBean.getMaterialCode());
            row.add(reservedBean.getMaterialOldNumber());
            row.add(reservedBean.getMaterialName());
            row.add(reservedBean.getSpecification());
            row.add(reservedBean.getUnit());
            row.add(reservedBean.getOldNum());
            row.add(reservedBean.getReservedNum());
            row.add(reservedBean.getQty());
            row.add(reservedBean.getRemark());
            row.add(reservedBean.getCustomerNumber());
            row.add(reservedBean.getCustomerName());
            row.add(reservedBean.getCreateBy());
            row.add(DateUtil.formatDate(reservedBean.getCreateTime()));
            row.add(reservedBean.getUpdateBy());
            row.add(DateUtil.formatDate(reservedBean.getUpdateTime()));
            row.add(reservedBean.getClosureBy());
            row.add(DateUtil.formatDate(reservedBean.getClosureTime()));
            rows.add(row);
        }
        ExcelData excelData = new ExcelData();
        excelData.setRows(rows);
        excelData.setTitles(Arrays.asList(titles));
        return excelData;
    }

    @Transactional(rollbackFor = Exception.class)
    public void automaticReserved() {



        SysDict sysDictGuangZhou = sysDictService.lambdaQuery().eq(SysDict::getDictCode, "GUANG_ZHOU_RESERVED_DAY").one();
        SysDict sysDictFoShan = sysDictService.lambdaQuery().eq(SysDict::getDictCode, "FO_SHAN_RESERVED_DAY").one();

        //广州订单预留
        Calendar todayGuangZhou = new GregorianCalendar(TimeZone.getTimeZone("GMT+8"));
        todayGuangZhou.add(Calendar.DAY_OF_MONTH, 0 - Convert.toInt(sysDictGuangZhou.getDictValue()));
        Date guangZhouDate = todayGuangZhou.getTime();
        List<ReservedOrderBean> reservedOrderBeanGuangZhou = listOrderReserved(guangZhouDate,"GZ");
        if (!CollectionUtils.isEmpty(reservedOrderBeanGuangZhou)) {

            for (ReservedOrderBean reservedOrderBean : reservedOrderBeanGuangZhou) {

                List<ReservedAdd> reservedAdds = new ArrayList<>();

                Integer number = reservedOrderBean.getRefundableQty();
                IPage<StockPositionStock> stockPositionStockIPage = listStock(null, null, 1, -1, reservedOrderBean.getCustomerId());
                if (!CollectionUtils.isEmpty(stockPositionStockIPage.getRecords())) {

                    for (StockPositionStock record : stockPositionStockIPage.getRecords()) {
                        if (number.equals(0))
                            break;
                        ReservedOrderItem reservedOrderItem = new ReservedOrderItem();
                        reservedOrderItem = BeanUtil.toBean(reservedOrderBean, ReservedOrderItem.class);
                        reservedOrderItem.setCorrespondId(record.getId());
                        reservedOrderItem.setCorrespondName(record.getName());
                        reservedOrderItem.setK3CategoryName(record.getName());
                        reservedOrderItem.setReservedStatus(1);
                        reservedOrderItem.setReservedStatus(1);

                       // Integer integer = stockCommonLogic.stockOpendNumber(record.getId(), reservedOrderBean.getMaterialId());

                        //查询该仓库库存
                        Integer integer = stockCommonLogic.stockCorrespondStatusRe(null, record.getId(), reservedOrderBean.getMaterialId(),reservedOrderBean.getCustomerId());
                        if (integer >= number){
                            reservedOrderItem.setReservedNum(number);
                            number=0;
                        }else if (integer < number && integer > 0){
                            reservedOrderItem.setReservedNum(integer);
                            number = number - integer;
                        }
                        if (integer <= 0){
                            continue;
                        }

                        List<ReservedOrderItem> reservedOrderItems = new ArrayList<>();
                        reservedOrderItems.add(reservedOrderItem);

                        ReservedAdd reservedAdd = new ReservedAdd();
                        reservedAdd.setReservedOrderItems(reservedOrderItems);
                        reservedAdd.setCreateBy("系统生成");
                        reservedAdd.setUpdateBy("系统生成");
                        reservedAdds.add(reservedAdd);


                    }

                }else {
                    break;
                }

                if (number <= 0 && !CollectionUtils.isEmpty(reservedAdds)){
                    for (ReservedAdd reservedAdd : reservedAdds) {
                        try {
                            this.add(reservedAdd);
                        }catch (Exception e){
                            log.info(e.getMessage());
                        }
                    }

                }

            }
        /*    if (!CollectionUtils.isEmpty(reservedOrderItems)) {
                reservedAdd.setReservedOrderItems(reservedOrderItems);
                reservedAdd.setCreateBy("系统生成");
                reservedAdd.setUpdateBy("系统生成");
                add(reservedAdd);
            }*/
        }

        //佛山订单预留
        Calendar todayFoShan = new GregorianCalendar(TimeZone.getTimeZone("GMT+8"));
        todayFoShan.add(Calendar.DAY_OF_MONTH, 0 - Convert.toInt(sysDictFoShan.getDictValue()));
        Date foShanDate = todayFoShan.getTime();
        List<ReservedOrderBean> reservedOrderBeanFoShan = listOrderReserved(foShanDate,"FS");

        if (!CollectionUtils.isEmpty(reservedOrderBeanFoShan)) {
            for (ReservedOrderBean reservedOrderBean : reservedOrderBeanFoShan) {

                List<ReservedAdd> reservedAdds = new ArrayList<>();

                Integer number = reservedOrderBean.getRefundableQty();
                IPage<StockPositionStock> stockPositionStockIPage = listStock(null, null, 1, -1, reservedOrderBean.getCustomerId());
                if (!CollectionUtils.isEmpty(stockPositionStockIPage.getRecords())) {

                    for (StockPositionStock record : stockPositionStockIPage.getRecords()) {
                        if (number == 0)
                            break;
                        ReservedOrderItem reservedOrderItem = new ReservedOrderItem();
                        reservedOrderItem = BeanUtil.toBean(reservedOrderBean, ReservedOrderItem.class);
                        reservedOrderItem.setCorrespondId(record.getId());
                        reservedOrderItem.setCorrespondName(record.getName());
                        reservedOrderItem.setK3CategoryName(record.getName());
                        reservedOrderItem.setReservedStatus(1);

                        //查询该仓库库存
                        Integer integer = stockCommonLogic.stockCorrespondStatusRe(null, record.getId(), reservedOrderBean.getMaterialId(),reservedOrderBean.getCustomerId());
                        if (integer >= number){
                            reservedOrderItem.setReservedNum(number);
                            number=0;
                        }else if (integer <= number && integer > 0){
                            reservedOrderItem.setReservedNum(integer);
                            number = number - integer;
                        }
                        if (integer <= 0){
                            continue;
                        }
                        List<ReservedOrderItem> reservedOrderItems = new ArrayList<>();
                        reservedOrderItems.add(reservedOrderItem);

                        ReservedAdd reservedAdd = new ReservedAdd();
                        reservedAdd.setReservedOrderItems(reservedOrderItems);
                        reservedAdd.setCreateBy("系统生成");
                        reservedAdd.setUpdateBy("系统生成");
                        reservedAdds.add(reservedAdd);

                    }

                }else {
                    break;
                }

                if (number <= 0 && !CollectionUtils.isEmpty(reservedAdds)){
                    for (ReservedAdd reservedAdd : reservedAdds) {
                        try {
                            this.add(reservedAdd);
                        }catch (Exception e){
                            log.info(e.getMessage());
                        }
                    }

                }
            }

        }


    }

    private List<ReservedOrderBean> listOrderReserved(Date today, String type) {

        List<String> collect = adminWebsitService.lambdaQuery().eq(AdminWebsit::getWebsitNumber, type).select(AdminWebsit::getAdminWebsitId).list()
                .stream().map(AdminWebsit::getAdminWebsitId).distinct().collect(Collectors.toList());


        List<ReservedOrderBean> reservedOrderIPage = reservedMapper.listOrderReserved(today,collect);

        return reservedOrderIPage;
    }

    public IPage<KingDeeMaterial> detailMaterialNumber(String number,String name,String specification,Integer pageNum, Integer pageSize) {
        IPage<KingDeeMaterial> list = kingDeeMaterialService.lambdaQuery()
                .like(StringUtils.isNotEmpty(number),KingDeeMaterial::getNumber, number)
                .like(StringUtils.isNotEmpty(name),KingDeeMaterial::getName, name)
                .like(StringUtils.isNotEmpty(specification),KingDeeMaterial::getSpecification, specification)
                .page(new Page<>(pageNum, pageSize));
        return list;
    }

    public List<KingDeeCustomer> detailCustomer(String number,String name) {
        List<KingDeeCustomer> list = kingDeeCustomerService.lambdaQuery()
                .like(StringUtils.isNotEmpty(number),KingDeeCustomer::getNumber, number)
                .like(StringUtils.isNotEmpty(name),KingDeeCustomer::getName, name)
                .eq(KingDeeCustomer::getJiaxianType, "KING")
                .list();
        return list;
    }

    public void reduceReserved(InvoiceApplicationOrder order, String correspondId) {
        InvoiceApplication invoiceApplicationServiceById = invoiceApplicationService.getById(order.getInvoiceId());

        Integer refundableQty = order.getRefundableQty();

        //更改预留单中绑定订单的物料预留数量

        // 更改对应仓库数量  订单+仓库扣除
        List<ReservedOrderItem> reservedOrderItemList = reservedOrderItemService.lambdaQuery()
                .eq(ReservedOrderItem::getCustomerId, invoiceApplicationServiceById.getCustomerId())
                .eq(ReservedOrderItem::getStatus, 1)
                .eq(ReservedOrderItem::getMaterialId, order.getMaterialId())
                .eq(ReservedOrderItem::getOrderId, order.getOrderId())
                .eq(ReservedOrderItem::getCorrespondId, correspondId).list();
        if (!CollectionUtils.isEmpty(reservedOrderItemList)) {
            for (ReservedOrderItem orderItem : reservedOrderItemList) {
                if (refundableQty.equals(0)) {
                    continue;
                }
                Integer resNumber = orderItem.getReservedNum();
                orderItem.setReservedNum((orderItem.getReservedNum() - refundableQty) < 0 ? 0 : orderItem.getReservedNum() - refundableQty);
                refundableQty = (refundableQty - resNumber) <= 0 ? 0 : (refundableQty - resNumber);
                if (orderItem.getReservedNum().equals(0)) {
                    orderItem.setStatus(0);
                    orderItem.setClosureBy("订单发完系统关闭");
                    orderItem.setClosureTime(new Date());
                }
                orderItem.updateById();
            }

        }

        //订单+无仓库扣除
        List<ReservedOrderItem> reservedOrderItems = reservedOrderItemService.lambdaQuery()
                .eq(ReservedOrderItem::getCustomerId, invoiceApplicationServiceById.getCustomerId())
                .eq(ReservedOrderItem::getMaterialId, order.getMaterialId())
                .eq(ReservedOrderItem::getOrderId, order.getOrderId())
                .eq(ReservedOrderItem::getStatus,1)
                .and(wraaper -> wraaper.ne(ReservedOrderItem::getCorrespondId, correspondId)
                        .or().isNull(ReservedOrderItem::getCorrespondId))
                .orderByAsc(ReservedOrderItem::getCreateTime).list();

        if (!CollectionUtils.isEmpty(reservedOrderItems)) {
            for (ReservedOrderItem orderItem : reservedOrderItems) {
                if (refundableQty.equals(0)) {
                    continue;
                }
                Integer resNumber = orderItem.getReservedNum();
                orderItem.setReservedNum((orderItem.getReservedNum() - refundableQty) < 0 ? 0 : orderItem.getReservedNum() - refundableQty);
                refundableQty = (refundableQty - resNumber) <= 0 ? 0 : (refundableQty - resNumber);
                if (orderItem.getReservedNum().equals(0)) {
                    orderItem.setStatus(0);
                    orderItem.setClosureBy("订单发完系统关闭");
                    orderItem.setClosureTime(new Date());
                }
                orderItem.updateById();
            }

        }


        //更改无绑定订单的物料预留数量  物料+订单为空扣除
        List<ReservedOrderItem> list = reservedOrderItemService.lambdaQuery()
                .eq(ReservedOrderItem::getCustomerId, invoiceApplicationServiceById.getCustomerId())
                .eq(ReservedOrderItem::getStatus,1)
                .eq(ReservedOrderItem::getMaterialId, order.getMaterialId())
                .isNull(ReservedOrderItem::getOrderId).list();


        if (!CollectionUtils.isEmpty(list)) {
            for (ReservedOrderItem orderItem : list) {
                if (refundableQty.equals(0)) {
                    continue;
                }
                Integer resNumber = orderItem.getReservedNum();
                orderItem.setReservedNum(orderItem.getReservedNum() - refundableQty < 0 ? 0 : orderItem.getReservedNum() - refundableQty);
                refundableQty = (refundableQty - resNumber) <= 0 ? 0 : (refundableQty - resNumber);
                if (orderItem.getReservedNum().equals(0)) {
                    orderItem.setStatus(0);
                    orderItem.setClosureBy("订单发完系统关闭");
                    orderItem.setClosureTime(new Date());
                }
                orderItem.updateById();
            }

        }


        //不对应订单，物料扣除
        List<ReservedOrderItem> res = reservedOrderItemService.lambdaQuery()
                .eq(ReservedOrderItem::getCustomerId, invoiceApplicationServiceById.getCustomerId())
                .eq(ReservedOrderItem::getStatus,1)
                .eq(ReservedOrderItem::getMaterialId, order.getMaterialId())
                .list();


        if (!CollectionUtils.isEmpty(res)) {
            for (ReservedOrderItem orderItem : res) {
                if (refundableQty.equals(0)) {
                    continue;
                }
                Integer resNumber = orderItem.getReservedNum();
                orderItem.setReservedNum(orderItem.getReservedNum() - refundableQty < 0 ? 0 : orderItem.getReservedNum() - refundableQty);
                refundableQty = (refundableQty - resNumber) <= 0 ? 0 : (refundableQty - resNumber);
                if (orderItem.getReservedNum().equals(0)) {
                    orderItem.setStatus(0);
                    orderItem.setClosureBy("订单发完系统关闭");
                    orderItem.setClosureTime(new Date());
                }
                orderItem.updateById();
            }

        }

        if (!order.getRefundableQty().equals(refundableQty)) {
            InvoiceApplication invoiceApplication = new InvoiceApplication();
            invoiceApplication.setId(invoiceApplicationServiceById.getId());
            invoiceApplication.setIsRe("YES");
            invoiceApplication.updateById();
        }

    }

    public IPage<StockPositionStock> listStock(String name, String stockName, Integer pageNum, Integer pageSize, String customerId) {
        return reservedMapper.listStock(new Page(pageNum,pageSize),name,stockName,customerId);
    }

    public void improtData(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();

        ExcelReader reader = ExcelUtil.getReader(inputStream);
        reader.addHeaderAlias("经销商编码", "customerNumber");
        reader.addHeaderAlias("*物料编码", "materialCode");
        reader.addHeaderAlias("预留数量", "reservedNum");
        reader.addHeaderAlias("预留仓库", "correspondName");
        reader.addHeaderAlias("备注", "reservedRemark");

        List<ReservedExport> reservedExports = reader.readAll(ReservedExport.class);

        AdminUserCom adminUser = commonLogic.getAdminUser();

        if (adminUser.getIsCustomer())
            throw new RemoteServiceException("经销商不可操作预留单");

        ReservedOrder reservedOrder = new ReservedOrder();
        reservedOrder.setOrderTime(new Date());
        reservedOrderService.save(reservedOrder);

        List<ReservedOrderItem> reservedOrderItems = new ArrayList<>();
        reservedExports.stream().forEach(item ->{
            ReservedOrderItem reservedOrderItem = new ReservedOrderItem();
            reservedOrderItem.setReservedId(reservedOrder.getId());
            reservedOrderItem.setReservedNum(item.getReservedNum());
            reservedOrderItem.setOldNum(item.getReservedNum());
            reservedOrderItem.setReservedRemark(item.getReservedRemark());
            KingDeeMaterial one = kingDeeMaterialService.lambdaQuery()
                    .eq(KingDeeMaterial::getNumber, item.getMaterialCode()).or()
                    .eq(KingDeeMaterial::getOldNumber, item.getMaterialCode()).one();
            if (one == null)
                throw new RemoteServiceException(item.getMaterialCode()+"该物料编码无法找到物料");
            reservedOrderItem.setMaterialId(one.getId());
            reservedOrderItem.setMaterialCode(one.getNumber());
            reservedOrderItem.setMaterialOldNumber(one.getOldNumber());
            reservedOrderItem.setMaterialName(one.getName());
            reservedOrderItem.setK3CategoryName(one.getCategoryName());
            reservedOrderItem.setK3CategoryId(one.getCategoryId());
            reservedOrderItem.setSpecification(one.getSpecification());
            reservedOrderItem.setUnit(one.getBaseUnitId());
            reservedOrderItem.setStatus(1);
            reservedOrderItem.setOrderTime(new Date());
            KingDeeCustomer one1 = kingDeeCustomerService.lambdaQuery()
                    .eq(KingDeeCustomer::getNumber, item.getCustomerNumber()).one();
            if (one1 == null)
                throw new RemoteServiceException(item.getCustomerNumber()+"该经销商编码无法找到经销商");
            reservedOrderItem.setCustomerId(one1.getId());
            reservedOrderItem.setCustomerNumber(one1.getNumber());
            reservedOrderItem.setCustomerName(one1.getName());
            reservedOrderItem.setReservedStatus(2);
            StockCorrespond one2 = stockCorrespondService.lambdaQuery().eq(StockCorrespond::getName, item.getCorrespondName()).one();
            if (one2 == null)
                throw new RemoteServiceException(item.getCorrespondName()+"该仓库名称无法找到对应仓库");
            reservedOrderItem.setCorrespondName(one2.getName());
            reservedOrderItem.setCorrespondId(one2.getId());
            reservedOrderItems.add(reservedOrderItem);
        });

        reservedOrderItemService.saveBatch(reservedOrderItems);
    }

    public IPage<ReservedBeanVO> listV2(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String customerId = adminUser.getIsCustomer() ? adminUser.getCustomerId() : "";

        zfireParamBean = FieldUtils.supplyParam(zfireParamBean);

        Integer integer = reservedMapper.listCountV2(zfireParamBean,customerId);
        IPage<ReservedBeanVO> reservedBeanVOIPage = reservedMapper.listV2(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize(),integer,false),
                zfireParamBean
                , customerId);

        return reservedBeanVOIPage;
    }

    public void closeList(List<String> itemId, HttpServletRequest request) {
        for (String s : itemId) {
            AdminUserCom adminUser = commonLogic.getAdminUser();
            if (adminUser.getIsCustomer())
                throw new RemoteServiceException("经销商不可操作预留单");
            ReservedOrderItem byId = reservedOrderItemService.getById(s);
            byId.setStatus(0);
            byId.setClosureBy(adminUser.getNickName());
            byId.setClosureTime(new Date());
            reservedOrderItemService.removeById(s);

            //减少预留单数量经销商
            stockCommonLogic.reduceStockCustomer(byId.getMaterialId(), byId.getCustomerId(), byId.getReservedNum());
        }

    }
}
