package com.hzs.sale.order.controller.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hzs.common.core.constant.*;
import com.hzs.common.core.constant.msg.SaOrderMsgConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.utils.CommonUtil;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.core.web.controller.BaseController;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.core.web.domain.EnumEntity;
import com.hzs.common.core.web.page.TableDataInfo;
import com.hzs.common.domain.sale.deliver.SaDeliver;
import com.hzs.common.domain.sale.ext.SaOrderExt;
import com.hzs.common.domain.sale.ext.SaOrderItemsExt;
import com.hzs.common.domain.sale.order.SaOrder;
import com.hzs.common.domain.sale.order.SaOrderItems;
import com.hzs.common.domain.third.pay.ext.TOnlineRefundExt;
import com.hzs.common.security.auth.AuthMemberUtil;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.util.TransactionUtils;
import com.hzs.sale.deliver.service.ISaDeliverItemsService;
import com.hzs.sale.deliver.service.ISaDeliverService;
import com.hzs.sale.order.param.*;
import com.hzs.sale.order.service.IOrderBusinessService;
import com.hzs.sale.order.service.ISaOrderItemsService;
import com.hzs.sale.order.service.ISaOrderService;
import com.hzs.sale.order.vo.*;
import com.hzs.system.base.IAreaServiceApi;
import com.hzs.system.base.ICurrencyServiceApi;
import com.hzs.system.base.dto.CurrencyDTO;
import com.hzs.third.express.IExpressTrackService;
import com.hzs.third.express.dto.ExpressDTO;
import com.hzs.third.express.dto.ExpressDetail;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * 我的订单控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/my-order")
public class ApiOrderController extends BaseController {

    @Autowired
    private ISaOrderService iSaOrderService;
    @Autowired
    private ISaOrderItemsService iSaOrderItemsService;
    @Autowired
    private ISaDeliverService iSaDeliverService;
    @Autowired
    private IOrderBusinessService iOrderBusinessService;
    @Autowired
    private ISaDeliverItemsService saDeliverItemsService;

    @DubboReference
    ICurrencyServiceApi iCurrencyServiceApi;
    @DubboReference
    IAreaServiceApi iAreaServiceApi;
    @DubboReference
    IExpressTrackService iExpressTrackService;


    /**
     * 查询订单
     *
     * @return
     */
    @GetMapping("/order-type")
    public AjaxResult orderType() {
        // 查询订单类型
        List<Integer> orderTypeList = iSaOrderService.queryOrderType(SecurityUtils.getUserId(), SecurityUtils.getPkCountry());

        List<EnumEntity> enumEntityList = new ArrayList<>();
        for (EOrderType value : EOrderType.values()) {
            if (orderTypeList.contains(value.getValue())) {
                enumEntityList.add(new EnumEntity(value.getValue(), value.getLabel(), EnumsPrefixConstants.ORDER_TYPE));
            }
        }
        return AjaxResult.success(enumEntityList);
    }

