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

import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
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.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zfire.mall.manager.bean.admin.AdminUserCom;
import com.zfire.mall.manager.bean.front.*;
import com.zfire.mall.manager.bean.reserved.ReservedExport;
import com.zfire.mall.manager.commonmapper.front.CustomerFrontMapper;
import com.zfire.mall.manager.constant.Constant;
import com.zfire.mall.manager.enums.ExamineStatusEnum;
import com.zfire.mall.manager.exception.RemoteServiceException;
import com.zfire.mall.manager.logic.common.CommonLogic;
import com.zfire.mall.manager.plus.entity.*;
import com.zfire.mall.manager.plus.service.*;
import com.zfire.mall.manager.zfire.bean.ZfireParamBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author changelin
 */
@Service
@Slf4j
public class CustomerFrontLogic {


    @Autowired
    CustomerFrontMapper customerFrontMapper;

    @Autowired
    CommonLogic commonLogic;

    @Autowired
    CustomerStockOrderItemService customerStockOrderItemService;

    @Autowired
    CustomerStockOrderService customerStockOrderService;


    @Autowired
    CustomerStockService customerStockService;

    @Autowired
    CustomerStockAccService customerStockAccService;

    @Autowired
    KingDeeCustomerService kingDeeCustomerService;

    @Autowired
    KingDeeMaterialService kingDeeMaterialService;


    @Autowired
    PickManagerPushService pickManagerPushService;

    @Autowired
    CustomerOrderService customerOrderService;

    @Autowired
    CustomerOrderRefundService customerOrderRefundService;

    @Autowired
    OrderTrackService orderTrackService;


    public IPage<CustomerStockBean> stockList(Page page, ZfireParamBean zfireParam) {

        AdminUserCom adminUser = commonLogic.getAdminUser();
        List<String> customers=new ArrayList<>();
        if (adminUser.getIsCustomer()) {
            KingDeeCustomer kingDeeCustomer = kingDeeCustomerService.getById(adminUser.getCustomerId());
            customers.add(kingDeeCustomer.getNumber());
            if (kingDeeCustomer.getJiaxianType().equals("KING")){
                List<KingDeeCustomer> list = kingDeeCustomerService.lambdaQuery().eq(KingDeeCustomer::getHigherPrantNumber, adminUser.getCustomerNumber()).list();
                if (CollectionUtils.isNotEmpty(list)){
                    list.stream().forEach(item -> customers.add(item.getNumber()));
                }
            }
        }
        IPage<CustomerStockBean> customerStockBeanIPage = customerFrontMapper.stockList(page, zfireParam,customers);
        return customerStockBeanIPage;
    }

    public IPage<CustomerStockOrderBean> listCustomerAcc(Page page, ZfireParamBean zfireParam) {

        AdminUserCom adminUser = commonLogic.getAdminUser();
        String customerId = adminUser.getIsCustomer() ? adminUser.getCustomerId() : "";
        IPage<CustomerStockOrderBean> customerStockBeanIPage = customerFrontMapper.listCustomerAcc(page, zfireParam, customerId);
        return customerStockBeanIPage;
    }


