package com.jwipc.shopping.logic.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.jwipc.exception.DaoException;
import com.jwipc.inquiry.client.PurchaseApplyBillDetailClient;
import com.jwipc.inquiry.dto.PurchaseApplyBillDetailClientDTO;
import com.jwipc.page.PageUtil;
import com.jwipc.page.PageView;
import com.jwipc.security.LoginUtil;
import com.jwipc.security.dto.CurrentUserDTO;
import com.jwipc.shopping.convert.OnlineMallConvert;
import com.jwipc.shopping.convert.ShoppingCartInfoConvert;
import com.jwipc.shopping.dto.OnlineMallResponseDTO;
import com.jwipc.shopping.dto.ShoppingAfterSalesDTO;
import com.jwipc.shopping.dto.ShoppingAfterSalesInfoDTO;
import com.jwipc.shopping.entity.*;
import com.jwipc.shopping.logic.OnlineMallLogic;
import com.jwipc.shopping.model.po.ShoppingAfterSalesPO;
import com.jwipc.shopping.model.po.ShoppingCartInfoPO;
import com.jwipc.shopping.model.query.*;
import com.jwipc.shopping.model.vo.*;
import com.jwipc.shopping.service.*;
import com.jwipc.shopping.service.impl.OnlineMallServiceImpl;
import com.jwipc.sys.client.DictClient;
import com.jwipc.sys.client.SequenceClient;
import com.jwipc.sys.client.dto.DictDTO;
import com.jwipc.util.EasyExcelImportUtils;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 功能描述:
 *
 * @Author: zx
 * @Date: 2024/3/14 0014 10:25
 */
@Service
@RequiredArgsConstructor
public class OnlineMallLogicImpl implements OnlineMallLogic {
    private final PurchaseApplyBillDetailClient purchaseApplyBillDetailClient;
    private final static Logger LOGGER = LoggerFactory.getLogger(OnlineMallLogicImpl.class);

    @Autowired
    IMiddleWareService middleWareService;

    @Autowired
    OnlineMallServiceImpl onlineMallServiceImpl;

    @Autowired
    SequenceClient sequenceClient;

    @Autowired
    IOnlineMallService onlineMallService;

    @Autowired
    IShoppingCartInfoService cartInfoService;

    @Autowired
    IShoppingReceivingAddressService shoppingReceivingAddressService;

    @Autowired
    IShoppingCartService cartService;

    @Autowired
    IShoppingCartInfoService shoppingCartInfoService;

    @Autowired
    OnlineMallConvert onlineMallConvert;

    @Autowired
    ShoppingCartInfoConvert shoppingCartInfoConvert;

    @Autowired
    IShoppingInvoiceService invoiceService;

    @Autowired
    IShoppingAfterSalesService shoppingAfterSalesService;

    @Autowired
    IShoppingAfterSalesInfoService shoppingAfterSalesInfoService;

    @Autowired
    DictClient dictClient;

    @Override
    public OnlineShoppingZkhResponse findOnlineMallCommodity(OnlineMallCommodityQuery query) {
        OnlineShoppingZkhResponse result = new OnlineShoppingZkhResponse();
        result.setTotalCount(0);
        result.setCode("1");
        result.setResulteMessage("");

        final List<String> sourceList = Arrays.asList(StringUtils.split(query.getSources(), ","));
        query.setPageSize(query.getPageSize() / sourceList.size());

        for (String source : sourceList) {
            query.setSource(source);
            final OnlineShoppingZkhResponse db = onlineMallService.findOnlineMallCommodity1(query);
            if (!"1".equals(db.getCode())) {
                result.setCode(db.getCode());
                result.setResulteMessage(db.getMessage() + "(出错商城编码 " + source + " )");
            } else {
                result.setTotalCount(db.getResult().getCount());
                List<ProductRecord> items = db.getResult().getRecords();
                if (db.getResult().getCount() != 0) {
                    for (ProductRecord productRecord : items) {
                        productRecord.setSource(source);
                        productRecord.setSourceName(source == "ZKH" ? "震坤行" : "");
                    }
                    db.getResult().setRecords(items);
                    result.setAccessToken(db.getAccessToken());
                    result.setResult(db.getResult());
                    result.setResultCode(db.getResultCode());
                    result.setSuccess(db.getSuccess());
                }
            }
        }
        return result;
    }


    @Override
    public ShoppingDetailReponse findShoppingDetail(ShoppingDetailQuery query) {
        ShoppingDetailReponse result = null;
        result = onlineMallService.findShoppingDetail(query);
        return result;
    }

    @Override
    public String getProductUrlByZkh(String productDescUrl) {
        return onlineMallService.getProductUrlByZkh(productDescUrl);
    }

    @Override
    public ShoppingReceivingAddress selectDetailById(Long id) {
        return shoppingReceivingAddressService.getById(id);
    }