    /**
     * 我的订单列表
     *
     * @param param 查询参数
     * @return
     */
    @GetMapping("/list")
    public TableDataInfo list(MyOrderParam param) {
        if (null != param.getCreationTimeStart()) {
            param.setCreationTimeStart(DateUtils.getStartTime(param.getCreationTimeStart()));
        }
        if (null != param.getCreationTimeEnd()) {
            param.setCreationTimeEnd(DateUtils.getEndTime(param.getCreationTimeEnd()));
        }

        // 所属国家
        Integer pkCountry = SecurityUtils.getPkCountry();
        // 会员ID
        Long userId = SecurityUtils.getUserId();
        // 返回的订单数据
        List<MyOrderVO> myOrderList = new ArrayList<>();

        startPage();
        List<SaOrderExt> orderList = iSaOrderService.myOrderList(param, userId, null);
        if (CollectionUtil.isNotEmpty(orderList)) {
            // 获取订单ID列表
            List<Long> orderIdList = new ArrayList<>();

            // 当前国家汇率
            CurrencyDTO currencyDTO = iCurrencyServiceApi.getCurrency(pkCountry).getData();

            for (SaOrderExt saOrderExt : orderList) {
                // 默认为直销订单
                orderIdList.add(saOrderExt.getPkId());
            }

            // 查询到的订单对应的订单明细列表
            List<SaOrderItemsExt> orderItemsList = iSaOrderItemsService.queryListByOrderId(orderIdList);

            // 调用system服务，获取地址
            Map<Integer, String> areaMap = iAreaServiceApi.getAreaMap(pkCountry).getData();

            // 遍历订单，转换成前台显示内容
            for (SaOrderExt saOrder : orderList) {
                // 返回订单数据
                MyOrderVO myOrder;
                // 订单明细状态
                Integer orderStatus = null;
                // 返回订单数据明细列表
                List<MyOrderItemsVO> myOrderItemsList = null;
                // 是否处理
                boolean isHandle = false;

                // 遍历订单明细，转换成前台显示内容
                for (SaOrderItemsExt saOrderItems : orderItemsList) {
                    if (EOrderStatus.SHIPPING.getValue() == saOrderItems.getOrderStatus()) {
                        // 已合单显示为已付款，因为合单为后台状态，前台不需要显示
                        saOrderItems.setOrderStatus(EOrderStatus.PAY.getValue());
                    }

                    // 当前订单明细处理
                    if (saOrderItems.getPkOrder().equals(saOrder.getPkId())) {
                        // 订单明细状态分组处理
                        if (!saOrderItems.getOrderStatus().equals(orderStatus)) {
                            // 明细状态不相同，则需要新建
                            orderStatus = saOrderItems.getOrderStatus();
                            // 处理订单
                            myOrder = BeanUtil.copyProperties(saOrder, MyOrderVO.class);
                            // 2024.07.09 新需求，如果有服务编码优先使用
                            if (userId.equals(myOrder.getPkCreator())) {
                                // 当前会员就是订单支付人，会员名称不做处理
                                myOrder.setCreatorName(saOrder.getCreatorName());
                                myOrder.setCreatorCode(saOrder.getCreatorCode());
                            } else {
                                myOrder.setCreatorName(CommonUtil.getMemberName(saOrder.getCreatorPkVertex(), saOrder.getCreatorName(), saOrder.getCreatorNickName()));
                                myOrder.setCreatorCode(CommonUtil.getMemberCode(saOrder.getCreatorCode(), saOrder.getCreatorServiceCode()));
                            }

                            if (userId.equals(myOrder.getPkMember())) {
                                // 当前会员就是订单会员，会员名称不做处理
                                myOrder.setMemberName(saOrder.getMemberName());
                                myOrder.setMemberCode(saOrder.getMemberCode());
                            } else {
                                myOrder.setMemberName(CommonUtil.getMemberName(saOrder.getMemberPkVertex(), saOrder.getMemberName(), saOrder.getMemberNickName()));
                                myOrder.setMemberCode(CommonUtil.getMemberCode(saOrder.getMemberCode(), saOrder.getMemberServiceCode()));
                            }

                            // 前台显示状态为明细状态
                            myOrder.setOrderStatus(saOrderItems.getOrderStatus());
                            // 订单显示金额 = 订单金额 + 运费
                            myOrder.setOrderAmount(myOrder.getOrderAmount().add(myOrder.getPostage()));
                            // 登录会员如果是中国会员，订单显示人民币业绩
                            myOrder.setOrderAchieve(myOrder.getOrderAchieve().multiply(currencyDTO.getInExchangeRate()));

                            String recProvince = areaMap.get(saOrder.getRecProvince());
                            if (StringUtils.isNotEmpty(recProvince)) {
                                myOrder.setRecProvince(recProvince);
                            }
                            String recCity = areaMap.get(saOrder.getRecCity());
                            if (StringUtils.isNotEmpty(recCity)) {
                                myOrder.setRecCity(recCity);
                            }
                            String recCounty = areaMap.get(saOrder.getRecCounty());
                            if (StringUtils.isNotEmpty(recCounty)) {
                                myOrder.setRecCounty(recCounty);
                            }
                            myOrder.setAddress(saOrder.getRecAddress());

                            // 处理订单明细
                            myOrderItemsList = new ArrayList<>();
                            myOrderItemsList.add(BeanUtil.copyProperties(saOrderItems, MyOrderItemsVO.class));
                            myOrder.setItemList(myOrderItemsList);

                            myOrderList.add(myOrder);
                        } else {
                            // 明细状态相同，直接追加
                            myOrderItemsList.add(BeanUtil.copyProperties(saOrderItems, MyOrderItemsVO.class));
                        }

                        // 订单ID处理过
                        isHandle = true;
                        continue;
                    }
                    if (isHandle) {
                        // 订单明细遍历，如果订单曾经处理过，则此处跳出本次订单明细遍历
                        break;
                    }
                }
            }
        }

        TableDataInfo tableDataInfo = getDataTable(orderList);
        tableDataInfo.setRows(myOrderList);
        return tableDataInfo;
    }