    @Transactional(rollbackFor = Exception.class)
    public void add(CustomerStockInsert customerStockInsert) {
        KingDeeCustomer kingDeeCustomer = kingDeeCustomerService.lambdaQuery()
                .eq(KingDeeCustomer::getNumber, customerStockInsert.getCustomerNumber()).last("limit 1").one();
        customerStockInsert.setChangeTime(new Date());
        customerStockInsert.setCustomerId(kingDeeCustomer.getId());
        customerStockInsert.setExamineStatus(ExamineStatusEnum.WAIT.toString());
        customerStockInsert.insert();
        for (CustomerStockOrderItem order : customerStockInsert.getOrders()) {
            if (order.getStockChangeQty() == null || order.getStockChangeQty().equals(0))
                throw new RemoteServiceException("数量不能为0");

            CustomerStock customerStock = customerStockService.lambdaQuery()
                    .eq(CustomerStock::getCustomerNumber, customerStockInsert.getCustomerNumber())
                    .eq(CustomerStock::getMaterialCode, order.getMaterialCode())
                  //  .eq(CustomerStock::getStockType, order.getStockType())
                    .last("limit 1").one();
      /*      if (order.getDirectFlag().equals(false) && Convert.toInt(customerStock.getStockQty()) < Convert.toInt(order.getStockChangeQty())) {
                throw new RemoteServiceException("数量大于可调整数量");
            }*/
            order.setOrderId(customerStockInsert.getId());
            order.setMaterialId(customerStock.getMaterialId());
            order.setCustomerStockId(customerStock.getId());
            // stockAcc(order.getDirectFlag(),Convert.toInt(order.getStockChangeQty()),customerStockInsert.getId(),"库存调整单",order.getStockType(),customerStock.getMaterialId(),customerStock.getCustomerId(),order.getNotes());

           // order.setStockCurQty(customerStock.getStockQty());

           // order.setStockCloseQty(customerStock.getStockQty());

            order.setChangeTime(customerStockInsert.getChangeTime());
            order.setId(null);

       /*     customerStock.setStockQty(order.getStockCloseQty());
            customerStock.updateById();*/
        }
        customerStockOrderItemService.saveBatch(customerStockInsert.getOrders());
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(CustomerStockInsert customerStockInsert) {
        customerStockInsert.updateById();
        List<CustomerStockOrderItem> list = customerStockOrderItemService.lambdaQuery().eq(CustomerStockOrderItem::getOrderId, customerStockInsert.getId()).list();
/*        for (CustomerStockOrderItem customerStockOrderItem : list) {

            CustomerStock customerStock = customerStockService.lambdaQuery()
                    .eq(CustomerStock::getCustomerNumber, customerStockInsert.getCustomerNumber())
                    .eq(CustomerStock::getMaterialCode, customerStockOrderItem.getMaterialCode())
                    .eq(CustomerStock::getStockType, customerStockOrderItem.getStockType())
                    .last("limit 1").one();

            if (customerStockOrderItem.getDirectFlag().equals(false)) {
                customerStock.setStockQty(customerStock.getStockQty().add(Convert.toBigDecimal(customerStockOrderItem.getStockChangeQty())));
                customerStockOrderItem.setDirectFlag(true);
            }else {
                customerStockOrderItem.setDirectFlag(false);
                customerStock.setStockQty(customerStock.getStockQty().subtract(Convert.toBigDecimal(customerStockOrderItem.getStockChangeQty())));
            }

          *//*  stockAcc(customerStockOrderItem.getDirectFlag(),Convert.toInt(customerStockOrderItem.getStockChangeQty()),
                    customerStockInsert.getId(),"库存调整单-返回修改前",customerStockOrderItem.getStockType(),customerStock.getMaterialId(),customerStock.getCustomerId(),customerStockOrderItem.getNotes());
  *//*      }*/
        customerStockOrderItemService.lambdaUpdate().eq(CustomerStockOrderItem::getOrderId, customerStockInsert.getId()).remove();
        for (CustomerStockOrderItem order : customerStockInsert.getOrders()) {

            if (order.getStockChangeQty() == null || order.getStockChangeQty().equals(0))
                throw new RemoteServiceException("数量不能为0");

            CustomerStock customerStock = customerStockService.lambdaQuery()
                    .eq(CustomerStock::getCustomerNumber, customerStockInsert.getCustomerNumber())
                    .eq(CustomerStock::getMaterialCode, order.getMaterialCode())
                //    .eq(CustomerStock::getStockType, order.getStockType())
                    .last("limit 1").one();
   /*         if (order.getDirectFlag().equals(false) && Convert.toInt(customerStock.getStockQty()) < Convert.toInt(order.getStockChangeQty())) {
                throw new RemoteServiceException("数量大于可调整数量");
            }*/

            // stockAcc(order.getDirectFlag(),Convert.toInt(order.getStockChangeQty()),customerStockInsert.getId(),"库存调整单-扣除修改后的库存",order.getStockType(),customerStock.getMaterialId(),customerStock.getCustomerId(),order.getNotes());

      /*      order.setStockCurQty(customerStock.getStockQty());
            order.setStockCloseQty(customerStock.getStockQty());*/
            order.setChangeTime(customerStockInsert.getChangeTime());
            order.setId(null);
            order.setOrderId(customerStockInsert.getId());
           /* customerStock.setStockQty(order.getStockCloseQty());
            customerStock.updateById();*/
        }

        customerStockOrderItemService.saveBatch(customerStockInsert.getOrders());
    }

    @Transactional(rollbackFor = Exception.class)
    public void approvalCustomerStockOrder(CustomerStockInsert customerStockInsert) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        CustomerStockOrder customerStockOrder = customerStockOrderService.getById(customerStockInsert.getId());
        if (!customerStockOrder.getExamineStatus().equals("WAIT")) {
            throw new RemoteServiceException("不为待审核状态");
        }

        customerStockOrder.setApprovalName(adminUser.getNickName());
        customerStockOrder.setApprovalTime(new Date());
        customerStockOrder.setExamineStatus(customerStockInsert.getExamineStatus());
        customerStockOrder.updateById();
        if (customerStockInsert.getExamineStatus().equals("WAIT")) {
            return;
        }
        if (customerStockInsert.getExamineStatus().equals("FAIL")) {
            return;
        }

        List<CustomerStockOrderItem> list = customerStockOrderItemService.lambdaQuery().eq(CustomerStockOrderItem::getOrderId, customerStockInsert.getId()).list();

        for (CustomerStockOrderItem customerStockOrderItem : list) {
            CustomerStock customerStock = customerStockService.lambdaQuery()
                    .eq(CustomerStock::getCustomerNumber, customerStockInsert.getCustomerNumber())
                    .eq(CustomerStock::getMaterialCode, customerStockOrderItem.getMaterialCode())
                   // .eq(CustomerStock::getStockType, customerStockOrderItem.getStockType())
                    .last("limit 1").one();
     /*       if (customerStockOrderItem.getDirectFlag().equals(false) && Convert.toInt(customerStock.getStockQty()) < Convert.toInt(customerStockOrderItem.getStockChangeQty())) {
                throw new RemoteServiceException("数量大于可调整数量");
            }*/

            stockAcc(customerStockOrderItem.getDirectFlag(), Convert.toInt(customerStockOrderItem.getStockChangeQty()), customerStockInsert.getId(),
                    "库存调整单-扣除修改后的库存", customerStockOrderItem.getStockType(), customerStock.getMaterialId(), customerStock.getCustomerId(), customerStockOrderItem.getNotes());

    /*        customerStockOrderItem.setStockCurQty(customerStock.getStockQty());
            if (customerStockOrderItem.getDirectFlag().equals(false)) {
                customerStockOrderItem.setStockCloseQty(customerStock.getStockQty().subtract(Convert.toBigDecimal(customerStockOrderItem.getStockChangeQty())));
            } else {
                customerStockOrderItem.setStockCloseQty(customerStock.getStockQty().add(Convert.toBigDecimal(customerStockOrderItem.getStockChangeQty())));
            }*/
            customerStockOrderItem.setChangeTime(customerStockInsert.getChangeTime());
            customerStockOrderItem.setOrderId(customerStockInsert.getId());
           // customerStock.setStockQty(customerStockOrderItem.getStockCloseQty());
            customerStock.updateById();
            customerStockOrderItem.updateById();
        }

    }