    @Override
    public OnlineMallResponseDTO pushMallShoppingCart(CurrentUserDTO currentUserDTO,
                                                      String XYParams, String ZKHParams, String receivingItem, String invoiceItem, String dateItem) {

        OnlineMallResponse response = new OnlineMallResponse();

        //List<MallShoppingCartSaveDto> xyDataList = JSONArray.parseArray(XYParams, MallShoppingCartSaveDto.class);
        List<MallShoppingCartSaveDto> zkhDataList = JSONArray.parseArray(ZKHParams, MallShoppingCartSaveDto.class);
        /*if(xyDataList.size() > 0){
            // 需要推送西域商城
            OnlineShoppingXyDto xyDto = new OnlineShoppingXyDto();
            List<OnlineShoppingXyDto.Items> itemList = Lists.newArrayList();
            // 最后需要保存到SRM中商城购物车记录中
            List<ShoppingCartInfo> scList = Lists.newArrayList();


            ShoppingCart cart = new ShoppingCart();
            String thirdOrder = sequenceClient.createSequenceNo("mall_reservation_code");
            xyDto.setThirdOrder(thirdOrder);
            cart.setThirdOrder(thirdOrder);

            xyDto.setToken(onlineMallService.findTokenByCart("XY"));

            // 收货地址信息
            ShoppingReceivingAddress address = JSONObject.parseObject(receivingItem, ShoppingReceivingAddress.class);
            if(!Objects.isNull(address)){
                xyDto.setName(address.getReceivingUser());
                xyDto.setProvince(Integer.parseInt(address.getProvinceCode()));
                xyDto.setCity(Integer.parseInt(address.getCityCode()));
                xyDto.setCounty(Integer.parseInt(address.getCountyCode()));
                xyDto.setTown(0);
                xyDto.setAddress(address.getAddress());
                xyDto.setMobile(address.getReceivingTel());

                xyDto.setInvoiceProvice(Integer.parseInt(address.getProvinceCode()));
                xyDto.setInvoiceCity(Integer.parseInt(address.getCityCode()));
                xyDto.setInvoiceCounty(Integer.parseInt(address.getCountyCode()));

                // 保存到购物车
                cart.setReceivingId(address.getId());
            }

            // 发票信息
            ShoppingInvoiceDTO invoice = JSONObject.parseObject(invoiceItem, ShoppingInvoiceDTO.class);
            if(!Objects.isNull(invoice)){
                xyDto.setInvoiceState(invoice.getInvoiceState());
                if(1 == invoice.getInvoiceState()) {
                    xyDto.setInvoiceType(invoice.getInvoiceType());
                    xyDto.setCompanyName(invoice.getInvoiceTitle());
                    xyDto.setOrderCompany(invoice.getInvoiceTitle());
                    xyDto.setReceiptCompanyTel(invoice.getInvoiceTel());
                    xyDto.setReceiptCompanyAddr(invoice.getInvoiceAddress());
                    xyDto.setReceiptTaxNo(invoice.getInvoiceNo());
                    xyDto.setReceiptBankName(invoice.getOpeningBank());
                    xyDto.setReceiptAccount(invoice.getBankAccount());
                    xyDto.setRemark(invoice.getContent());

                    // 保存到购物车
                    cart.setInvoiceId(invoice.getId());
                    cart.setInvoiceState(invoice.getInvoiceState());
                    cart.setInvoiceType(invoice.getInvoiceType());
                    cart.setContent(invoice.getContent());
                }
            }

            // 采购信息
            ShoppingCartDTO date = JSONObject.parseObject(dateItem, ShoppingCartDTO.class);
            if(!Objects.isNull(date)){
                xyDto.setFactoryCode(date.getFactoryCode());
                xyDto.setFactoryName(date.getFactoryName());
                xyDto.setContent(date.getRemark());

                cart.setFactoryCode(date.getFactoryCode());
                cart.setCenterCode(date.getCenterCode());
                cart.setPurchaseGroup(date.getPurchaseGroup());
                cart.setPurchaseOrg(date.getPurchaseOrg());
                cart.setRemark(date.getRemark());
                cart.setInvoiceState(date.getInvoiceState());
            }

            String storeCode = "", storeName = "";
            for (MallShoppingCartSaveDto dto: xyDataList){
                OnlineShoppingXyDto.Items items = new OnlineShoppingXyDto.Items();
                items.setSkuId(dto.getProductCode());
                items.setNum(dto.getQty().intValue());
                items.setPrice(dto.getProductPrice().setScale(2, BigDecimal.ROUND_HALF_UP));
                items.setProductUnit(dto.getProductUnit());
                storeCode = dto.getSourceCode();
                storeName = dto.getSourceName();
                itemList.add(items);

                scList.add(dto.toSc());
            }

            cart.setSrmStatus(1);
            cart.setStoreCode(storeCode);
            cart.setStoreName(storeName);
            cart.setCreateUserCode(currentUserDTO.getLoginName());
            cart.setCreateUserId(currentUserDTO.getUserId());
            cart.setCreateUserName(currentUserDTO.getName());
            cart.setCreateTime(LocalDateTime.now());
            cartService.save(cart);

            // 将推送商城购物车的数据保存到本地
            if(CollectionUtils.isNotEmpty(scList)){
                for (ShoppingCartInfo info: scList) {
                    info.setCartId(cart.getId());
                }
                shoppingCartInfoService.saveBatch(scList);
            }else {
                throw new DaoException("西域商城数据保存失败, 请检查");
            }

            if(CollectionUtils.isNotEmpty(itemList)){
                xyDto.setSku(itemList);
                xyDto.setStoreCode(storeCode);
                xyDto.setStoreName(storeName);
                response = onlineMallService.pushShoppingCartXy(cart, xyDto, currentUserDTO.getLoginName(), scList);
            }
        }*/

        // 需要推送震坤行商城
        if (zkhDataList.size() > 0) {
            OnlineShoppingZkhDto zkhDto = new OnlineShoppingZkhDto();
            List<OnlineShoppingZkhDto.Items> itemList = Lists.newArrayList();
            // 最后需要保存到SRM中商城购物车记录中
            List<ShoppingCartInfo> scList = Lists.newArrayList();

            ShoppingCart cart = new ShoppingCart();
            String thirdOrder = sequenceClient.createSequenceNo("mall_reservation_code");
            zkhDto.setThirdOrder(thirdOrder);
            cart.setThirdOrder(thirdOrder);

            zkhDto.setToken(onlineMallService.findTokenByCart("ZKH"));

            // 收货地址信息
            ShoppingReceivingAddress address = JSONObject.parseObject(receivingItem, ShoppingReceivingAddress.class);
            if (!Objects.isNull(address)) {
                zkhDto.setPurchaseAccount(currentUserDTO.getLoginName());

                zkhDto.setName(address.getReceivingUser());
                zkhDto.setInvoiceName(address.getReceivingUser());
                zkhDto.setAddress(address.getAddress());
                zkhDto.setMobile(address.getReceivingTel());
                zkhDto.setInvoicePhone(address.getReceivingTel());
                OnlineShoppingZkhDto.ShoppingAddress region = new OnlineShoppingZkhDto.ShoppingAddress();
                region.setProvince(address.getProvinceName());
                region.setCity(address.getCityName());
                region.setCounty(address.getCountyName());
                region.setTown("");
                zkhDto.setRegion(region);

                String invoiceAddress = address.getProvinceName() + address.getCityName() + address.getCountyName() + address.getAddress();
                zkhDto.setAddress(invoiceAddress);
                zkhDto.setInvoiceAddress(invoiceAddress);

                // 保存到购物车
                cart.setReceivingId(address.getId());
            }

            // 发票信息
            ShoppingInvoiceDTO invoice = JSONObject.parseObject(invoiceItem, ShoppingInvoiceDTO.class);
            if (!Objects.isNull(invoice)) {
                OnlineShoppingZkhDto.invoice invoiceInfo = new OnlineShoppingZkhDto.invoice();
                invoiceInfo.setType(invoice.getInvoiceType());
                invoiceInfo.setContent(invoice.getContent());
                invoiceInfo.setTitle(invoice.getInvoiceTitle());
                invoiceInfo.setEnterpriseTaxpayer(invoice.getInvoiceNo());
                invoiceInfo.setBank(invoice.getOpeningBank());
                invoiceInfo.setAccount(invoice.getBankAccount());
                invoiceInfo.setTel(invoice.getInvoiceTel());
                invoiceInfo.setAddress(invoice.getInvoiceAddress());
                zkhDto.setInvoiceInfo(invoiceInfo);

                // 保存到购物车
                cart.setInvoiceId(invoice.getId());
                cart.setInvoiceType(invoice.getInvoiceType());
                cart.setContent(invoice.getContent());
                cart.setInvoiceState(invoice.getInvoiceState());
            }

            // 采购信息
            ShoppingCartDTO date = JSONObject.parseObject(dateItem, ShoppingCartDTO.class);
            if (!Objects.isNull(date)) {
                zkhDto.setFactoryCode(date.getFactoryCode());
                zkhDto.setFactoryName(date.getFactoryName());
                zkhDto.setRemark(date.getRemark());

                cart.setFactoryCode(date.getFactoryCode());
                //cart.setCenterCode(date.getCenterCode());
                cart.setPurchaseGroup(date.getPurchaseGroup());
                cart.setPurchaseOrg(date.getPurchaseOrg());
                cart.setRemark(date.getRemark());
            }

            String storeCode = "", storeName = "";
            //新保存的
            List<Long> detailIds = new ArrayList<>();
            //拿到剩余数量和采购申请明细id
            BigDecimal remainQuantity = null;
            List<PurchaseApplyBillDetailClientDTO> applyBillDetailList = new ArrayList<>();
//            Long remainId = null;
            for (MallShoppingCartSaveDto dto : zkhDataList) {
                //查询采购申请明细信息
                PurchaseApplyBillDetailClientDTO applyBillDetail = purchaseApplyBillDetailClient.getByBillCodeAndItemCode(dto.getPrCode(), dto.getPrItemNo());
                detailIds.add(applyBillDetail.getId());
                //购物车提交时，让剩余数量减去订单里的数量
                remainQuantity = applyBillDetail.getRemainQuantity().subtract(dto.getQty());
                applyBillDetail.setRemainQuantity(remainQuantity);
                applyBillDetailList.add(applyBillDetail);
//                remainId = applyBillDetail.getId();
                OnlineShoppingZkhDto.Items items = new OnlineShoppingZkhDto.Items();
                items.setSkuId(dto.getProductCode());
                //调用上架接口
                ApplyProductResponse applyProductResponse = onlineMallService.applyProduct(dto.getProductCode());
                if (!"0000".equals(applyProductResponse.getResultCode())) {
                    throw new DaoException(applyProductResponse.getResultMessage());
                }
                items.setNum(dto.getQty().intValue());
                items.setPrice(dto.getProductPrice().setScale(2, BigDecimal.ROUND_HALF_UP));
                items.setProductUnit(dto.getProductUnit());
                items.setNakedPrice(dto.getNakedPrice().setScale(2, BigDecimal.ROUND_HALF_UP));
                storeCode = dto.getSourceCode();
                storeName = dto.getSourceName();
                itemList.add(items);

                scList.add(dto.toSc());


            }

            cart.setSrmStatus(1);
            cart.setStoreCode(storeCode);
            cart.setStoreName(storeName);
            cart.setCreateUserCode(currentUserDTO.getLoginName());
            cart.setCreateUserId(currentUserDTO.getUserId());
            cart.setCreateUserName(currentUserDTO.getName());
            cart.setCreateTime(LocalDateTime.now());
            cartService.save(cart);

            // 将推送商城购物车的数据保存到本地
            if (CollectionUtils.isNotEmpty(scList)) {
                for (ShoppingCartInfo info : scList) {
                    info.setCartId(cart.getId());
                }
                shoppingCartInfoService.saveBatch(scList);
            } else {
                throw new DaoException("震坤行商城数据保存失败, 请检查");
            }

            if (CollectionUtils.isNotEmpty(itemList)) {
                zkhDto.setSku(itemList);
                zkhDto.setStoreCode(storeCode);
                zkhDto.setStoreName(storeName);

                String message = "";
                if (response.getCode() == -1) {
                    message = response.getErrorMsg();
                }
                zkhDto.setPurchaseMobile(LoginUtil.getCurrentUser().getPhone());
                response = onlineMallService.pushShoppingCartZkh(cart, zkhDto, scList);
                if (response.getCode() == 0) {

                    //商城订单成功后回写采购明细表剩余数量
                    purchaseApplyBillDetailClient.updateRemainQuantity(applyBillDetailList);
                    //商城订单成功后回写采购明细表采购方式
                    purchaseApplyBillDetailClient.updatePuchaseMethode("Z003", 2, detailIds);
                }
                if (response.getCode() == -1) {
                    response.setErrorMsg(message + ";" + response.getErrorMsg());
                } else if (!Strings.isNullOrEmpty(message)) {
                    response.setCode(-1);
                    response.setErrorMsg(message);
                }
            }
        }
        return onlineMallConvert.entitiesPoToDto(response);
    }