    @GetMapping("/refund-list")
    public TableDataInfo refundList() {
        // 返回结果
        startPage();
        List<TOnlineRefundExt> list = iSaOrderService.queryRefundList();
        TableDataInfo tableDataInfo = getDataTable(list);
        tableDataInfo.setRows(list);
        return tableDataInfo;
    }
    /**
     * 订单详情
     *
     * @param orderCode 订单编号
     * @return
     */
    @GetMapping("/detail/{orderCode}")
    public AjaxResult detail(@PathVariable("orderCode") String orderCode) {
        // 所属国家
        Integer pkCountry = SecurityUtils.getPkCountry();

        // 返回数据
        MyOrderVO myOrder = new MyOrderVO();

        // 查询订单以及详情
        SaOrderExt saOrder = iSaOrderService.queryOrderByCode(orderCode, pkCountry);
        if (null != saOrder) {
            // 直销订单处理
            myOrder = this.handleSaOrderDetail(saOrder, pkCountry);
        }
        return AjaxResult.success(myOrder);
    }

    /**
     * 我的订单数量
     *
     * @return
     */
    @GetMapping("/num")
    public AjaxResult num() {
        Long userId = SecurityUtils.getUserId();
        Integer pkCountry = SecurityUtils.getPkCountry();
        return AjaxResult.success(MyOrderNumVO.builder()
                // 待付款数量
                .waitPayNum(iSaOrderService.myOrderNum(Collections.singletonList(EOrderStatus.WAIT_PAY.getValue()), userId, pkCountry))
                // 已付款数量
                .payNum(iSaOrderService.myOrderNum(Arrays.asList(EOrderStatus.PAY.getValue(), EOrderStatus.SHIPPING.getValue()), userId, pkCountry))
                .build());
    }

    /**
     * 订单物流信息
     *
     * @param orderCode
     * @return
     */
    @GetMapping("/express/{orderCode}")
    public AjaxResult express(@PathVariable("orderCode") String orderCode) {
        // 物流返回信息
        List<MyOrderExpressVO> resultList = new ArrayList<>();

        // 当前用户
        Long userId = SecurityUtils.getUserId();

        LambdaQueryWrapper<SaOrder> orderQueryWrapper = new LambdaQueryWrapper<>();
        orderQueryWrapper.eq(SaOrder::getOrderCode, orderCode).and(wrapper -> wrapper.eq(SaOrder::getPkMember, userId).or().eq(SaOrder::getPkCreator, userId));
        SaOrder saOrder = iSaOrderService.getOne(orderQueryWrapper);
        if (null != saOrder) {
            // 查询订单
            List<SaOrderItems> deliverList = iSaOrderItemsService.queryDeliverByOrder(saOrder.getPkId());
            if (CollectionUtil.isNotEmpty(deliverList)) {
                for (SaOrderItems orderItems : deliverList) {
                    if (null != orderItems && StringUtils.isNotEmpty(orderItems.getLogisticsCode())) {
                        String[] logisticsCodeArray = orderItems.getLogisticsCode().split(",");

                        for (String logisticsCode : logisticsCodeArray) {
                            R<ExpressDTO> expressDTOR = iExpressTrackService.expressTrackInfo(logisticsCode, saOrder.getRecPhone());
                            if (expressDTOR.isSuccess()) {
                                ExpressDTO expressDTO = expressDTOR.getData();

                                List<MyOrderExpressDetailVO> detailList = new ArrayList<>();
                                for (ExpressDetail expressDetail : expressDTO.getExpressDetails()) {
                                    detailList.add(MyOrderExpressDetailVO.builder()
                                            .time(expressDetail.getTime())
                                            .context(expressDetail.getContext())
                                            .build());
                                }

                                resultList.add(MyOrderExpressVO.builder()
                                        .expressCode(logisticsCode)
                                        .expressName(orderItems.getLogisticsCompany())
                                        .logisticsStatus(expressDTO.getLogisticsStatus())
                                        .detailList(detailList)
                                        .build());
                            }
                        }
                    }
                }
            }
            return AjaxResult.success(resultList);
        }
        return AjaxResult.error(TransactionUtils.getContent(SaOrderMsgConstants.ORDER_NOT_EXIST));
    }