    public CustomerStockDetail detail(String id) {
        CustomerStockOrder customerStockOrderServiceById = customerStockOrderService.getById(id);

        List<CustomerStockOrderItem> list = customerStockOrderItemService.lambdaQuery().eq(CustomerStockOrderItem::getOrderId, id).list();

        CustomerStockDetail customerStockDetail = BeanUtil.toBean(customerStockOrderServiceById, CustomerStockDetail.class);
        customerStockDetail.setOrders(list);
        return customerStockDetail;
    }

    public IPage<CustomerStockAccBean> listStockAcc(Page page, ZfireParamBean zfireParam) {

        AdminUserCom adminUser = commonLogic.getAdminUser();
        String customerId = adminUser.getIsCustomer() ? adminUser.getCustomerId() : "";
        IPage<CustomerStockAccBean> customerStockBeanIPage = customerFrontMapper.listStockAcc(page, zfireParam, customerId);
        return customerStockBeanIPage;
    }

    public void deleteCustomerStockOrder(CustomerStockInsert customerStockInsert) {
        CustomerStockOrder customerStockOrder = customerStockOrderService.getById(customerStockInsert.getId());
        if (!customerStockOrder.getExamineStatus().equals("WAIT"))
            throw new RemoteServiceException("不为待审，不能删除");
        List<CustomerStockOrderItem> list = customerStockOrderItemService.lambdaQuery().eq(CustomerStockOrderItem::getOrderId, customerStockInsert.getId()).list();
/*        for (CustomerStockOrderItem customerStockOrderItem : list) {

            CustomerStock customerStock = customerStockService.lambdaQuery()
                    .eq(CustomerStock::getCustomerNumber, customerStockOrder.getCustomerNumber())
                    .eq(CustomerStock::getMaterialCode, customerStockOrderItem.getMaterialCode())
                    .eq(CustomerStock::getStockType, customerStockOrderItem.getStockType())
                    .last("limit 1").one();
            stockAcc(!customerStockOrderItem.getDirectFlag(),Convert.toInt(customerStockOrderItem.getStockChangeQty()),customerStockInsert.getId(),"库存调整单删除",
                    customerStockOrderItem.getStockType(),customerStock.getMaterialId(),customerStock.getCustomerId(),customerStockOrderItem.getNotes());

            customerStock.setStockQty(customerStockOrderItem.getStockChangeQty().add(customerStock.getStockQty()));
            customerStock.updateById();
        }*/
        customerStockOrderItemService.lambdaUpdate().eq(CustomerStockOrderItem::getOrderId, customerStockInsert.getId()).remove();
        customerStockInsert.deleteById();
    }