    @Override
    public void pushMallExcelCart(CurrentUserDTO currentUserDTO, String params, String receivingItem, String invoiceItem, String dateItem) {
        List<MallShoppingCartSaveDto> paramsList = JSONArray.parseArray(params, MallShoppingCartSaveDto.class);
        if (paramsList.size() > 0) {
            OnlineShoppingZkhDto zkhDto = new OnlineShoppingZkhDto();
            // 最后需要保存到SRM中商城购物车记录中
            List<ShoppingCartInfo> scList = Lists.newArrayList();

            ShoppingCart cart = new ShoppingCart();
            String thirdOrder = sequenceClient.createSequenceNo("mall_reservation_code");
            zkhDto.setThirdOrder(thirdOrder);
            cart.setThirdOrder(thirdOrder);
            cart.setDataStatus(1);
            //cart.setReceiptStatus(1);//已收货
            zkhDto.setToken(onlineMallService.findTokenByCart("ZKH"));

            // 收货地址信息
            //ShoppingReceivingAddress address = JSONObject.parseObject(receivingItem, ShoppingReceivingAddress.class);
            /*if(!Objects.isNull(address)){
                zkhDto.setPurchaseAccount(currentUserDTO.getLoginName());

                zkhDto.setName(address.getReceivingUser());
                zkhDto.setInvoiceName(address.getReceivingUser());
                zkhDto.setAddress(address.getAddress());
                zkhDto.setMobile(address.getReceivingTel());
                zkhDto.setInvoicePhone(address.getReceivingTel());
                OnlineShoppingZkhDto.ShoppingAddress region = new OnlineShoppingZkhDto.ShoppingAddress();
                region.setProvince(address.getProvinceName());
                region.setCity(address.getCityName());
                region.setCounty(address.getCountyName());
                region.setTown("");
                zkhDto.setRegion(region);

                String invoiceAddress = address.getProvinceName() + address.getCityName() + address.getCountyName() + address.getAddress();
                zkhDto.setAddress(invoiceAddress);
                zkhDto.setInvoiceAddress(invoiceAddress);

                // 保存到购物车
                cart.setReceivingId(address.getId());
            }*/

            // 发票信息
            ShoppingInvoiceDTO invoice = JSONObject.parseObject(invoiceItem, ShoppingInvoiceDTO.class);
            if (!Objects.isNull(invoice)) {
                OnlineShoppingZkhDto.invoice invoiceInfo = new OnlineShoppingZkhDto.invoice();
                invoiceInfo.setType(invoice.getInvoiceType());
                invoiceInfo.setContent(invoice.getContent());
                invoiceInfo.setTitle(invoice.getInvoiceTitle());
                invoiceInfo.setEnterpriseTaxpayer(invoice.getInvoiceNo());
                invoiceInfo.setBank(invoice.getOpeningBank());
                invoiceInfo.setAccount(invoice.getBankAccount());
                invoiceInfo.setTel(invoice.getInvoiceTel());
                invoiceInfo.setAddress(invoice.getInvoiceAddress());
                zkhDto.setInvoiceInfo(invoiceInfo);

                // 保存到购物车
                cart.setInvoiceId(invoice.getId());
                cart.setInvoiceType(invoice.getInvoiceType());
                cart.setContent(invoice.getContent());
                cart.setInvoiceState(invoice.getInvoiceState());
            }

            // 采购信息
            ShoppingCartDTO date = JSONObject.parseObject(dateItem, ShoppingCartDTO.class);
            if (!Objects.isNull(date)) {
                zkhDto.setFactoryCode(date.getFactoryCode());
                zkhDto.setFactoryName(date.getFactoryName());
                zkhDto.setRemark(date.getRemark());

                cart.setFactoryCode(date.getFactoryCode());
                cart.setCenterCode(date.getCenterCode());
                cart.setPurchaseGroup(date.getPurchaseGroup());
                cart.setPurchaseOrg(date.getPurchaseOrg());
                cart.setRemark(date.getRemark());
            }
            List<Long> detailIds = new ArrayList<>();
            for (MallShoppingCartSaveDto dto : paramsList) {
                PurchaseApplyBillDetailClientDTO applyBillDetail = purchaseApplyBillDetailClient.getByBillCodeAndItemCode(dto.getPrCode(), dto.getPrItemNo());
                detailIds.add(applyBillDetail.getId());
                OnlineShoppingZkhDto.Items items = new OnlineShoppingZkhDto.Items();
                items.setSkuId(dto.getProductCode());
                items.setNum(dto.getQty().intValue());
                items.setPrice(dto.getProductPrice().setScale(2, BigDecimal.ROUND_HALF_UP));
                //items.setProductUnit(dto.getProductUnit());
                dto.setDeliveryStatus(2);//签收
                dto.setPurchaseDate(LocalDateTime.now());
                scList.add(dto.toSc());
            }

            if(CollectionUtils.isNotEmpty(detailIds)){
                purchaseApplyBillDetailClient.updatePuchaseMethodeById(3,detailIds);
            }

            cart.setSrmStatus(6);
            cart.setStoreCode("other");
            cart.setStoreName("第三方商城");
            cart.setCreateUserCode(currentUserDTO.getLoginName());
            cart.setCreateUserId(currentUserDTO.getUserId());
            cart.setCreateUserName(currentUserDTO.getName());
            cart.setCreateTime(LocalDateTime.now());
            cartService.save(cart);

            // 将推送商城购物车的数据保存到本地
            if (CollectionUtils.isNotEmpty(scList)) {
                for (ShoppingCartInfo info : scList) {
                    info.setCartId(cart.getId());
                }
                shoppingCartInfoService.saveBatch(scList);
            }

            //
        }
    }

