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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.taobao.api.ApiException;
import com.zfire.mall.manager.bean.admin.AdminUserCom;
import com.zfire.mall.manager.bean.front.*;
import com.zfire.mall.manager.commonmapper.front.CustomerFrontOrderMapper;
import com.zfire.mall.manager.constant.Constant;
import com.zfire.mall.manager.enums.CustomerStockEnum;
import com.zfire.mall.manager.enums.JiaXianOrderTypeEnum;
import com.zfire.mall.manager.exception.RemoteServiceException;
import com.zfire.mall.manager.logic.common.CommonLogic;
import com.zfire.mall.manager.logic.pick.PickLogic;
import com.zfire.mall.manager.plus.entity.*;
import com.zfire.mall.manager.plus.service.*;
import com.zfire.mall.manager.schedule.GongdanLogic;
import com.zfire.mall.manager.utils.JiaXianUtils;
import com.zfire.mall.manager.utils.RedisUtil;
import com.zfire.mall.manager.zfire.bean.ZfireParamBean;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

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


    @Autowired
    CustomerFrontOrderMapper customerFrontOrderMapper;

    @Autowired
    CommonLogic commonLogic;

    @Autowired
    CustomerStockOrderItemService customerStockOrderItemService;

    @Autowired
    CustomerStockOrderService customerStockOrderService;

    @Autowired
    CustomerOrderService customerOrderService;

    @Autowired
    CustomerOrderItemService customerOrderItemService;

    @Autowired
    CustomerOrderRefundService customerOrderRefundService;

    @Autowired
    CustomerOrderRefundItemService customerOrderRefundItemService;

    @Autowired
    KingDeeMaterialService kingDeeMaterialService;

    @Autowired
    KingDeeCustomerService kingDeeCustomerService;

    @Autowired
    CustomerStockService customerStockService;

    @Autowired
    CustomerFrontLogic customerFrontLogic;

    @Resource
    RedisUtil redisUtil;

    @Resource
    PickLogic pickLogic;

    @Autowired
    JiaXianUtils jiaXianUtils;

    @Autowired
    GongdanLogic gongdanLogic;


    public IPage<CustomerOrderBean> list(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<CustomerOrderBean> customerStockBeanIPage = customerFrontOrderMapper.list(page, zfireParam, customers);
        return customerStockBeanIPage;
    }

    public IPage<CustomerRefundOrderBean> listRefund(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<CustomerRefundOrderBean> customerStockBeanIPage = customerFrontOrderMapper.listRefund(page, zfireParam, customers);
        return customerStockBeanIPage;
    }

    public CustomerOrderDetail detail(String id) {
        CustomerOrder customerOrder = customerOrderService.getById(id);

        List<CustomerOrderItem> list = customerOrderItemService.lambdaQuery().eq(CustomerOrderItem::getOrderId, id).list();

        CustomerOrderDetail customerOrderDetail = BeanUtil.toBean(customerOrder, CustomerOrderDetail.class);
        customerOrderDetail.setOrders(list);
        return customerOrderDetail;
    }

    public CustomerOrderRefundDetail detailRefund(String id) {
        CustomerOrderRefund customerOrder = customerOrderRefundService.getById(id);

        List<CustomerOrderRefundItem> list = customerOrderRefundItemService.lambdaQuery().eq(CustomerOrderRefundItem::getOrderId, id).list();

        CustomerOrderRefundDetail customerOrderDetail = BeanUtil.toBean(customerOrder, CustomerOrderRefundDetail.class);
        customerOrderDetail.setOrders(list);
        return customerOrderDetail;
    }

    @Transactional(rollbackFor = Exception.class)
    public String add(CustomerOrderDetail customerOrderDetail) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        KingDeeCustomer kingDeeCustomer = kingDeeCustomerService.lambdaQuery().eq(KingDeeCustomer::getNumber, customerOrderDetail.getCustomerNumber()).last("limit 1").one();
        customerOrderDetail.setCustomerId(kingDeeCustomer.getId());
        customerOrderDetail.setOrderTime(new Date());
        customerOrderDetail.setStatus(customerOrderDetail.getStatus() == null ? 1 : customerOrderDetail.getStatus());
        String orderId = generateOrder();
        customerOrderDetail.setId("XS" + orderId);
        customerOrderDetail.insert();
        Map<String, String> map = new HashMap<>();
        for (CustomerOrderItem order : customerOrderDetail.getOrders()) {
            KingDeeMaterial kingDeeMaterial = kingDeeMaterialService.lambdaQuery().eq(KingDeeMaterial::getNumber, order.getMaterialCode()).last("limit 1").one();
            order.setOrderId(customerOrderDetail.getId());
            order.setMaterialId(kingDeeMaterial.getId());
            order.setRefundQty(order.getQty());
            order.setRealQty(order.getQty());
            CustomerStock customerStock = customerStockService.lambdaQuery()
                    .eq(CustomerStock::getCustomerNumber, kingDeeCustomer.getNumber())
                    .eq(CustomerStock::getMaterialCode, order.getMaterialCode())
                    .last("limit 1").one();

            String s = map.get(order.getMaterialCode());
            if (StringUtils.isNotEmpty(s))
                throw new RemoteServiceException("不能重复添加同一机型");

            map.put(order.getMaterialCode(), order.getMaterialName());
            if (Convert.toInt(customerOrderDetail.getStockType().equals(1) ? customerStock.getFrontStockNum() : customerStock.getCustomerStockNum()) < Convert.toInt(order.getQty()) || order.getQty() <= 0) {
                throw new RemoteServiceException("数量大于可调整数量");
            }

            customerFrontLogic.stockAcc(false, Convert.toInt(order.getQty()), customerOrderDetail.getId(), "客户销售订单", customerOrderDetail.getStockType(), customerStock.getMaterialId(), customerStock.getCustomerId(), order.getNotes());

            if (customerOrderDetail.getStockType().equals(1)) {
                customerStock.setFrontStockNum(customerStock.getFrontStockNum().subtract(new BigDecimal(order.getQty())));
                customerStock.setLockFrontStockNum(customerStock.getLockFrontStockNum().add(new BigDecimal(order.getQty())));
            } else {
                customerStock.setCustomerStockNum(customerStock.getCustomerStockNum().subtract(new BigDecimal(order.getQty())));
                customerStock.setLockCustomerStockNum(customerStock.getLockCustomerStockNum().add(new BigDecimal(order.getQty())));
            }
            customerStock.updateById();

        }
        customerOrderItemService.saveBatch(customerOrderDetail.getOrders());
        if (customerOrderDetail.getStockType().equals(CustomerStockEnum.NO.getKey()))
            gongdanLogic.installOrder(customerOrderDetail.getId());
        return customerOrderDetail.getId();
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(CustomerOrderDetail customerOrderDetail) {
        CustomerOrder customerOrder = customerOrderService.getById(customerOrderDetail.getId());
        if (!customerOrder.getStatus().equals(1))
            throw new RemoteServiceException("订单不为提交状态");


        List<CustomerOrderItem> list = customerOrderItemService.lambdaQuery().eq(CustomerOrderItem::getOrderId, customerOrderDetail.getId()).list();

        for (CustomerOrderItem order : list) {
            KingDeeMaterial kingDeeMaterial = kingDeeMaterialService.lambdaQuery().eq(KingDeeMaterial::getNumber, order.getMaterialCode()).last("limit 1").one();
            order.setOrderId(customerOrderDetail.getId());
            order.setMaterialId(kingDeeMaterial.getId());
            CustomerStock customerStock = customerStockService.lambdaQuery()
                    .eq(CustomerStock::getCustomerNumber, customerOrder.getCustomerNumber())
                    .eq(CustomerStock::getMaterialCode, order.getMaterialCode())
                    // .eq(CustomerStock::getStockType, customerOrder.getStockType())
                    .last("limit 1").one();


            customerFrontLogic.stockAcc(true, Convert.toInt(order.getQty()), customerOrderDetail.getId(), "客户销售订单修改-返回修改前得库存", customerOrderDetail.getStockType(), customerStock.getMaterialId(), customerStock.getCustomerId(), order.getNotes());


            if (customerOrderDetail.getStockType().equals(1)) {
                customerStock.setFrontStockNum(customerStock.getFrontStockNum().add(new BigDecimal(order.getQty())));
                customerStock.setLockFrontStockNum(customerStock.getLockFrontStockNum().subtract(new BigDecimal(order.getQty())));
            } else {
                customerStock.setCustomerStockNum(customerStock.getCustomerStockNum().add(new BigDecimal(order.getQty())));
                customerStock.setLockCustomerStockNum(customerStock.getLockCustomerStockNum().subtract(new BigDecimal(order.getQty())));
            }
            customerStock.updateById();

        }


        KingDeeCustomer kingDeeCustomer = kingDeeCustomerService.lambdaQuery().eq(KingDeeCustomer::getNumber, customerOrder.getCustomerNumber()).last("limit 1").one();
        customerOrderDetail.updateById();
        customerOrderItemService.lambdaUpdate().eq(CustomerOrderItem::getOrderId, customerOrderDetail.getId()).remove();
        for (CustomerOrderItem order : customerOrderDetail.getOrders()) {
            KingDeeMaterial kingDeeMaterial = kingDeeMaterialService.lambdaQuery().eq(KingDeeMaterial::getNumber, order.getMaterialCode()).last("limit 1").one();
            order.setOrderId(customerOrderDetail.getId());
            order.setMaterialId(kingDeeMaterial.getId());
            order.setRefundQty(order.getQty());
            order.setRealQty(order.getQty());
            CustomerStock customerStock = customerStockService.lambdaQuery()
                    .eq(CustomerStock::getCustomerNumber, kingDeeCustomer.getNumber())
                    .eq(CustomerStock::getMaterialCode, order.getMaterialCode())
                    // .eq(CustomerStock::getStockType, customerOrderDetail.getStockType())
                    .last("limit 1").one();

            if (Convert.toInt(customerOrderDetail.getStockType().equals(1) ? customerStock.getFrontStockNum() : customerStock.getCustomerStockNum()) < Convert.toInt(order.getQty()) || order.getQty() < 0) {
                throw new RemoteServiceException("数量大于可调整数量");
            }


            customerFrontLogic.stockAcc(false, Convert.toInt(order.getQty()), customerOrderDetail.getId(), "客户销售订单修改-扣除修改后得库存", customerOrderDetail.getStockType(), customerStock.getMaterialId(), customerStock.getCustomerId(), order.getNotes());

            if (customerOrderDetail.getStockType().equals(1)) {
                customerStock.setFrontStockNum(customerStock.getFrontStockNum().subtract(new BigDecimal(order.getQty())));
                customerStock.setLockFrontStockNum(customerStock.getLockFrontStockNum().add(new BigDecimal(order.getQty())));
            } else {
                customerStock.setCustomerStockNum(customerStock.getCustomerStockNum().subtract(new BigDecimal(order.getQty())));
                customerStock.setLockCustomerStockNum(customerStock.getLockCustomerStockNum().add(new BigDecimal(order.getQty())));
            }
            customerStock.updateById();

        }
        customerOrderItemService.saveBatch(customerOrderDetail.getOrders());
    }

    @Transactional(rollbackFor = Exception.class)
    public String addRefund(CustomerOrderRefundDetail customerOrderRefundDetail) {
        KingDeeCustomer kingDeeCustomer = kingDeeCustomerService.lambdaQuery().eq(KingDeeCustomer::getNumber, customerOrderRefundDetail.getCustomerNumber()).last("limit 1").one();
        customerOrderRefundDetail.setCustomerId(kingDeeCustomer.getId());
        customerOrderRefundDetail.setOrderTime(new Date());
        customerOrderRefundDetail.setStatus(1);
        String orderId = generateRefundOrder();
        customerOrderRefundDetail.setId("TH" + orderId);
        customerOrderRefundDetail.insert();
        for (CustomerOrderRefundItem order : customerOrderRefundDetail.getOrders()) {
            CustomerOrderItem customerOrderItem = customerOrderItemService.lambdaQuery().eq(CustomerOrderItem::getMaterialCode, order.getMaterialCode()).eq(CustomerOrderItem::getOrderId, customerOrderRefundDetail.getCustomerOrderNo())
                    .last("limit 1").one();
            if (customerOrderItem == null)
                throw new RemoteServiceException("非同一个订单进行退货");
            customerOrderItem.setRefundQty(customerOrderItem.getRefundQty() - order.getQty());
            if (customerOrderItem.getRefundQty() < 0) {
                throw new RemoteServiceException("大于发货数量");
            }
            customerOrderItem.updateById();


            KingDeeMaterial kingDeeMaterial = kingDeeMaterialService.lambdaQuery().eq(KingDeeMaterial::getNumber, order.getMaterialCode()).last("limit 1").one();
            order.setOrderId(customerOrderRefundDetail.getId());
            order.setOrderId(customerOrderRefundDetail.getId());
            order.setMaterialId(kingDeeMaterial.getId());

        }

        customerOrderRefundItemService.saveBatch(customerOrderRefundDetail.getOrders());
        if (customerOrderRefundDetail.getStockType().equals(2)){
            sendRefund(customerOrderRefundDetail.getId(),2);
        }
        return customerOrderRefundDetail.getId();
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateRefund(CustomerOrderRefundDetail customerOrderRefundDetail) {
        KingDeeCustomer kingDeeCustomer = kingDeeCustomerService.lambdaQuery().eq(KingDeeCustomer::getNumber, customerOrderRefundDetail.getCustomerNumber()).last("limit 1").one();
        customerOrderRefundDetail.updateById();

        List<CustomerOrderRefundItem> list = customerOrderRefundItemService.lambdaQuery().eq(CustomerOrderRefundItem::getOrderId, customerOrderRefundDetail.getId()).list();
        for (CustomerOrderRefundItem order : list) {
            KingDeeMaterial kingDeeMaterial = kingDeeMaterialService.lambdaQuery().eq(KingDeeMaterial::getNumber, order.getMaterialCode()).last("limit 1").one();
            order.setOrderId(customerOrderRefundDetail.getId());
            order.setOrderId(customerOrderRefundDetail.getId());
            order.setMaterialId(kingDeeMaterial.getId());


            CustomerOrderItem customerOrderItem = customerOrderItemService.lambdaQuery().eq(CustomerOrderItem::getMaterialCode, order.getMaterialCode())
                    .eq(CustomerOrderItem::getOrderId, customerOrderRefundDetail.getCustomerOrderNo())
                    .last("limit 1").one();
            customerOrderItem.setRefundQty(customerOrderItem.getRefundQty() + order.getQty());
            customerOrderItem.updateById();

        }

        customerOrderRefundItemService.lambdaUpdate().eq(CustomerOrderRefundItem::getOrderId, customerOrderRefundDetail.getId()).remove();
        for (CustomerOrderRefundItem order : customerOrderRefundDetail.getOrders()) {

            KingDeeMaterial kingDeeMaterial = kingDeeMaterialService.lambdaQuery().eq(KingDeeMaterial::getNumber, order.getMaterialCode()).last("limit 1").one();
            order.setOrderId(customerOrderRefundDetail.getId());
            order.setOrderId(customerOrderRefundDetail.getId());
            order.setMaterialId(kingDeeMaterial.getId());



            CustomerOrderItem customerOrderItem = customerOrderItemService.lambdaQuery().eq(CustomerOrderItem::getMaterialCode, order.getMaterialCode()).eq(CustomerOrderItem::getOrderId, customerOrderRefundDetail.getCustomerOrderNo())
                    .last("limit 1").one();
            customerOrderItem.setRefundQty(customerOrderItem.getRefundQty() - order.getQty());
            if (customerOrderItem.getRefundQty() < 0 ){
                throw new RemoteServiceException("大于发货数量");
            }
            customerOrderItem.updateById();
        }
        customerOrderRefundItemService.saveBatch(customerOrderRefundDetail.getOrders());
    }


    @Transactional(rollbackFor = Exception.class)
    public void send(String id, Integer status) throws Exception {

        CustomerOrder customerOrderOne = customerOrderService.getById(id);
        if (!customerOrderOne.getStatus().equals(1) || customerOrderOne.getStockType().equals(2))
            throw new RemoteServiceException("订单不为嘉贤仓或提交状态，不能通知发货");

        List<CustomerOrderItem> list = customerOrderItemService.lambdaQuery().eq(CustomerOrderItem::getOrderId, id).list();

        for (CustomerOrderItem customerOrderRefundItem : list) {
            CustomerStock customerStock = customerStockService.lambdaQuery()
                    .eq(CustomerStock::getCustomerNumber, customerOrderOne.getCustomerNumber())
                    .eq(CustomerStock::getMaterialCode, customerOrderRefundItem.getMaterialCode())
                    .last("limit 1").one();
            if (customerOrderOne.getStockType().equals(1)) {
                customerStock.setLockFrontStockNum(customerStock.getLockFrontStockNum().subtract(new BigDecimal(customerOrderRefundItem.getQty())));
                if (Convert.toInt(customerStock.getLockFrontStockNum()) < 0)
                    throw new RemoteServiceException("库存数量不够");
            } else {
                customerStock.setLockCustomerStockNum(customerStock.getLockCustomerStockNum().subtract(new BigDecimal(customerOrderRefundItem.getQty())));
                if (Convert.toInt(customerStock.getLockCustomerStockNum()) < 0)
                    throw new RemoteServiceException("库存数量不够");
            }


            customerStock.updateById();

        }


        customerOrderOne.setId(id);
        customerOrderOne.setStatus(status);

        if (!customerOrderOne.getStockType().equals(1))
            return;

        List<CustomerOrderJiaBean> customerOrderJiaBeans = new ArrayList<>();


        CustomerOrderJiaBean customerOrderJiaBean = new CustomerOrderJiaBean();
        customerOrderJiaBean.setReceiptAddress(customerOrderOne.getReceAddress());

        customerOrderJiaBean.setRequireDeliveryDate(Convert.toStr(customerOrderOne.getPickTime().getTime()));
        customerOrderJiaBean.setMerchantName(customerOrderOne.getCustomerName());
        customerOrderJiaBean.setMerchantCode(customerOrderOne.getCustomerNumber());
        customerOrderJiaBean.setCustomerName(customerOrderOne.getUserName());
        customerOrderJiaBean.setCustomerPhone(customerOrderOne.getPhone());
        customerOrderJiaBean.setComment(customerOrderOne.getNotes());
        customerOrderJiaBean.setProvince(customerOrderOne.getProvince());
        customerOrderJiaBean.setCity(customerOrderOne.getCity());
        customerOrderJiaBean.setArea(customerOrderOne.getArea());
        customerOrderJiaBean.setStreet(customerOrderOne.getStreet());

        List<SaleOrderJsonListDto> saleOrderJsonListDtos = new ArrayList<>();
        for (CustomerOrderItem customerOrderItem : list) {
            SaleOrderJsonListDto saleOrderJsonListDto = new SaleOrderJsonListDto();
            saleOrderJsonListDto.setMaterialCode(customerOrderItem.getMaterialOldNumber());
            saleOrderJsonListDto.setMaterialName(customerOrderItem.getMaterialName());
            saleOrderJsonListDto.setDeliveredNumber(customerOrderItem.getQty());
            saleOrderJsonListDtos.add(saleOrderJsonListDto);
        }
        customerOrderJiaBean.setSaleOrderDetailList(saleOrderJsonListDtos);


        customerOrderJiaBeans.add(customerOrderJiaBean);


        try {
            List<String> strings = jiaXianUtils.apiSaleOrderSave(customerOrderJiaBeans);
            customerOrderOne.setSyncStatus("OK");
            customerOrderOne.setJiaxianOrderId(strings.get(0));
            customerOrderOne.setStatus(status);
            customerOrderOne.updateById();
        } catch (Exception e) {

            throw new RemoteServiceException(e.getMessage());
        }

        gongdanLogic.installOrder(customerOrderOne.getId());

    }

    @Transactional(rollbackFor = Exception.class)
    public void sendRefund(String id, Integer status) {

        CustomerOrderRefund customerOrderOne = customerOrderRefundService.getById(id);
        if (!customerOrderOne.getStatus().equals(1))
            throw new RemoteServiceException("订单不为提交状态，不能通知发货");


        List<CustomerOrderRefundItem> list = customerOrderRefundItemService.lambdaQuery().eq(CustomerOrderRefundItem::getOrderId, id).list();

        for (CustomerOrderRefundItem customerOrderRefundItem : list) {


            CustomerStock customerStock = customerStockService.lambdaQuery()
                    .eq(CustomerStock::getCustomerNumber, customerOrderOne.getCustomerNumber())
                    .eq(CustomerStock::getMaterialCode, customerOrderRefundItem.getMaterialCode())
                    .last("limit 1").one();
            if (customerOrderOne.getStockType().equals(1)) {
                customerStock.setFrontStockNum(customerStock.getFrontStockNum().add(new BigDecimal(customerOrderRefundItem.getQty())));
            } else {
                customerStock.setCustomerStockNum(customerStock.getCustomerStockNum().add(new BigDecimal(customerOrderRefundItem.getQty())));
            }
            customerFrontLogic.stockAcc(true, Convert.toInt(customerOrderRefundItem.getQty()), customerOrderOne.getId(), "客户退货订单",
                    customerOrderOne.getStockType(), customerStock.getMaterialId(), customerStock.getCustomerId(), customerOrderRefundItem.getNotes());

            customerStock.updateById();

            CustomerOrderItem customerOrderItem = customerOrderItemService.lambdaQuery().eq(CustomerOrderItem::getMaterialCode, customerOrderRefundItem.getMaterialCode())
                    .eq(CustomerOrderItem::getOrderId, customerOrderOne.getCustomerOrderNo())
                    .last("limit 1").one();
            if (customerOrderItem == null)
                throw new RemoteServiceException("非同一个订单进行退货");
            customerOrderItem.setRealQty(customerOrderItem.getRealQty() - customerOrderRefundItem.getQty());
            if (customerOrderItem.getRealQty() < 0) {
                throw new RemoteServiceException("大于发货数量");
            }
            customerOrderItem.updateById();

        }
        CustomerOrderRefund customerOrder = new CustomerOrderRefund();
        customerOrder.setId(id);
        customerOrder.setStatus(status);
        customerOrder.updateById();


        if (!customerOrderOne.getStockType().equals(1))
            return;

        List<SaleOrderReturnJsonList> customerOrderJiaBeans = new ArrayList<>();


        SaleOrderReturnJsonList customerOrderJiaBean = new SaleOrderReturnJsonList();
        customerOrderJiaBean.setReceiptAddress(customerOrderOne.getReceAddress());

        CustomerOrder byId = customerOrderService.getById(customerOrderOne.getCustomerOrderNo());

        customerOrderJiaBean.setPickUpDate(Convert.toStr(customerOrderOne.getPickTime().getTime()));
        customerOrderJiaBean.setMerchantName(customerOrderOne.getCustomerName());
        customerOrderJiaBean.setMerchantCode(customerOrderOne.getCustomerNumber());
        customerOrderJiaBean.setCustomerName(customerOrderOne.getUserName());
        customerOrderJiaBean.setCustomerPhone(customerOrderOne.getPhone());
        customerOrderJiaBean.setComment(customerOrderOne.getRefundRemark());
        customerOrderJiaBean.setProvince(customerOrderOne.getProvince());
        customerOrderJiaBean.setCity(customerOrderOne.getCity());
        customerOrderJiaBean.setArea(customerOrderOne.getArea());
        customerOrderJiaBean.setStreet(customerOrderOne.getStreet());
        customerOrderJiaBean.setSaleOrderCode(byId.getJiaxianOrderId());

        List<SaleOrderReturnDetailList> saleOrderJsonListDtos = new ArrayList<>();
        for (CustomerOrderRefundItem customerOrderItem : list) {

            CustomerOrderItem one = customerOrderItemService.lambdaQuery().eq(CustomerOrderItem::getOrderId, customerOrderOne.getCustomerOrderNo())
                    .eq(CustomerOrderItem::getMaterialId, customerOrderItem.getMaterialId()).last("limit 1").one();

            SaleOrderReturnDetailList saleOrderJsonListDto = new SaleOrderReturnDetailList();
            saleOrderJsonListDto.setMaterialCode(customerOrderItem.getMaterialOldNumber());
            saleOrderJsonListDto.setMaterialName(customerOrderItem.getMaterialName());
            saleOrderJsonListDto.setMaterialSpecification(customerOrderItem.getSpecification());
            saleOrderJsonListDto.setDeliveredNumber(one.getQty());
            saleOrderJsonListDto.setReturnNumber(customerOrderItem.getQty());
            saleOrderJsonListDtos.add(saleOrderJsonListDto);
        }
        customerOrderJiaBean.setSaleOrderReturnDetailList(saleOrderJsonListDtos);


        customerOrderJiaBeans.add(customerOrderJiaBean);


        try {
            List<String> strings = jiaXianUtils.apiSaleOrderReturnSave(customerOrderJiaBeans);
            customerOrderOne.setSyncStatus("OK");
            customerOrderOne.setJiaxianOrderId(strings.get(0));
            customerOrderOne.setStatus(status);
            customerOrderOne.updateById();
        } catch (Exception e) {

            throw new RemoteServiceException(e.getMessage());
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void delete(String id) {

        CustomerOrder customerOrder = customerOrderService.getById(id);

        if (!customerOrder.getStatus().equals(1))
            throw new RemoteServiceException("订单不为提交状态");


        List<CustomerOrderItem> list = customerOrderItemService.lambdaQuery().eq(CustomerOrderItem::getOrderId, customerOrder.getId()).list();

        for (CustomerOrderItem order : list) {
            KingDeeMaterial kingDeeMaterial = kingDeeMaterialService.lambdaQuery().eq(KingDeeMaterial::getNumber, order.getMaterialCode()).last("limit 1").one();
            order.setOrderId(customerOrder.getId());
            order.setMaterialId(kingDeeMaterial.getId());
            CustomerStock customerStock = customerStockService.lambdaQuery()
                    .eq(CustomerStock::getCustomerNumber, customerOrder.getCustomerNumber())
                    .eq(CustomerStock::getMaterialCode, order.getMaterialCode())
                    .last("limit 1").one();


            customerFrontLogic.stockAcc(true, Convert.toInt(order.getQty()), customerOrder.getId(), "客户销售订单删除", customerOrder.getStockType(), customerStock.getMaterialId(), customerStock.getCustomerId(), order.getNotes());

            if (customerOrder.getStockType().equals(1)) {
                customerStock.setFrontStockNum(customerStock.getFrontStockNum().add(new BigDecimal(order.getQty())));
                customerStock.setLockFrontStockNum(customerStock.getLockFrontStockNum().subtract(new BigDecimal(order.getQty())));
            } else {
                customerStock.setCustomerStockNum(customerStock.getCustomerStockNum().add(new BigDecimal(order.getQty())));
                customerStock.setLockCustomerStockNum(customerStock.getLockCustomerStockNum().subtract(new BigDecimal(order.getQty())));
            }
            customerStock.updateById();

        }


        customerOrderService.removeById(id);
        customerOrderItemService.lambdaUpdate().eq(CustomerOrderItem::getOrderId, customerOrder.getId()).remove();
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteRefund(String id) {

        CustomerOrderRefund customerOrder = customerOrderRefundService.getById(id);

        if (!customerOrder.getStatus().equals(1))
            throw new RemoteServiceException("订单不为提交状态");


        List<CustomerOrderRefundItem> list = customerOrderRefundItemService.lambdaQuery().eq(CustomerOrderRefundItem::getOrderId, customerOrder.getId()).list();

        for (CustomerOrderRefundItem order : list) {
            KingDeeMaterial kingDeeMaterial = kingDeeMaterialService.lambdaQuery().eq(KingDeeMaterial::getNumber, order.getMaterialCode()).last("limit 1").one();
            order.setOrderId(customerOrder.getId());
            order.setMaterialId(kingDeeMaterial.getId());


            CustomerOrderItem customerOrderItem = customerOrderItemService.lambdaQuery().eq(CustomerOrderItem::getMaterialCode, order.getMaterialCode())
                    .eq(CustomerOrderItem::getOrderId, customerOrder.getCustomerOrderNo())
                    .last("limit 1").one();
            customerOrderItem.setRefundQty(customerOrderItem.getRefundQty() + order.getQty());
            customerOrderItem.updateById();

        }


        customerOrderRefundService.removeById(id);
        customerOrderRefundItemService.lambdaUpdate().eq(CustomerOrderRefundItem::getOrderId, customerOrder.getId()).remove();
    }

    public CustomerOrderPushBean listPush(String encrypted) {
        Date date = DateUtil.date(Convert.toLong(encrypted + "000"));
        String format = DateUtil.format(date, "yyyy-MM-dd HH:mm:ss");
        String sync = Convert.toStr(System.currentTimeMillis() / 1000);
        List<CustomerOrderPush> customerOrderPushes = customerFrontOrderMapper.listPush(format);

        CustomerOrderPushBean customerOrderPushBean = new CustomerOrderPushBean();
        customerOrderPushBean.setSyncTime(sync);
        customerOrderPushBean.setCustomerOrderPushes(customerOrderPushes);
        return customerOrderPushBean;
    }

    public CustomerOrderRefundPushBean orderRefundPush(String encrypted) {
        Date date = DateUtil.date(Convert.toLong(encrypted + "000"));
        String format = DateUtil.format(date, "yyyy-MM-dd HH:mm:ss");
        String sync = Convert.toStr(System.currentTimeMillis() / 1000);
        List<CustomerOrderRefundPush> customerOrderPushes = customerFrontOrderMapper.orderRefundPush(format);

        CustomerOrderRefundPushBean customerOrderPushBean = new CustomerOrderRefundPushBean();
        customerOrderPushBean.setSyncTime(sync);
        customerOrderPushBean.setCustomerOrderRefundPushes(customerOrderPushes);
        return customerOrderPushBean;
    }

    public CustomerStockOrderPushBean customerStockAcc(String encrypted) {

        Date date = DateUtil.date(Convert.toLong(encrypted + "000"));
        String format = DateUtil.format(date, "yyyy-MM-dd HH:mm:ss");
        String sync = Convert.toStr(System.currentTimeMillis() / 1000);
        List<CustomerStockOrderPush> customerOrderPushes = customerFrontOrderMapper.customerStockAcc(format);

        CustomerStockOrderPushBean customerOrderPushBean = new CustomerStockOrderPushBean();
        customerOrderPushBean.setSyncTime(sync);
        customerOrderPushBean.setCustomerStockOrderPushes(customerOrderPushes);
        return customerOrderPushBean;
    }

    public IPage<CustomerOrderRefundOrder> listOrder(Page page, ZfireParamBean zfireParam) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String customerId = adminUser.getIsCustomer() ? adminUser.getCustomerId() : "";
        IPage<CustomerOrderRefundOrder> customerStockBeanIPage = customerFrontOrderMapper.listOrder(page, zfireParam, customerId);
        return customerStockBeanIPage;
    }

    @Transactional(rollbackFor = Exception.class)
    public void signIn(String id, Integer status) {

        CustomerOrder customerOrderOne = customerOrderService.getById(id);
        if (!status.equals(4))
            throw new RemoteServiceException("状态不为签收，不能签收");

        if (customerOrderOne.getStatus().equals(4))
            throw new RemoteServiceException("状态已为签收");

        if (customerOrderOne.getStockType().equals(1))
            throw new RemoteServiceException("不为商家仓，不能签收");

        List<CustomerOrderItem> list = customerOrderItemService.lambdaQuery().eq(CustomerOrderItem::getOrderId, id).list();

        for (CustomerOrderItem customerOrderRefundItem : list) {
            CustomerStock customerStock = customerStockService.lambdaQuery()
                    .eq(CustomerStock::getCustomerNumber, customerOrderOne.getCustomerNumber())
                    .eq(CustomerStock::getMaterialCode, customerOrderRefundItem.getMaterialCode())
                    .last("limit 1").one();
            if (customerOrderOne.getStockType().equals(1)) {
                customerStock.setLockFrontStockNum(customerStock.getLockFrontStockNum().subtract(new BigDecimal(customerOrderRefundItem.getQty())));
            } else {
                customerStock.setLockCustomerStockNum(customerStock.getLockCustomerStockNum().subtract(new BigDecimal(customerOrderRefundItem.getQty())));
            }
            customerStock.updateById();

        }

        CustomerOrder customerOrder = new CustomerOrder();
        customerOrder.setId(id);
        customerOrder.setStatus(status);
        customerOrder.updateById();
    }


    /*
     * 发货单生订单号
     * */
    public String generateOrder() {

        //生成订单流水号
        String yyyyMM = DateUtil.format(new Date(), "yyyyMMdd");
        String orderWater = yyyyMM.substring(yyyyMM.length() - 8);
        if (redisUtil.get(Constant.RedisPrefix.CUSTOMER_ORDER_NUMBER + orderWater) == null) {
            redisUtil.set(Constant.RedisPrefix.CUSTOMER_ORDER_NUMBER + orderWater, "000000", 2726560);
        }
        Object water = redisUtil.get(Constant.RedisPrefix.CUSTOMER_ORDER_NUMBER + orderWater);
        String s = pickLogic.generateNum(4, Convert.toStr(water));


        redisUtil.set(Constant.RedisPrefix.CUSTOMER_ORDER_NUMBER + orderWater, s, 2726560);

        return orderWater + s;
    }

    /*
     * 发货单生订单号
     * */
    public String generateRefundOrder() {

        //生成订单流水号
        String yyyyMM = DateUtil.format(new Date(), "yyyyMMdd");
        String orderWater = yyyyMM.substring(yyyyMM.length() - 8);
        if (redisUtil.get(Constant.RedisPrefix.CUSTOMER_ORDER_REFUND_NUMBER + orderWater) == null) {
            redisUtil.set(Constant.RedisPrefix.CUSTOMER_ORDER_REFUND_NUMBER + orderWater, "000000", 2726560);
        }
        Object water = redisUtil.get(Constant.RedisPrefix.CUSTOMER_ORDER_REFUND_NUMBER + orderWater);
        String s = pickLogic.generateNum(4, Convert.toStr(water));


        redisUtil.set(Constant.RedisPrefix.CUSTOMER_ORDER_REFUND_NUMBER + orderWater, s, 2726560);

        return orderWater + s;
    }

    @Transactional(rollbackFor = Exception.class)
    public void sendRevokeRefund(String id, Integer status) {

        CustomerOrderRefund customerOrderOne = customerOrderRefundService.getById(id);
        if (!customerOrderOne.getStatus().equals(2))
            throw new RemoteServiceException("订单不为退货状态，不能通知发货");

        List<CustomerOrderRefundItem> list = customerOrderRefundItemService.lambdaQuery().eq(CustomerOrderRefundItem::getOrderId, id).list();

        for (CustomerOrderRefundItem customerOrderRefundItem : list) {
            CustomerStock customerStock = customerStockService.lambdaQuery()
                    .eq(CustomerStock::getCustomerNumber, customerOrderOne.getCustomerNumber())
                    .eq(CustomerStock::getMaterialCode, customerOrderRefundItem.getMaterialCode())
                    .last("limit 1").one();

            customerFrontLogic.stockAcc(true, Convert.toInt(customerOrderRefundItem.getQty()), customerOrderOne.getId(), "客户销售订单删除",
                    customerOrderOne.getStockType(), customerStock.getMaterialId(), customerStock.getCustomerId(), customerOrderRefundItem.getNotes());

            if (customerOrderOne.getStockType().equals(1)) {
                customerStock.setFrontStockNum(customerStock.getFrontStockNum().subtract(new BigDecimal(customerOrderRefundItem.getQty())));
                if (Convert.toLong(customerStock.getFrontStockNum()) < 0)
                    throw new RemoteServiceException("库存没有那么多");
            } else {
                customerStock.setCustomerStockNum(customerStock.getCustomerStockNum().subtract(new BigDecimal(customerOrderRefundItem.getQty())));
                if (Convert.toLong(customerStock.getCustomerStockNum()) < 0)
                    throw new RemoteServiceException("库存没有那么多");
            }
            customerStock.updateById();

            CustomerOrderItem customerOrderItem = customerOrderItemService.lambdaQuery().eq(CustomerOrderItem::getMaterialCode, customerOrderRefundItem.getMaterialCode())
                    .eq(CustomerOrderItem::getOrderId, customerOrderOne.getCustomerOrderNo())
                    .last("limit 1").one();
            customerOrderItem.setRealQty(customerOrderItem.getRefundQty() + customerOrderRefundItem.getQty());
            customerOrderItem.updateById();

        }

        CustomerOrderRefund customerOrder = new CustomerOrderRefund();
        customerOrder.setId(id);
        customerOrder.setStatus(status);
        customerOrder.updateById();

        if (customerOrderOne.getStockType().equals(2)){
            deleteRefund(id);
        }

        if (!customerOrderOne.getStockType().equals(1))
            return;

        List<String> orderId = new ArrayList<>();
        orderId.add(customerOrderOne.getJiaxianOrderId());
        try {
            jiaXianUtils.apiSaleOrderReturnRemove(orderId);
        } catch (Exception e) {
            throw new RemoteServiceException(e.getMessage());
        }
    }


    @Transactional(rollbackFor = Exception.class)
    public void sendRevoke(String id, Integer status) {

        CustomerOrder customerOrderOne = customerOrderService.getById(id);
        if (!customerOrderOne.getStatus().equals(2))
            throw new RemoteServiceException("订单不为待发货状态，不能撤销发货");


        List<CustomerOrderItem> list = customerOrderItemService.lambdaQuery().eq(CustomerOrderItem::getOrderId, id).list();

        for (CustomerOrderItem customerOrderRefundItem : list) {
            CustomerStock customerStock = customerStockService.lambdaQuery()
                    .eq(CustomerStock::getCustomerNumber, customerOrderOne.getCustomerNumber())
                    .eq(CustomerStock::getMaterialCode, customerOrderRefundItem.getMaterialCode())
                    .last("limit 1").one();
            if (customerOrderOne.getStockType().equals(1)) {
                customerStock.setLockFrontStockNum(customerStock.getLockFrontStockNum().add(new BigDecimal(customerOrderRefundItem.getQty())));
            } else {
                customerStock.setLockCustomerStockNum(customerStock.getLockCustomerStockNum().add(new BigDecimal(customerOrderRefundItem.getQty())));
            }
            customerStock.updateById();

        }
        CustomerOrder customerOrder = new CustomerOrder();
        customerOrder.setId(id);
        customerOrder.setStatus(status);
        customerOrder.updateById();

        if (!customerOrderOne.getStockType().equals(1))
            return;

        List<String> orderId = new ArrayList<>();
        orderId.add(customerOrderOne.getJiaxianOrderId());
        try {
            jiaXianUtils.apiSaleOrderRemove(orderId);
        } catch (Exception e) {
            throw new RemoteServiceException(e.getMessage());
        }
    }

    public IPage<OrderTrackTocBean> orderTrackList(Page page, ZfireParamBean zfireParam) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String customerId = adminUser.getIsCustomer() ? adminUser.getCustomerId() : "";
        IPage<OrderTrackTocBean> orderTrackTocBeanIPage = customerFrontOrderMapper.orderTrackList(page, zfireParam, customerId);
        return orderTrackTocBeanIPage;
    }
}