    /**
     * 记录库存数量
     * <p>
     * directFlag  true 增加 false 减少  qty 数量  ref 订单   refType 订单类型 stockType 1 前置仓 2商家仓 materialId 物料id  customerId 经销商id  notes 备注
     */

    public void stockAcc(Boolean directFlag, Integer qty, String ref, String refType, Integer stockType, String materialId, String customerId, String notes) {
        KingDeeCustomer kingDeeCustomer = kingDeeCustomerService.getById(customerId);
        KingDeeMaterial kingDeeMaterial = kingDeeMaterialService.getById(materialId);
        CustomerStock customerStock = customerStockService.lambdaQuery()
                .eq(CustomerStock::getCustomerId, customerId)
                .eq(CustomerStock::getMaterialCode, kingDeeMaterial.getNumber())
                .last("limit 1").one();

        CustomerStockAcc customerStockAcc = new CustomerStockAcc();
        customerStockAcc.setChangeTime(new Date());
        customerStockAcc.setDirectFlag(directFlag);
        customerStockAcc.setStockChangeQty(Convert.toBigDecimal(qty));
        if (stockType.equals(1) && (customerStock == null || customerStock.getFrontStockNum() == null))
            customerStockAcc.setStockCurQty(new BigDecimal(0));
        else if (stockType.equals(1))
            customerStockAcc.setStockCurQty(customerStock.getFrontStockNum());

        if (stockType.equals(2) && (customerStock == null || customerStock.getCustomerStockNum() == null))
            customerStockAcc.setStockCurQty(new BigDecimal(0));
        else if (stockType.equals(2))
            customerStockAcc.setStockCurQty(customerStock.getCustomerStockNum());

        if (customerStockAcc.getDirectFlag().equals(false)) {
            customerStockAcc.setStockCloseQty(customerStockAcc.getStockCurQty().subtract(Convert.toBigDecimal(customerStockAcc.getStockChangeQty())));
        } else {
            customerStockAcc.setStockCloseQty(customerStockAcc.getStockCurQty().add(Convert.toBigDecimal(customerStockAcc.getStockChangeQty())));
        }
        if (customerStockAcc.getStockCloseQty().compareTo(BigDecimal.ZERO) == -1)
            throw new RemoteServiceException("库存数量小于0");
        customerStockAcc.setRef(ref);
        customerStockAcc.setRefType(refType);
        customerStockAcc.setNotes(notes);
        customerStockAcc.setStockType(stockType);
        customerStockAcc.setMaterialId(kingDeeMaterial.getId());
        customerStockAcc.setMaterialCode(kingDeeMaterial.getNumber());
        customerStockAcc.setMaterialName(kingDeeMaterial.getName());
        customerStockAcc.setMaterialOldNumber(kingDeeMaterial.getOldNumber());
        customerStockAcc.setSpecification(kingDeeMaterial.getSpecification());
        customerStockAcc.setCustomerId(kingDeeCustomer.getId());
        customerStockAcc.setCustomerName(kingDeeCustomer.getName());
        customerStockAcc.setCustomerNumber(kingDeeCustomer.getNumber());
        customerStockAcc.setCategoryId(kingDeeMaterial.getCategoryId());
        customerStockAcc.setCategoryName(kingDeeMaterial.getCategoryName());
        customerStockAcc.setCategoryNumber(kingDeeMaterial.getCategoryNumber());
        customerStockAcc.insert();
    }