    @Override
    public PageView addresslistPage(ReceivingAddressQuery query) {
        final Page<ShoppingReceivingAddress> page = PageUtil.toPage(query);
        List<ShoppingReceivingAddress> list = shoppingReceivingAddressService.selectDataByQuery(page, query);
        return PageUtil.getPV(list, page.getTotal());
    }

    @Override
    public void updateAddressById(String receivingAddressId) {
        ShoppingReceivingAddress receivingAddress = new ShoppingReceivingAddress();
        receivingAddress.setId(Long.valueOf(receivingAddressId));
        receivingAddress.setDeleteFlag(1);
        receivingAddress.setUpdateTime(LocalDateTime.now());
        receivingAddress.setUpdateUserId(LoginUtil.getUserId());
        receivingAddress.setUpdateUserCode(LoginUtil.getAccount());
        receivingAddress.setUpdateUserName(LoginUtil.getName());
        shoppingReceivingAddressService.updateById(receivingAddress);
    }

    @Override
    public void saveOrUpdate(ShoppingReceivingAddress data) {
        if (0L == data.getId()) {
            data.setId(null);
            data.setCreateUserCode(LoginUtil.getAccount());
            data.setCreateUserId(LoginUtil.getUserId());
            data.setCreateUserName(LoginUtil.getName());
            data.setCreateTime(LocalDateTime.now());
        } else {
            data.setUpdateUserId(LoginUtil.getUserId());
            data.setUpdateUserCode(LoginUtil.getAccount());
            data.setUpdateUserName(LoginUtil.getName());
            data.setUpdateTime(LocalDateTime.now());
        }
        shoppingReceivingAddressService.saveOrUpdate(data);
    }

    @Override
    public ShoppingInvoice selectInvoiceDetailById(Long id) {
        return invoiceService.getById(id);
    }

    @Override
    public PageView listInvoicePage(ShoppingQuery query) {
        final Page<ShoppingReceivingAddress> page = PageUtil.toPage(query);
        List<ShoppingInvoice> list = invoiceService.selectDataByQuery(page, query);
        return PageUtil.getPV(list, page.getTotal());
    }

    @Override
    public void addOrEditInvoice(ShoppingInvoice data) {
        invoiceService.saveOrUpdate(data);
    }

    @Override
    public PageView findByCartPage(OnlineMallCartQuery query) {
        final Page<OnlineMallCart> page = PageUtil.toPage(query);
        List<OnlineMallCart> list = cartService.selectDataByQuery(page, query);
        return PageUtil.getPV(list, page.getTotal());
    }

    @Override
    public PageView findInfoByCartPage(OnlineMallCartQuery query) {
        final Page<OnlineMallCart> page = PageUtil.toPage(query);
        List<OnlineMallCart> list = cartService.selectInfoDataByQuery(page, query);
        return PageUtil.getPV(list, page.getTotal());
    }

    @Override
    public Integer confirmMallOrder(Long id) {
        return onlineMallService.confirmMallOrder(id);
    }

    @Override
    public String confirmMallOrder2(Long id) {
        return onlineMallService.confirmMallOrder2(id);
    }

    @Override
    public void remove(Long id) {
        //删除
        shoppingAfterSalesService.remove(new LambdaQueryWrapper<ShoppingAfterSales>().eq(ShoppingAfterSales::getId, id));
        shoppingAfterSalesInfoService.remove(new LambdaQueryWrapper<ShoppingAfterSalesInfo>().eq(ShoppingAfterSalesInfo::getAfId, id));
    }