    /**
     * 确认收货
     *
     * @param orderCode
     * @return
     */
    @PutMapping("/confirm/{orderCode}")
    public AjaxResult confirm(@PathVariable("orderCode") String orderCode) {
        Long userId = SecurityUtils.getUserId();

        LambdaQueryWrapper<SaOrder> orderQueryWrapper = new LambdaQueryWrapper<>();
        orderQueryWrapper.eq(SaOrder::getOrderCode, orderCode).and(wrapper -> wrapper.eq(SaOrder::getPkMember, userId).or().eq(SaOrder::getPkCreator, userId));
        SaOrder saOrder = iSaOrderService.getOne(orderQueryWrapper);
        if (null != saOrder) {
            if (EOrderStatus.DELIVERED.getValue() != saOrder.getOrderStatus()) {
                // 订单状态不为待收货
                return AjaxResult.error(TransactionUtils.getContent(SaOrderMsgConstants.ORDER_STATUS_NOT));
            }
            return toAjax(iSaOrderService.myOrderConfirm(saOrder.getPkId(), userId));
        }
        return AjaxResult.error(TransactionUtils.getContent(SaOrderMsgConstants.ORDER_NOT_EXIST));
    }

    /**
     * 取消订单
     *
     * @param orderCode
     * @return
     */
    @DeleteMapping("/cancel/{orderCode}")
    public AjaxResult cancel(@PathVariable("orderCode") String orderCode) {
        Long userId = SecurityUtils.getUserId();

        LambdaQueryWrapper<SaOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SaOrder::getOrderCode, orderCode).and(wrapper -> wrapper.eq(SaOrder::getPkMember, userId).or().eq(SaOrder::getPkCreator, userId));
        SaOrder saOrder = iSaOrderService.getOne(queryWrapper);
        if (null != saOrder) {
            if (EOrderStatus.WAIT_PAY.getValue() != saOrder.getOrderStatus()) {
                // 订单状态不为待收货
                return AjaxResult.error(TransactionUtils.getContent(SaOrderMsgConstants.ORDER_STATUS_NOT));
            }

            String str = iSaOrderService.myOrderCancel(saOrder, userId);
            if (null == str) {
                return AjaxResult.success();
            }
            return AjaxResult.error(str);
        }
        return AjaxResult.error(TransactionUtils.getContent(SaOrderMsgConstants.ORDER_NOT_EXIST));
    }

    /**
     * 校验是否能支付
     *
     * @param orderCode 订单编号
     * @return
     */
    @GetMapping("/pay-check/{orderCode}")
    public AjaxResult payCheck(@PathVariable("orderCode") String orderCode) {
        if (iSaOrderItemsService.checkOrderItemsPutOn(orderCode) > 0) {
            // 订单下商品已下架，不能购买
            return AjaxResult.error(TransactionUtils.getContent(SaOrderMsgConstants.ORDER_ITEM_OFF));
        }
        return AjaxResult.success();
    }

    /**
     * 自助服务-修改地址订单列表
     **/
    @GetMapping("/selflist")
    public TableDataInfo selflist(MyOrderParam param) {
        if (null != param.getCreationTimeStart()) {
            param.setCreationTimeStart(DateUtils.getStartTime(param.getCreationTimeStart()));
        }
        if (null != param.getCreationTimeEnd()) {
            param.setCreationTimeEnd(DateUtils.getEndTime(param.getCreationTimeEnd()));
        }

        // 所属国家
        Integer pkCountry = SecurityUtils.getPkCountry();
        // 返回的订单数据
        List<CanApplyOrderVO> myOrderList = new ArrayList<>();

        startPage();
        param.setEditType(EApprovalBusiness.SELF_MODIFY_ADDRESS.getValue());
        List<SaOrderExt> orderList = iSaOrderService.selfAddressOrderList(param, SecurityUtils.getUserId(), pkCountry);
        orderList.forEach(item -> myOrderList.add(BeanUtil.copyProperties(item, CanApplyOrderVO.class)));
        if (CollectionUtil.isNotEmpty(myOrderList)) {
            // 获取订单ID列表
            List<Long> orderIdList = new ArrayList<>();
            for (SaOrderExt saOrderExt : orderList) {
                orderIdList.add(saOrderExt.getPkId());
            }
            // 查询订单商品明细列表
            List<WaresOrderVo> waresAllList = iSaOrderItemsService.waresListByOrderId(orderIdList);
            // 查询订单产品明细列表
            List<SaOrderItemsExt> productAllList = iSaOrderItemsService.queryListByOrderId(orderIdList);
            Map<Integer, String> areaMap = iAreaServiceApi.getAreaMap(pkCountry).getData();
            myOrderList.forEach(itm -> {
                //处理昵称和服务编号
                if (itm.getPkMember() != null && !itm.getPkMember().equals(itm.getPkCreator())) {
                    itm.setMemberCode(CommonUtil.getMemberCode(itm.getMemberCode(), itm.getMemberServiceCode()));
                    itm.setMemberName(CommonUtil.getMemberName(itm.getMemberPkVertex(), itm.getMemberName(), itm.getMemberNickName()));
                }
                itm.setSpecialArea(itm.getOrderType());
                String recProvince = areaMap.get(itm.getRecProvince());
                if (StringUtils.isNotEmpty(recProvince)) {
                    itm.setRecProvinceVal(recProvince);
                }
                String recCity = areaMap.get(itm.getRecCity());
                if (StringUtils.isNotEmpty(recCity)) {
                    itm.setRecCityVal(recCity);
                }
                String recCounty = areaMap.get(itm.getRecCounty());
                if (StringUtils.isNotEmpty(recCounty)) {
                    itm.setRecCountyVal(recCounty);
                }
                List<OrderItemsParam> orderItemsParams = new ArrayList<>();
                if (CollectionUtil.isNotEmpty(waresAllList)) {
                    for (WaresOrderVo wo : waresAllList) {
                        if (wo.getPkOrder().intValue() == itm.getPkId().intValue()) {
                            OrderItemsParam oip = BeanUtil.copyProperties(wo, OrderItemsParam.class);
                            if (CollectionUtil.isNotEmpty(productAllList)) {
                                List<WaresItemsParam> waresItemsParamList = new ArrayList<>();
                                for (SaOrderItemsExt saOrderItems : productAllList) {
                                    WaresItemsParam wip = BeanUtil.copyProperties(saOrderItems, WaresItemsParam.class);
                                    if (wo.getPkOrder().intValue() == saOrderItems.getPkOrder().intValue() &&
                                            wo.getPkWares().intValue() == saOrderItems.getPkWares().intValue()) {
                                        waresItemsParamList.add(wip);
                                    }
                                    if (itm.getPkId().intValue() == saOrderItems.getPkOrder().intValue()) {
                                        itm.setOrderStatus(saOrderItems.getOrderStatus());
                                    }
                                }
                                oip.setWaresItemsParamList(waresItemsParamList);
                                orderItemsParams.add(oip);
                                itm.setOrderItemsParams(orderItemsParams);
                            }
                        }
                    }
                }
            });
        }
        TableDataInfo tableDataInfo = getDataTable(orderList);
        tableDataInfo.setRows(myOrderList);
        return tableDataInfo;
    }

    /**
     * 自助业务-订单自提订单列表
     **/
    @GetMapping("/self-list")
    public TableDataInfo selfOrderList(MyOrderParam param) {
        // 所属国家
        Integer pkCountry = SecurityUtils.getPkCountry();
        // 返回的订单数据
        List<OrderSelfPickupVO> myOrderList = new ArrayList<>();

        startPage();
        List<SaOrderExt> orderList = iSaOrderService.selfOrderList(param, SecurityUtils.getUserId(), pkCountry);
        param.setEditType(EApprovalBusiness.SELF_DELIVERY_MANAGE.getValue());
        orderList.forEach(item -> myOrderList.add(BeanUtil.copyProperties(item, OrderSelfPickupVO.class)));
        if (CollectionUtil.isNotEmpty(myOrderList)) {
            Map<Integer, String> areaMap = iAreaServiceApi.getAreaMap(pkCountry).getData();
            // 获取订单ID列表
            List<Long> orderIdList = new ArrayList<>();
            for (SaOrderExt saOrderExt : orderList) {
                orderIdList.add(saOrderExt.getPkId());
            }
            // 查询订单商品明细列表
            List<WaresOrderVo> waresAllList = iSaOrderItemsService.waresListByOrderId(orderIdList);
            // 查询订单产品明细列表
            List<SaOrderItemsExt> productAllList = iSaOrderItemsService.queryListByOrderId(orderIdList);

            Iterator<OrderSelfPickupVO> ii = myOrderList.iterator();
            // 遍历订单，转换成前台显示内容
            while (ii.hasNext()) {
                OrderSelfPickupVO saOrder = ii.next();
                //处理昵称和服务编号
                if (saOrder.getPkMember() != null && !saOrder.getPkMember().equals(saOrder.getPkCreator())) {
                    saOrder.setMemberCode(CommonUtil.getMemberCode(saOrder.getMemberCode(), saOrder.getMemberServiceCode()));
                    saOrder.setMemberName(CommonUtil.getMemberName(saOrder.getMemberPkVertex(), saOrder.getMemberName(), saOrder.getMemberNickName()));
                }

                //处理订单收货地址
                String recProvince = areaMap.get(saOrder.getRecProvince());
                if (StringUtils.isNotEmpty(recProvince)) {
                    saOrder.setRecProvinceVal(recProvince);
                }
                String recCity = areaMap.get(saOrder.getRecCity());
                if (StringUtils.isNotEmpty(recCity)) {
                    saOrder.setRecCityVal(recCity);
                }
                String recCounty = areaMap.get(saOrder.getRecCounty());
                if (StringUtils.isNotEmpty(recCounty)) {
                    saOrder.setRecCountyVal(recCounty);
                }
                saOrder.setRecAddress(saOrder.getRecAddress());
                List<WaresOrderVo> waresList = new ArrayList<>();
                if (CollectionUtil.isNotEmpty(waresAllList)) {
                    for (WaresOrderVo wo : waresAllList) {
                        // 返回订单数据明细列表
                        List<MyOrderItemsVO> myOrderItemsList = new ArrayList<>();
                        if (CollectionUtil.isNotEmpty(productAllList)) {
                            for (SaOrderItemsExt saOrderItems : productAllList) {
                                if (wo.getPkOrder().intValue() == saOrderItems.getPkOrder().intValue() &&
                                        wo.getPkWares().intValue() == saOrderItems.getPkWares().intValue()) {
                                    // 遍历订单明细，转换成前台显示内容
                                    if (EOrderStatus.SHIPPING.getValue() == saOrderItems.getOrderStatus()) {
                                        // 已合单显示为已付款，因为合单为后台状态，前台不需要显示
                                        saOrderItems.setOrderStatus(EOrderStatus.PAY.getValue());
                                    }
                                    if (saOrder.getPkId().intValue() == saOrderItems.getPkOrder().intValue()) {
                                        saOrder.setOrderStatus(saOrderItems.getOrderStatus());
                                    }
                                    myOrderItemsList.add(BeanUtil.copyProperties(saOrderItems, MyOrderItemsVO.class));
                                }
                            }
                        }
                        wo.setProductList(myOrderItemsList);
                        if (wo.getPkOrder().intValue() == saOrder.getPkId().intValue()) {
                            waresList.add(wo);
                        }
                    }
                    saOrder.setWaresOrderList(waresList);
                }
                if (EOrderStatus.RECEIVED.getValue() == saOrder.getOrderStatus()) {
                    ii.remove();
                }
            }
        }
        TableDataInfo tableDataInfo = getDataTable(orderList);
        tableDataInfo.setRows(myOrderList);
        return tableDataInfo;
    }

    /**
     * 订单详情处理
     *
     * @param saOrder   订单信息
     * @param pkCountry 所属国家
     * @return
     */
    private MyOrderVO handleSaOrderDetail(SaOrderExt saOrder, Integer pkCountry) {
        // 调用system服务，获取地址
        Map<Integer, String> areaMap = iAreaServiceApi.getAreaMap(pkCountry).getData();

        MyOrderVO myOrder = BeanUtil.copyProperties(saOrder, MyOrderVO.class);
        // 订单明细
        List<MyOrderItemsVO> itemList = new ArrayList<>();
        for (SaOrderItemsExt saOrderItems : saOrder.getOrderItemsExtList()) {
            itemList.add(BeanUtil.copyProperties(saOrderItems, MyOrderItemsVO.class));
        }
        myOrder.setItemList(itemList);

        // 省市县处理
        String recProvince = areaMap.get(saOrder.getRecProvince());
        if (StringUtils.isNotEmpty(recProvince)) {
            myOrder.setRecProvince(recProvince);
        }
        String recCity = areaMap.get(saOrder.getRecCity());
        if (StringUtils.isNotEmpty(recCity)) {
            myOrder.setRecCity(recCity);
        }
        String recCounty = areaMap.get(saOrder.getRecCounty());
        if (StringUtils.isNotEmpty(recCounty)) {
            myOrder.setRecCounty(recCounty);
        }
        myOrder.setAddress(saOrder.getRecAddress());

        // 直销订单处理
        // 汇率（目前只有中国需要由美金转人民币显示，其它国家显示就是美金不需要转换）
        BigDecimal baseExchangeRate = saOrder.getInExchangeRate();
        if (null != baseExchangeRate) {
            // 基础汇率不为空，则进行转换
            myOrder.setOrderAchieve(myOrder.getOrderAchieve().multiply(baseExchangeRate));
            for (MyOrderItemsVO myOrderItemsVO : myOrder.getItemList()) {
                myOrderItemsVO.setAchievement(myOrderItemsVO.getAchievement().multiply(baseExchangeRate));
            }
        }

        List<SaDeliver> deliverList = new ArrayList<>();
        // 查询物流信息
        List<SaDeliver> queryDeliverList = iSaDeliverService.queryDeliverByOrder(saOrder.getPkId());
        for (SaDeliver querySaDeliver : queryDeliverList) {
            String[] logisticsCode = querySaDeliver.getLogisticsCode().split(",");
            for (String code : logisticsCode) {
                SaDeliver saDeliver = new SaDeliver();
                saDeliver.setLogisticsCode(code);
                saDeliver.setLogisticsCompany(querySaDeliver.getLogisticsCompany());
                deliverList.add(saDeliver);
            }
        }
        myOrder.setDeliverList(deliverList);

        return myOrder;
    }

    /**
     * 自助撤单列表(24点内)
     **/
    @GetMapping("/selfRevokeList")
    public TableDataInfo selfRevokeList(MyOrderParam param) {
        if (null != param.getCreationTimeStart()) {
            param.setCreationTimeStart(DateUtils.getStartTime(param.getCreationTimeStart()));
        }
        if (null != param.getCreationTimeEnd()) {
            param.setCreationTimeEnd(DateUtils.getEndTime(param.getCreationTimeEnd()));
        }

        // 所属国家
        Integer pkCountry = SecurityUtils.getPkCountry();
        // 返回的订单数据
        List<MyOrderVO> myOrderList = new ArrayList<>();

        startPage();
        param.setOrderStatus(EOrderStatus.PAY.getValue());
        List<SaOrderExt> orderList = iSaOrderService.selfRevokeOrderList(param, SecurityUtils.getUserId(), null);
        if (CollectionUtil.isNotEmpty(orderList)) {
            // 获取订单ID列表
            List<Long> orderIdList = new ArrayList<>();

            for (SaOrderExt saOrderExt : orderList) {
                // 默认为直销订单
                orderIdList.add(saOrderExt.getPkId());
                //处理昵称和服务编号
                if (saOrderExt.getPkMember() != null && !saOrderExt.getPkMember().equals(saOrderExt.getPkCreator())) {
                    saOrderExt.setMemberCode(CommonUtil.getMemberCode(saOrderExt.getMemberCode(), saOrderExt.getMemberServiceCode()));
                    saOrderExt.setMemberName(CommonUtil.getMemberName(saOrderExt.getMemberPkVertex(), saOrderExt.getMemberName(), saOrderExt.getMemberNickName()));
                }
            }

            // 查询到的订单对应的订单明细列表
            List<SaOrderItemsExt> orderItemsList = iSaOrderItemsService.queryListByOrderId(orderIdList);

            // 调用system服务，获取地址
            Map<Integer, String> areaMap = iAreaServiceApi.getAreaMap(pkCountry).getData();

            // 遍历订单，转换成前台显示内容
            for (SaOrderExt saOrder : orderList) {
                // 返回订单数据
                MyOrderVO myOrder;
                // 订单明细状态
                Integer orderStatus = null;
                // 返回订单数据明细列表
                List<MyOrderItemsVO> myOrderItemsList = null;
                // 是否处理
                boolean isHandle = false;
                // 汇率（目前只有中国需要由美金转人民币显示，其它国家显示就是美金不需要转换）
                BigDecimal baseExchangeRate = saOrder.getInExchangeRate();

                // 遍历订单明细，转换成前台显示内容
                for (SaOrderItemsExt saOrderItems : orderItemsList) {
                    if (EOrderStatus.SHIPPING.getValue() == saOrderItems.getOrderStatus()) {
                        // 已合单显示为已付款，因为合单为后台状态，前台不需要显示
                        saOrderItems.setOrderStatus(EOrderStatus.PAY.getValue());
                    }

                    // 当前订单明细处理
                    if (saOrderItems.getPkOrder().equals(saOrder.getPkId())) {
                        // 订单明细状态分组处理
                        if (!saOrderItems.getOrderStatus().equals(orderStatus)) {
                            // 明细状态不相同，则需要新建
                            orderStatus = saOrderItems.getOrderStatus();
                            // 处理订单
                            myOrder = BeanUtil.copyProperties(saOrder, MyOrderVO.class);
                            //处理昵称和服务编号
                            if (myOrder.getPkMember() != null && !saOrder.getPkMember().equals(saOrder.getPkCreator())) {
                                myOrder.setMemberCode(CommonUtil.getMemberCode(saOrder.getMemberCode(), saOrder.getMemberServiceCode()));
                                myOrder.setMemberName(CommonUtil.getMemberName(saOrder.getMemberPkVertex(), saOrder.getMemberName(), saOrder.getMemberNickName()));
                            }
                            // 前台显示状态为明细状态
                            myOrder.setOrderStatus(saOrderItems.getOrderStatus());
                            // 订单显示金额 = 订单金额 + 运费
                            myOrder.setOrderAmount(myOrder.getOrderAmount().add(myOrder.getPostage()));
                            // 如果是中国订单
                            myOrder.setOrderAchieve(myOrder.getOrderAchieve().multiply(baseExchangeRate));

                            String recProvince = areaMap.get(saOrder.getRecProvince());
                            if (StringUtils.isNotEmpty(recProvince)) {
                                myOrder.setRecProvince(recProvince);
                            }
                            String recCity = areaMap.get(saOrder.getRecCity());
                            if (StringUtils.isNotEmpty(recCity)) {
                                myOrder.setRecCity(recCity);
                            }
                            String recCounty = areaMap.get(saOrder.getRecCounty());
                            if (StringUtils.isNotEmpty(recCounty)) {
                                myOrder.setRecCounty(recCounty);
                            }
                            myOrder.setAddress(saOrder.getRecAddress());

                            // 处理订单明细
                            myOrderItemsList = new ArrayList<>();
                            myOrderItemsList.add(BeanUtil.copyProperties(saOrderItems, MyOrderItemsVO.class));
                            myOrder.setItemList(myOrderItemsList);

                            myOrderList.add(myOrder);
                        } else {
                            // 明细状态相同，直接追加
                            myOrderItemsList.add(BeanUtil.copyProperties(saOrderItems, MyOrderItemsVO.class));
                        }

                        // 订单ID处理过
                        isHandle = true;
                        continue;
                    }
                    if (isHandle) {
                        // 订单明细遍历，如果订单曾经处理过，则此处跳出本次订单明细遍历
                        break;
                    }
                }
            }
        }

        TableDataInfo tableDataInfo = getDataTable(orderList);
        tableDataInfo.setRows(myOrderList);
        return tableDataInfo;
    }

    /**
     * 自动撤单参数校验
     **/
    @PostMapping("/check-self-revoke-order")
    public AjaxResult checkSelfRevokeOrder(@RequestBody MyOrderVO myOrderVO) {
        // 验证订单编号、订单类型是否存在
        if (StringUtils.isEmpty(myOrderVO.getOrderCode())) {
            return AjaxResult.error(TransactionUtils.getContent(SaOrderMsgConstants.ORDER_CODE_EMPTY));
        }
        List<Long> itemIdList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(myOrderVO.getItemList())) {
            myOrderVO.getItemList().forEach(itm -> {
                itemIdList.add(itm.getPkId());
            });
        }
        if (saDeliverItemsService.validateOrderBindBarCode(myOrderVO.getOrderCode(), itemIdList)) {
            return AjaxResult.error(TransactionUtils.getContent(SaOrderMsgConstants.ORDER_BIND_BAR_CODE));
        }
        return AjaxResult.success();
    }

    /**
     * 自助撤单
     **/
    @PostMapping("/self-revoke-order")
    public AjaxResult selfRevokeOrder(@RequestBody MyOrderVO myOrderVO, HttpServletRequest request) {
        Long userId = SecurityUtils.getUserId();
        myOrderVO = iOrderBusinessService.checkSelfOrder(userId, myOrderVO);
        if (StringUtils.isNotEmpty(myOrderVO.getMsg())) {
            return AjaxResult.error(myOrderVO.getMsg());
        }
        iSaOrderService.selfRevokeOrder(userId, myOrderVO);
        //注册订单强制退出登录
        if (myOrderVO.getOrderType() == EOrderType.REGISTER_ORDER.getValue() ||
                myOrderVO.getOrderType() == EOrderType.SPECIAL_REGISTER_ORDER.getValue()) {
            if (userId.equals(myOrderVO.getPkMember())) {
                String token = SecurityUtils.getToken(request);
                if (StringUtils.isNotEmpty(token)) {
                    // 删除用户缓存记录
                    AuthMemberUtil.logoutByToken(token);
                }
            }
        }
        return AjaxResult.success();
    }

}