    @Transactional(rollbackFor = Exception.class)
    public void syncStatus(SyncStatusBean syncStatusBean) {
        try {

            log.info("嘉贤同步成功订单内容:" + syncStatusBean.toString());
            if (syncStatusBean.getResourcesEncrypted().equals(Constant.SUPPLY_ORDER)) {
                syncStatusBean.getSyncStatusOrderBeans().stream().forEach(item -> {
                    pickManagerPushService.lambdaUpdate().eq(PickManagerPush::getInvoiceId, item.getOrderId()).set(PickManagerPush::getSyncStatus, item.getStatus()).update();
                });
            }

            if (syncStatusBean.getResourcesEncrypted().equals(Constant.SUPPLY_CUSTOMER_ORDER)) {
                syncStatusBean.getSyncStatusOrderBeans().stream().forEach(item -> {
                    customerOrderService.lambdaUpdate().eq(CustomerOrder::getId, item.getOrderId()).set(CustomerOrder::getSyncStatus, item.getStatus()).update();
                });
            }

            if (syncStatusBean.getResourcesEncrypted().equals(Constant.SUPPLY_CUSTOMER_ORDER_REFUND)) {
                syncStatusBean.getSyncStatusOrderBeans().stream().forEach(item -> {
                    customerOrderRefundService.lambdaUpdate().eq(CustomerOrderRefund::getId, item.getOrderId()).set(CustomerOrderRefund::getSyncStatus, item.getStatus()).update();
                });
            }

            if (syncStatusBean.getResourcesEncrypted().equals(Constant.SUPPLY_CUSTOMER_STOCK_ACC)) {
                syncStatusBean.getSyncStatusOrderBeans().stream().forEach(item -> {
                    customerStockOrderService.lambdaUpdate().eq(CustomerStockOrder::getId, item.getOrderId()).set(CustomerStockOrder::getSyncStatus, item.getStatus()).update();
                });
            }

            if (syncStatusBean.getResourcesEncrypted().equals(Constant.SUPPLY_CUSTOMER_CUSTOMER_SYS)) {
                syncStatusBean.getSyncStatusOrderBeans().stream().forEach(item -> {
                    kingDeeCustomerService.lambdaUpdate().eq(KingDeeCustomer::getNumber, item.getOrderId()).set(KingDeeCustomer::getSyncStatus, item.getStatus()).update();
                });
            }
        } catch (Exception e) {
            throw new RemoteServiceException("参数有误");
        }

    }