    @Override
    public Long findHeadByOrderCode(String cartId) {

        ShoppingCart onlineMallCart = cartService.getByOArderCode(cartId);
        return onlineMallCart.getId();
    }

    @Override
    public ShoppingAfterSales findById(Long id) {
        ShoppingAfterSales shoppingAfterSales = shoppingAfterSalesService.getById(id);
        return shoppingAfterSales;
    }

    @Override
    public List<OnlineMallCart> selectDataExport(String thirdOrder) {
        List<OnlineMallCart> onlineMallCarts = cartService.selectDataExport(thirdOrder);
        List<DictDTO> deliver = dictClient.getDicByType("deliver_status");
        List<DictDTO> receipt = dictClient.getDicByType("receipt_status");

        Map<String, String> deliverStatus = deliver.stream().collect(Collectors.toMap(DictDTO::getCode,DictDTO::getName,(key1, key2)->key2));
        Map<String, String> receiptStatus = receipt.stream().collect(Collectors.toMap(DictDTO::getCode,DictDTO::getName,(key1,key2)->key2));



        for (OnlineMallCart onlineMallCart : onlineMallCarts) {
            onlineMallCart.setProvinceCityCounty(onlineMallCart.getProvinceName() + "/" + onlineMallCart.getCityName() + "/" + onlineMallCart.getCountyName());
            onlineMallCart.setDeliveryStatusText(deliverStatus.get(String.valueOf(onlineMallCart.getDeliveryStatus())));
            onlineMallCart.setReceiptStatusText(receiptStatus.get(String.valueOf(onlineMallCart.getReceiptStatus())));

        }

        return onlineMallCarts;
    }  

    @Override
    public void whetherCallOff(Long id, Integer whetherCallOff) {
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setId(id);
        List<CartPurchaseDTO> cartPurchaseDTOList = cartInfoService.getByCartId(id);
        //将prCode和itemCode合并为一个流用于判断
        List<String> codeList = cartPurchaseDTOList.stream()
//                .map(CartPurchaseDTO::getPrCode)
                .map(dto -> dto.getPrCode() + " - " + dto.getItemCode())
                .collect(Collectors.toList());
        if(whetherCallOff == 1){
            shoppingCart.setWhetherCallOff(2);
            cartPurchaseDTOList.forEach(cartPurchaseDTO -> {
                codeList.forEach(code -> {
                    if (code.equals(cartPurchaseDTO.getPrCode() + " - " + cartPurchaseDTO.getItemCode())){
                        BigDecimal cartQty = cartPurchaseDTO.getQty();
                        purchaseApplyBillDetailClient.updatePurchaseAppliyBillDetailForShoppingW(code,cartQty);
                    }
                });
            });

        }else{
            shoppingCart.setWhetherCallOff(1);
//            purchaseApplyBillDetailClient.updatePurchaseAppliyBillDetailForShoppingY(codeList,cartQty);
            cartPurchaseDTOList.forEach(cartPurchaseDTO -> {
                codeList.forEach(code -> {
                    if (code.equals(cartPurchaseDTO.getPrCode() + " - " + cartPurchaseDTO.getItemCode())){
                        BigDecimal cartQty = cartPurchaseDTO.getQty();
                        purchaseApplyBillDetailClient.updatePurchaseAppliyBillDetailForShoppingY(code,cartQty);
                    }
                });
            });
        }
        cartService.updateById(shoppingCart);
    }

    @Override
    public List<OnlineMallCart> selectDataExport1(OnlineMallCartQuery query) {
        List<OnlineMallCart> onlineMallCarts = cartService.selectDataExport1(query);
        List<DictDTO> deliver = dictClient.getDicByType("deliver_status");
        List<DictDTO> receipt = dictClient.getDicByType("receipt_status");

        Map<String, String> deliverStatus = deliver.stream().collect(Collectors.toMap(DictDTO::getCode,DictDTO::getName,(key1, key2)->key2));
        Map<String, String> receiptStatus = receipt.stream().collect(Collectors.toMap(DictDTO::getCode,DictDTO::getName,(key1,key2)->key2));



        for (OnlineMallCart onlineMallCart : onlineMallCarts) {
            onlineMallCart.setProvinceCityCounty(onlineMallCart.getProvinceName() + "/" + onlineMallCart.getCityName() + "/" + onlineMallCart.getCountyName());
            onlineMallCart.setDeliveryStatusText(deliverStatus.get(String.valueOf(onlineMallCart.getCartDeliveryStatus())));
            onlineMallCart.setReceiptStatusText(receiptStatus.get(String.valueOf(onlineMallCart.getReceiptStatus())));

        }

        return onlineMallCarts;
    }