    @Transactional(rollbackFor = Exception.class)
    public void importData(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();

        ExcelReader reader = ExcelUtil.getReader(inputStream);
        reader.addHeaderAlias("*商家编号", "customerNumber");
        reader.addHeaderAlias("*产品编码", "materialCode");
        reader.addHeaderAlias("*数量", "qty");
        reader.addHeaderAlias("*发生方向", "directFlag");
        reader.addHeaderAlias("表体备注", "remark");

        List<CustomerOrderImport> customerOrderImports = reader.readAll(CustomerOrderImport.class);

        for (CustomerOrderImport customerOrderImport : customerOrderImports) {
            KingDeeMaterial kingDeeMaterial = kingDeeMaterialService.lambdaQuery().eq(KingDeeMaterial::getOldNumber, customerOrderImport.getMaterialCode())
                    .last("limit 1").one();
            KingDeeCustomer kingDeeCustomer = kingDeeCustomerService.lambdaQuery().eq(KingDeeCustomer::getNumber, customerOrderImport.getCustomerNumber()).last("limit 1").one();
            if (kingDeeCustomer == null || kingDeeMaterial == null)
                throw new RemoteServiceException("商家编号或物料编号错误：" + customerOrderImport.getCustomerNumber() + "," + customerOrderImport.getMaterialCode());


            CustomerStock customerStock = customerStockService.lambdaQuery().eq(CustomerStock::getCustomerId, kingDeeCustomer.getId())
                    .eq(CustomerStock::getMaterialId, kingDeeMaterial.getId())
                    .last("limit 1").one();

            if (customerStock == null) {
                if (customerOrderImport.getDirectFlag().equals("减少"))
                    throw new RemoteServiceException("商家无库存减少库存失败：" + customerOrderImport.getCustomerNumber() + "," + customerOrderImport.getDirectFlag());



                CustomerStock customerStockInsert = new CustomerStock();
               // customerStockInsert.setStockType(kingDeeCustomer.getIsFront() ? 1 : 2);
                customerStockInsert.setCustomerNumber(kingDeeCustomer.getNumber());
                customerStockInsert.setCustomerName(kingDeeCustomer.getName());
                customerStockInsert.setCustomerId(kingDeeCustomer.getId());
                customerStockInsert.setMaterialOldNumber(kingDeeMaterial.getOldNumber());
                customerStockInsert.setMaterialName(kingDeeMaterial.getName());
                customerStockInsert.setMaterialCode(kingDeeMaterial.getNumber());
                customerStockInsert.setMaterialId(kingDeeMaterial.getId());
                customerStockInsert.setSpecification(kingDeeMaterial.getSpecification());
              //  customerStockInsert.setStockQty(Convert.toBigDecimal(customerOrderImport.getQty()));
                customerStockInsert.setCategoryId(kingDeeMaterial.getCategoryId());
                customerStockInsert.setCategoryNumber(kingDeeMaterial.getCategoryNumber());
                customerStockInsert.setCategoryName(kingDeeMaterial.getCategoryName());

                stockAcc(true, Convert.toInt(customerOrderImport.getQty()), kingDeeCustomer.getNumber() + "(" + kingDeeMaterial.getNumber() + ")",
                        "导入商家库存", kingDeeCustomer.getIsFront() ? 1 : 2, kingDeeMaterial.getId(), kingDeeCustomer.getId(), customerOrderImport.getRemark());

                customerStockInsert.insert();


            } else {
           /*     if (customerOrderImport.getDirectFlag().equals("减少")) {
                    customerStock.setStockQty(customerStock.getStockQty().subtract(Convert.toBigDecimal(customerOrderImport.getQty())));
                } else {
                    customerStock.setStockQty(customerStock.getStockQty().add(Convert.toBigDecimal(customerOrderImport.getQty())));
                }
                if (customerStock.getStockQty().compareTo(BigDecimal.ZERO) < 0) {
                    throw new RemoteServiceException("商家无库存减少库存失败：" + customerOrderImport.getCustomerNumber() + "," + customerOrderImport.getDirectFlag());
                }*/
                stockAcc(customerOrderImport.getDirectFlag().equals("减少") ? false : true, Convert.toInt(customerOrderImport.getQty()), kingDeeCustomer.getNumber() + "(" + kingDeeMaterial.getNumber() + ")",
                        "导入商家库存", kingDeeCustomer.getIsFront() ? 1 : 2, kingDeeMaterial.getId(), kingDeeCustomer.getId(), customerOrderImport.getRemark());

                customerStock.updateById();


            }
        }

    }

    @Transactional(rollbackFor = Exception.class)
    public void syncOrderTrack(SyncOrderTrack syncStatusBean) {
        List<OrderTrack> orderTracks = BeanUtil.copyToList(syncStatusBean.getSyncOrderTrackBeans(), OrderTrack.class);
        orderTrackService.saveOrUpdateBatch(orderTracks);
    }

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

        ExcelReader reader = ExcelUtil.getReader(inputStream);
        reader.addHeaderAlias("经销商编号", "customerNumber");
        reader.addHeaderAlias("经销商名称", "customerName");
        reader.addHeaderAlias("产品编号", "materialCode");
        reader.addHeaderAlias("前置仓库存数量", "frontStockNum");
        reader.addHeaderAlias("自有仓可用数量", "customerStockNum");

        List<CustomerStock> customerOrderImports = reader.readAll(CustomerStock.class);

        for (CustomerStock customerOrderImport : customerOrderImports) {
            CustomerStock customerStock = customerStockService.lambdaQuery().eq(CustomerStock::getCustomerNumber, customerOrderImport.getCustomerNumber())
                    .eq(CustomerStock::getMaterialCode, customerOrderImport.getMaterialCode()).last("limit 1").one();
            KingDeeCustomer king = kingDeeCustomerService.lambdaQuery().eq(KingDeeCustomer::getNumber, customerOrderImport.getCustomerNumber()).last("limit 1").one();
            KingDeeMaterial kingDeeMaterial = kingDeeMaterialService.lambdaQuery().eq(KingDeeMaterial::getNumber, customerOrderImport.getMaterialCode()).last("limit 1").one();
            if (customerStock != null){
                customerOrderImport.setId(customerStock.getId());
                continue;
            }
            customerOrderImport.setCustomerId(king.getId());
            customerOrderImport.setCustomerName(king.getName());
            customerOrderImport.setMaterialId(kingDeeMaterial.getId());
            customerOrderImport.setMaterialName(kingDeeMaterial.getName());
            customerOrderImport.setMaterialOldNumber(kingDeeMaterial.getOldNumber());
            customerOrderImport.setSpecification(kingDeeMaterial.getSpecification());
            customerOrderImport.setCategoryId(kingDeeMaterial.getCategoryId());
            customerOrderImport.setCategoryName(kingDeeMaterial.getCategoryName());
            customerOrderImport.setCategoryNumber(kingDeeMaterial.getCategoryNumber());
        }

        customerStockService.saveOrUpdateBatch(customerOrderImports);
    }

    public void kunCunTiaoImportData(MultipartFile file) throws IOException {

        InputStream inputStream = file.getInputStream();

        ExcelReader reader = ExcelUtil.getReader(inputStream);
        reader.addHeaderAlias("经销商编号", "customerNumber");
        reader.addHeaderAlias("经销商名称", "customerName");
        reader.addHeaderAlias("产品编号", "materialCode");
        reader.addHeaderAlias("前置仓库存数量", "frontStockNum");
        reader.addHeaderAlias("自有仓可用数量", "customerStockNum");

        List<CustomerStock> customerOrderImports = reader.readAll(CustomerStock.class);

        for (CustomerStock customerOrderImport : customerOrderImports) {
            CustomerStock customerStock = customerStockService.lambdaQuery().eq(CustomerStock::getCustomerNumber, customerOrderImport.getCustomerNumber())
                    .eq(CustomerStock::getMaterialCode, customerOrderImport.getMaterialCode()).last("limit 1").one();
            KingDeeCustomer king = kingDeeCustomerService.lambdaQuery().eq(KingDeeCustomer::getNumber, customerOrderImport.getCustomerNumber()).last("limit 1").one();
            KingDeeMaterial kingDeeMaterial = kingDeeMaterialService.lambdaQuery().eq(KingDeeMaterial::getNumber, customerOrderImport.getMaterialCode()).last("limit 1").one();
            if (customerStock != null){
                customerOrderImport.setId(customerStock.getId());
                customerOrderImport.setFrontStockNum(customerStock.getFrontStockNum().add(customerOrderImport.getFrontStockNum()));
                customerOrderImport.setCustomerStockNum(customerStock.getCustomerStockNum().add(customerOrderImport.getCustomerStockNum()));
                continue;
            }
            customerOrderImport.setCustomerId(king.getId());
            customerOrderImport.setCustomerName(king.getName());
            customerOrderImport.setMaterialId(kingDeeMaterial.getId());
            customerOrderImport.setMaterialName(kingDeeMaterial.getName());
            customerOrderImport.setMaterialOldNumber(kingDeeMaterial.getOldNumber());
            customerOrderImport.setSpecification(kingDeeMaterial.getSpecification());
            customerOrderImport.setCategoryId(kingDeeMaterial.getCategoryId());
            customerOrderImport.setCategoryName(kingDeeMaterial.getCategoryName());
            customerOrderImport.setCategoryNumber(kingDeeMaterial.getCategoryNumber());
        }

        customerStockService.saveOrUpdateBatch(customerOrderImports);
    }
}