    @Override
    public List<ShoppingAfterSalesPO> exportMyAfterSalesPage(MyAfterSalesQuery myAfterSalesQuery) {
        List<ShoppingAfterSalesPO> list = cartService.selectAsDataByQuery(null, myAfterSalesQuery);
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void noteSave(ShoppingAfterSalesInfo param) {
//        ShoppingAfterSales shoppingAfterSales = shoppingAfterSalesService.getByCartId(param.get)
        shoppingAfterSalesInfoService.saveOrUpdate(param);
    }

    @Override
    public ShoppingAfterSalesInfo findByInfoId(Long sasiId) {
        ShoppingAfterSalesInfo shoppingAfterSalesInfo  = shoppingAfterSalesInfoService.getById(sasiId);
        return shoppingAfterSalesInfo;
    }

    @Override
    public List<ShoppingCartInfoPO> detailListPage(Long cartId) {
        List<ShoppingCartInfoPO> list = shoppingCartInfoService.findByCartId(cartId);
//                list(new LambdaQueryWrapper<ShoppingCartInfo>()
//                .eq(ShoppingCartInfo::getCartId, cartId))
//                .leftJoin(ShoppingAfterSalesInfo.class, ShoppingCartInfo::getId, ShoppingAfterSalesInfo::getSalesId)
//                .select(ShoppingCartInfo::*, ShoppingAfterSalesInfo::getReturnQuatity);
        return list;
    }

    @Override
    public List<ShoppingCartInfoPO> detailListPagePO(Long cartId) {
        List<ShoppingCartInfoPO> poList = shoppingCartInfoService.getList(cartId);
        return poList;
    }

    @Override
    public OnlineMallCart findHeadById(Long cartId) {
        return cartService.findHeadById(cartId);
    }

    @Override
    public OnlineMallResponse pushPoToCart(Long id) {
        if (ObjectUtil.isNull(id)) {
            throw new DaoException("参数错误, 请联系管理员");
        }
        OnlineMallCartQuery query = new OnlineMallCartQuery();
        query.setCartId(id);
        OnlineMallCart dto = cartService.selectByQuery(query);

        ShoppingCart cart = cartService.getById(dto.getId());

        OnlineMallResponse response = new OnlineMallResponse();
        if ("XY".equals(dto.getStoreCode())) {
            //封装数据
            OnlineShoppingXyDto xyDto = dto.toXySc();
            String token = onlineMallService.findTokenByCart(dto.getStoreCode());
            xyDto.setToken(token);
            xyDto.setFactoryCode(dto.getFactoryCode());
            xyDto.setFactoryName(dto.getFactoryName());

            //查找详细
            List<ShoppingCartInfo> infoList = shoppingCartInfoService.list(new LambdaQueryWrapper<ShoppingCartInfo>().eq(ShoppingCartInfo::getCartId, cart.getId()));
            List<OnlineShoppingXyDto.Items> itemList = Lists.newArrayList();
            for (ShoppingCartInfo info : infoList) {
                OnlineShoppingXyDto.Items items = new OnlineShoppingXyDto.Items();
                items.setSkuId(info.getSkuCode());
                items.setNum(info.getQty().intValue());
                items.setPrice(info.getUnitCost().setScale(2, BigDecimal.ROUND_HALF_UP));
                items.setProductUnit(info.getUnit());
                itemList.add(items);
            }
            xyDto.setSku(itemList);

            response = onlineMallService.pushShoppingCartXy(cart, xyDto, LoginUtil.getAccount(), infoList);
        }
        if ("ZKH".equals(dto.getStoreCode())) {
            //封装数据
            OnlineShoppingZkhDto zkhDto = dto.toZkhSc();
            String token = onlineMallService.findTokenByCart(dto.getStoreCode());
            zkhDto.setToken(token);
            zkhDto.setFactoryCode(dto.getFactoryCode());
            zkhDto.setFactoryName(dto.getFactoryName());
            zkhDto.setPurchaseAccount(LoginUtil.getAccount());

            //查找详细
            List<ShoppingCartInfo> infoList = shoppingCartInfoService.list(new LambdaQueryWrapper<ShoppingCartInfo>().eq(ShoppingCartInfo::getCartId, cart.getId()));
            List<OnlineShoppingZkhDto.Items> itemList = Lists.newArrayList();
            for (ShoppingCartInfo info : infoList) {
                OnlineShoppingZkhDto.Items items = new OnlineShoppingZkhDto.Items();
                items.setSkuId(info.getSkuCode());
                items.setNum(info.getQty().intValue());
                items.setPrice(info.getUnitCost().setScale(2, BigDecimal.ROUND_HALF_UP));
                //items.setProductUnit(info.getUnit());
                itemList.add(items);
            }
            zkhDto.setSku(itemList);

            response = onlineMallService.pushShoppingCartZkh(cart, zkhDto, infoList);
        }
        return response;
    }

    @Override
    public void updateReceiptStatus(Long cartId, String rows) {
        ShoppingCart cart = cartService.getById(cartId);
        List<ShoppingCartInfo> infos = JSON.parseArray(rows, ShoppingCartInfo.class);
        List<ShoppingCartInfoDTO> infoDTOS = JSON.parseArray(rows, ShoppingCartInfoDTO.class);

            for (ShoppingCartInfoDTO shoppingCartInfoDTO : infoDTOS) {
               BigDecimal ThisReceiptNum = shoppingCartInfoDTO.getThisReceiptNum() == null ? BigDecimal.ZERO : shoppingCartInfoDTO.getThisReceiptNum();
                shoppingCartInfoDTO.setReceiptNum(shoppingCartInfoDTO.getReceiptNum().add(ThisReceiptNum));

            }


        List<ShoppingCartInfo> shoppingCartInfos = shoppingCartInfoConvert.dto2Entities(infoDTOS);
        Boolean f = false;
//        for (ShoppingCartInfo info : infos) {
//            info.setPurchaseDate(LocalDateTime.now());
//            info.setReceiptNum(info.getReceiptNum());
//            /**
//             * int c = b1.compareTo(b2);  // -1
//             * c=1表示b1大于b2
//             * c=0表示b1等于b2
//             * c=-1表示b1小于b2
//             */
//            if (info.getReceiptNum().compareTo(info.getQty()) == -1) {
//                f = true;
//                break;
//            }
//        }
        for (ShoppingCartInfoDTO info : infoDTOS) {
            info.setPurchaseDate(LocalDateTime.now());
            info.setReceiptNum(info.getReceiptNum());
            /**
             * int c = b1.compareTo(b2);  // -1
             * c=1表示b1大于b2
             * c=0表示b1等于b2
             * c=-1表示b1小于b2
             */
            BigDecimal ThisReceiptNum = info.getThisReceiptNum() == null ? BigDecimal.ZERO : info.getThisReceiptNum();
            if ((info.getReceiptNum().add(ThisReceiptNum)).compareTo(info.getQty()) == -1) {
                f = true;
                break;
            }
        }
        //部分收货
        if (f) {
            cart.setReceiptStatus(2);
        } else {
            cart.setReceiptStatus(1);
        }
        cartService.updateById(cart);
        shoppingCartInfoService.updateBatchById(shoppingCartInfos);
    }

    @Override
    public List<ExcelShopCartVO> excelShopCart(InputStream inputStream) {
        List<ExcelShopCartVO> costResultExcels =new ArrayList<>();
        List<Map<String,String>> dataList = EasyExcelImportUtils.parseExcelToData(inputStream, 2);
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(dataList)){
            for (Map<String,String> map : dataList){
                ExcelShopCartVO excelShopCartVO = new ExcelShopCartVO();
                excelShopCartVO.setSource(map.get("source"));
                excelShopCartVO.setSourceName(map.get("sourceName"));
                excelShopCartVO.setProductCode(map.get("productCode"));
                excelShopCartVO.setProductName(map.get("productName"));
                excelShopCartVO.setProductUnit(map.get("productUnit"));
                excelShopCartVO.setProductPrice(map.get("productPrice"));
                excelShopCartVO.setQty(map.get("qty"));
                excelShopCartVO.setPrCode(map.get("prCode"));
                excelShopCartVO.setPrItemNo(map.get("prItemNo"));
                excelShopCartVO.setRequireNum(map.get("requireNum"));
                excelShopCartVO.setMaterialName(map.get("materialName"));
                excelShopCartVO.setMaterialSpec(map.get("materialSpec"));
                costResultExcels.add(excelShopCartVO);
            }
        }

       /* ExcelReader excelReader = EasyExcel.read(inputStream).build();
        EasyExcelListener boxServerListener = new EasyExcelListener();
        ReadSheet readSheet0 = EasyExcel.readSheet(0).head(ExcelShopCartVO.class).registerReadListener(boxServerListener).build();
        excelReader.read(readSheet0);
        excelReader.finish();
        List<ExcelShopCartVO> costResultExcels = boxServerListener.getDatas();*/
        return costResultExcels;
    }


    @Override
    public OrderTrackResponse requestMiddleOrderTrack(String packageId) {
        OrderTrackResponse orderTrackResponse = onlineMallService.requestMiddleOrderTrack(packageId);
        return orderTrackResponse;
    }

    @Override
    public DelOrderResponse delOrder(Long id, String orderId) {
//        DelOrderResponse delOrderResponse =  onlineMallService.delOrder(id,orderId);

        // 接口调用日志信息
        String message = "";
        String token = onlineMallService.findTokenByCart("ZKH");
        DelOrderDto delOrderDto = new DelOrderDto();
        delOrderDto.setOrderId(orderId);
        delOrderDto.setToken(token);
        String paramJson = JSON.toJSONString(delOrderDto);
        DelOrderResponse response = null;
        try {
            LOGGER.info("取消订单信息接口, 调用参数为: {}", paramJson);
            //推送预订单
            String result = middleWareService.requestMiddleDelOrder(paramJson);
            LOGGER.info("取消订单信息接口, 本次调用返回结果为: {}", result);
            if (StringUtils.isNotEmpty(result)) {
                response = JSON.parseObject(result, DelOrderResponse.class);
                if (response.getSuccess()) {
                    if ("0000".equals(response.getResultCode())) {
                        //采购申请id
                        List<Long> detailIds = new ArrayList<>();
                        List<ShoppingCartInfo> list = cartInfoService.list(new LambdaQueryWrapper<ShoppingCartInfo>().eq(ShoppingCartInfo::getCartId, id));
                        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(list)) {
                            //拿到剩余数量和采购申请明细id
//                            BigDecimal remainQuantity = null;
                            List<PurchaseApplyBillDetailClientDTO> applyBillDetailList = new ArrayList<>();
                            list.forEach(item -> {
                                //查询采购申请明细信息
                                detailIds.add(item.getId());
                                PurchaseApplyBillDetailClientDTO applyBillDetail = purchaseApplyBillDetailClient.getByBillCodeAndItemCode(item.getPrCode(), item.getPrItemNo());
                                //查询采购申请明细信息
                                detailIds.add(applyBillDetail.getId());
                                BigDecimal remainQuantity = applyBillDetail.getRemainQuantity().add(item.getQty());
                                applyBillDetail.setRemainQuantity(remainQuantity);
                                applyBillDetailList.add(applyBillDetail);
                            });
                            //商城订单成功后回写采购明细表剩余数量
                            purchaseApplyBillDetailClient.updateRemainQuantity(applyBillDetailList);
                            //删除 -  删除 状态 =  待确认商城订单 的记录后，对应的采购申请 中 采购方式 = 空 &&  transfer_status = 1
                            purchaseApplyBillDetailClient.updatePuchaseMethode("", 1, detailIds);
                        }

                        cartService.removeById(id);
                        cartInfoService.remove(new LambdaQueryWrapper<ShoppingCartInfo>().eq(ShoppingCartInfo::getCartId, id));
                        return response;
                    }
                } else {
                    return response;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
        return response;
//        return delOrderResponse;
    }

    //列表主数据
    @Override
    public List<OnlineMallCart> listAllExport(OnlineMallCartQuery query) {
        List<OnlineMallCart> quotaManagementPOS = cartService.bidFindByPage(null, query);
        return onlineMallConvert.po2PageListDTO(quotaManagementPOS);
    }

    /**
     * 售后申请保存
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void afSaveOrUpdate(ShoppingAfterSalesDTO param) {

        ShoppingAfterSales shoppingAfterSales = onlineMallConvert.dtoToEntity(param);
        shoppingAfterSales.setOrderCode(param.getThirdOrder());
        shoppingAfterSales.setStatus(param.getSrmStatus());
        shoppingAfterSales.setCreateTime(LocalDateTime.now());
        shoppingAfterSalesService.save(shoppingAfterSales);

        //保存售后明细
        List<ShoppingAfterSalesInfo> shoppingAfterSalesInfos = new ArrayList<>(param.getItems().size());
        final List<ShoppingAfterSalesInfoDTO> shoppingAfterSalesInfoDTOS = param.getItems();
        for (ShoppingAfterSalesInfoDTO shoppingAfterSalesInfoDTO : shoppingAfterSalesInfoDTOS){
            if(Objects.nonNull(shoppingAfterSalesInfoDTO.getReturnQuatity())){
                shoppingAfterSalesInfoDTO.setRefundAmount(shoppingAfterSalesInfoDTO.getUnitCost().multiply(shoppingAfterSalesInfoDTO.getReturnQuatity()));
                shoppingAfterSalesInfoDTO.setSalesId(shoppingAfterSalesInfoDTO.getId());
                shoppingAfterSalesInfoDTO.setId(null);
                shoppingAfterSalesInfoDTO.setAfId(shoppingAfterSales.getId());
                ShoppingAfterSalesInfo inquiryMaterial = onlineMallConvert.DTO2Entity(shoppingAfterSalesInfoDTO);
                shoppingAfterSalesInfos.add(inquiryMaterial);
                shoppingAfterSalesInfoService.save(inquiryMaterial);
            }else{
                shoppingAfterSalesInfoDTO.setReturnQuatity(BigDecimal.valueOf(0));
                shoppingAfterSalesInfoDTO.setRefundAmount(shoppingAfterSalesInfoDTO.getUnitCost().multiply(shoppingAfterSalesInfoDTO.getReturnQuatity()));
                shoppingAfterSalesInfoDTO.setSalesId(shoppingAfterSalesInfoDTO.getId());
                shoppingAfterSalesInfoDTO.setId(null);
                ShoppingAfterSalesInfo inquiryMaterial = onlineMallConvert.DTO2Entity(shoppingAfterSalesInfoDTO);
                shoppingAfterSalesInfos.add(inquiryMaterial);
            }

//            shoppingAfterSalesInfoDTO.setSalesId(shoppingAfterSalesInfoDTO.getId());
//            shoppingAfterSalesInfoDTO.setId(null);
//            ShoppingAfterSalesInfo inquiryMaterial = onlineMallConvert.DTO2Entity(shoppingAfterSalesInfoDTO);
//            shoppingAfterSalesInfos.add(inquiryMaterial);
        }
        //售后单据推送震坤行获取返回售后单号
//        OnlineMallCartQuery query = new OnlineMallCartQuery();
//        query.setCartId(shoppingAfterSalesInfoDTO.getSalesId());
//        final OnlineMallCart cartDto = cartService.selectByQuery(query);

//        ShoppingCart cart1 = new ShoppingCart();
//        ShoppingAfterSales sales = new ShoppingAfterSales();
//        OnlineShoppingConfirmOrderXyDto orderDto = new OnlineShoppingConfirmOrderXyDto();
        ZkhMallDto orderDto = new ZkhMallDto();
        //商城返回订单号
        orderDto.setOrderNumber(param.getOrderId());
        //售后类型
        orderDto.setServiceType(Integer.valueOf(param.getAfterSalesType()));
        //售后申请原因
        orderDto.setDescription(param.getApplyReason());
        //售后方式
        orderDto.setReturnType(Integer.valueOf(param.getAfterSalesWay()));
        //申请人名称
        orderDto.setApplicant(param.getCreateUserName());
        //申请人电话
        orderDto.setApplicationPhone(param.getApplyTel());
        //申请时间
        String formattedDateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        orderDto.setApplicationTime(formattedDateTime);
        //售后商品集合
//        orderDto.detail_entity.setNum(param.get);
        // 声明并初始化空的售后商品集合
        List<ZkhMallDto.detail_entity> detailList = new ArrayList<>();



// 遍历产品列表，创建并添加售后商品对象到 detailList 中
        for (ShoppingAfterSalesInfoDTO product : param.getItems()) {
            ZkhMallDto.detail_entity detailEntity = new ZkhMallDto.detail_entity();
            detailEntity.setNum(product.getReturnQuatity());
//            detailEntity.setNum(product.getQty());
            detailEntity.setSkuId(product.getSkuCode());
            detailList.add(detailEntity);
        }
// 将 detailList 设置为 orderDto 的 detail 属性的值
        orderDto.setDetail(detailList);



        String token = onlineMallServiceImpl.findTokenByCart("ZKH");
//        orderDto.setToken("bearer " + token);
//        orderDto.setOrderId(param.getOrderId());
        String orderJson = JSON.toJSONString(orderDto);
        try {
            String result = middleWareService.requestMiddleConfirmOrder1(token,orderJson, "ZKH");
            LOGGER.info("售后申请商城订单(" + "震坤行" + ")订单, 本次调用返回结果为: {}", result);

            if (StringUtils.isNotEmpty(result)) {
                final ApplyProductResponse orderResponse = JSON.parseObject(result, ApplyProductResponse.class);
                String result1 = orderResponse.getResult();
//                String result1 = orderResponse.getResultMessage();
//                JSONObject jsonObject = JSON.parseObject(result1);
                if (orderResponse.getSuccess()) {
                    JSONObject jsonObject = JSON.parseObject(result1);
                    // 确认订单成功，更改商城以及订单状态
                    shoppingAfterSales.setStatus("2");
                    //除了String类型都要做非空判断，用三元运算式判断
//                    ObjectUtil.isNotNull(jsonObject.get("serviceId"))?jsonObject.getInteger("serviceId"):null;
                    shoppingAfterSales.setAfOrderCode(jsonObject.getString("serviceId"));
                    shoppingAfterSalesService.saveOrUpdate(shoppingAfterSales);
//                    return result1;

//                    sales.setCallbackDesc(orderResponse.getResultMessage());
                } else {
                    String result2 = orderResponse.getResultMessage();
//                    JSONObject jsonObject = JSON.parseObject(result2);
                    // 确认订单失败，更改商城以及订单状态
                    shoppingAfterSales.setStatus("3");
                    throw new DaoException("震坤行接口返回报错：" + result2);
//                    throw new DaoException("震坤行接口返回报错：" + jsonObject.getString("resultMessage"));
//                    sales.setCallbackDesc(orderResponse.getResultMessage());
                }
            } else {
                // 确认订单失败，更改商城以及订单状态
//                shoppingAfterSales.setStatus("4");
//                cart.setCallbackDesc("确认商城订单失败");
            }
            shoppingAfterSalesService.saveOrUpdate(shoppingAfterSales);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("售后申请发起失败, 原因: {}", e.getMessage(), e);
            throw new DaoException("售后申请发起失败, 原因: {" + e.getMessage() + "}");

            // 为了前端不会出现空指针异常
//            sales.setSrmStatus(7);
        }
//20240923注销，测试售后申请单是否报错
//        shoppingAfterSalesInfoService.saveBatch(shoppingAfterSalesInfos);
//        List<ShoppingAfterSalesInfoDTO> shoppingAfterSalesInfoDTO =
    }

    /**
     * 售后申请提交
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submit(ShoppingAfterSalesDTO param) {

    }

    @Override
    public PageView findMyAfterSalesPage(MyAfterSalesQuery query) {
        final Page<ShoppingAfterSales> page = PageUtil.toPage(query);
        List<ShoppingAfterSalesPO> list = cartService.selectAsDataByQuery(page, query);
        return PageUtil.getPV(list, page.getTotal());
    }

    @Override
    public List<ShoppingCartInfoPO> getShoppingCartInfoListPO(String billNo, String itemNO) {
        List<ShoppingCartInfoPO> poList = shoppingCartInfoService.getShoppingCartInfoListPO(billNo,itemNO);
        return poList;
    }

    /*@Override
    public void downLoad(HttpServletRequest request, HttpServletResponse response, List<ExcelShopCartVO> list) {
        {
            try {
                List<Map<String, String>> listMap = Lists.newArrayList();
                for (ExcelShopCartVO vo : list) {
                    Map<String, String> map = Maps.newHashMap();
                    map.put("商城编码", vo.getSource());
                    map.put("来源", vo.getSourceName());
                    map.put("商品编码", vo.getProductCode());
                    map.put("商品名称", vo.getProductName());
                    map.put("单位", vo.getProductUnit());
                    map.put("商品价格", vo.getProductPrice());
                    map.put("数量", vo.getQty());
                    map.put("采购申请单号", vo.getPrCode());
                    map.put("行号", vo.getPrItemNo());
                    map.put("请购数量", vo.getRequireNum());
                    map.put("物料描述", vo.getMaterialName());
                    map.put("规格", vo.getMaterialSpec());
                    listMap.add(map);
                }


                String[] titleAndKey = new String[]{"商城编码", "来源", "商品编码", "商品名称", "单位", "商品价格", "数量", "采购申请单号", "行号",
                        "请购数量", "物料描述","规格"};
                Integer[] cellLength = new Integer[]{12, 12, 12, 32, 12, 12, 12, 32, 12, 12,32, 18};
                String[] cellNumberFormat = new String[]{};

                String fileName = DateUtil.format(new Date(), "yyyyMMddHHmmssSSS");
                ExportExcelCommonUtil.setExcelResponseInfo(request, response, fileName);
                ExportExcelCommonUtil.exportExcel2(listMap, titleAndKey, titleAndKey, cellNumberFormat, cellLength,
                        response.getOutputStream());

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }*/
}
