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.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.*;
import java.util.stream.Collectors;

/**
 * @Description: 我的订单控制器
 * @Author: jiang chao
 * @Time: 2023/1/13 15:53
 * @Classname: ApiOrderController
 * @PackageName: com.hzs.sale.order.controller.api
 */
@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()));
        }
        // 会员ID
        Long userId = SecurityUtils.getUserId();
        // 返回的订单数据
        List<MyOrderVO> myOrderList = new ArrayList<>();

        startPage();
        List<SaOrderExt> orderList = iSaOrderService.myOrderList(param, userId, null);

        // 处理订单返回
        this.handleOrderReturn(orderList, myOrderList);

        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;
                        if (orderItems.getLogisticsCode().contains("/")) {
                            logisticsCodeArray = orderItems.getLogisticsCode().split("/");
                        } else {
                            logisticsCodeArray = orderItems.getLogisticsCode().split(",");
                        }

                        for (String logisticsCode : logisticsCodeArray) {
                            R<ExpressDTO> expressResult = iExpressTrackService.expressTrackInfo(logisticsCode, saOrder.getRecPhone());
                            if (expressResult.isSuccess()) {
                                ExpressDTO expressDTO = expressResult.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());
                            } else {
                                resultList.add(MyOrderExpressVO.builder()
                                        .expressCode(logisticsCode)
                                        .expressName(orderItems.getLogisticsCompany())
                                        .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();
    }

    /**
     * @description: 自助服务-修改地址订单列表
     * @author: zhang jing
     * @date: 2023/5/11 16:03
     * @param: [param]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @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<>();
        // 调用system服务，获取地址
        Map<Integer, String> areaMap = iAreaServiceApi.getAreaMap(pkCountry).getData();

        startPage();
        List<SaOrderExt> orderList = iSaOrderService.selfAddressOrderList(param, SecurityUtils.getUserId(), pkCountry);
        // 当前国家汇率
        CurrencyDTO currencyDTO = iCurrencyServiceApi.getCurrency(pkCountry).getData();
        orderList.forEach(item -> myOrderList.add(BeanUtil.copyProperties(item, CanApplyOrderVO.class)));
        if (CollectionUtil.isNotEmpty(myOrderList)) {
            // 遍历订单，转换成前台显示内容
            for (CanApplyOrderVO myOrder : myOrderList) {
                String recProvince = areaMap.get(myOrder.getRecProvince());
                if (StringUtils.isNotEmpty(recProvince)) {
                    myOrder.setRecProvinceVal(recProvince);
                }
                String recCity = areaMap.get(myOrder.getRecCity());
                if (StringUtils.isNotEmpty(recCity)) {
                    myOrder.setRecCityVal(recCity);
                }
                String recCounty = areaMap.get(myOrder.getRecCounty());
                if (StringUtils.isNotEmpty(recCounty)) {
                    myOrder.setRecCountyVal(recCounty);
                }
                myOrder.setRecAddress(myOrder.getRecAddress());
                // 订单显示金额 = 订单金额 + 运费
                myOrder.setOrderAmount(myOrder.getOrderAmount().add(myOrder.getPostage()));
                // 登录会员如果是中国会员，订单显示人民币业绩
                myOrder.setOrderAchieve(myOrder.getOrderAchieve().multiply(currencyDTO.getInExchangeRate()));
            }
        }
        TableDataInfo tableDataInfo = getDataTable(orderList);
        tableDataInfo.setRows(myOrderList);
        return tableDataInfo;
    }

    /**
     * @description: 自助业务-订单自提订单列表
     * @author: zhang jing
     * @date: 2023/5/29 9:10
     * @param: [selfPickUpParam]
     * @return: com.hzs.common.core.web.page.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(saOrder.getMemberCode());
                    saOrder.setMemberName(saOrder.getMemberName());
                }

                //处理订单收货地址
                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());

        // 直销订单处理
        if (saOrder.getPkCountry().equals(CountryConstants.CHINA_COUNTRY)) {
            // 中国需要处理PV显示问题
            // 汇率（目前只有中国需要由美金转人民币显示，其它国家显示就是美金不需要转换）
            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[] logisticsCodeArray;
            if (querySaDeliver.getLogisticsCode().contains("/")) {
                logisticsCodeArray = querySaDeliver.getLogisticsCode().split("/");
            } else {
                logisticsCodeArray = querySaDeliver.getLogisticsCode().split(",");
            }
            for (String code : logisticsCodeArray) {
                SaDeliver saDeliver = new SaDeliver();
                saDeliver.setLogisticsCode(code);
                saDeliver.setLogisticsCompany(querySaDeliver.getLogisticsCompany());
                deliverList.add(saDeliver);
            }
        }
        myOrder.setDeliverList(deliverList);

        return myOrder;
    }

    /**
     * @description: 自助撤单列表(24点内)
     * @author: zhang jing
     * @date: 2023/11/21 10:33
     * @param: [param]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @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()));
        }
        // 会员ID
        Long userId = SecurityUtils.getUserId();
        // 返回的订单数据
        List<MyOrderVO> myOrderList = new ArrayList<>();

        startPage();
        param.setOrderStatus(EOrderStatus.PAY.getValue());
        List<SaOrderExt> orderList = iSaOrderService.selfRevokeOrderList(param, SecurityUtils.getUserId(), null);

        // 处理订单返回
        this.handleOrderReturn(orderList, myOrderList);

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

    /**
     * @description: 自动撤单参数校验
     * @author: zhang jing
     * @date: 2023/11/21 14:49
     * @param: [orderQueryParam]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @PostMapping("/check-self-revoke-order")
    public AjaxResult checkSelfRevokeOrder(@RequestBody MyOrderVO myOrderVO) {
        log.info(myOrderVO.getOrderCode());
        // 验证订单编号、订单类型是否存在
        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();
    }

    /**
     * @description: 自助撤单
     * @author: zhang jing
     * @date: 2023/11/21 15:19
     * @param: [orderCancelParam]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @PostMapping("/self-revoke-order")
    public AjaxResult selfRevokeOrder(@RequestBody MyOrderVO myOrderVO, HttpServletRequest request) {
        Long userId = SecurityUtils.getUserId();
        myOrderVO.setPkCountry(SecurityUtils.getPkCountry());
        myOrderVO = iOrderBusinessService.checkSelfOrder(userId, myOrderVO);
        if (StringUtils.isNotEmpty(myOrderVO.getMsg())) {
            return AjaxResult.error(myOrderVO.getMsg());
        }
        iSaOrderService.selfRevokeOrder(userId, myOrderVO);

        //注册订单强制退出登录
        if (myOrderVO.getOrderType() == EOrderType.RETAIL_REGISTER.getValue()) {
            if (userId.equals(myOrderVO.getPkMember())) {
                String token = SecurityUtils.getToken(request);
                if (StringUtils.isNotEmpty(token)) {
                    // 删除用户缓存记录
                    AuthMemberUtil.logoutByToken(token);
                }
            }
        }

        return AjaxResult.success();
    }

    /**
     * 处订单返回
     *
     * @param orderList   订单列表
     * @param myOrderList 返回订单列表
     */
    private void handleOrderReturn(List<SaOrderExt> orderList, List<MyOrderVO> myOrderList) {
        if (CollectionUtil.isNotEmpty(orderList)) {
            // 查询到的订单对应的订单明细列表
            List<SaOrderItemsExt> orderItemsList = iSaOrderItemsService.queryListByOrderId(orderList.stream().map(SaOrderExt::getPkId).collect(Collectors.toList()));
            // 当前国家汇率
            CurrencyDTO currencyDTO = iCurrencyServiceApi.getCurrency(CountryConstants.CHINA_COUNTRY).getData();
            // 调用system服务，获取地址
            Map<Integer, String> areaMap = iAreaServiceApi.getAreaMap(CountryConstants.CHINA_COUNTRY).getData();

            // 遍历订单，转换成前台显示内容
            for (SaOrderExt saOrder : orderList) {
                // 返回订单数据
                MyOrderVO myOrder;
                // 订单明细状态
                Integer orderStatus = null;
                // 订单明细商品分组
                String orderGroup = 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())) {
                        // 订单明细状态分组处理
                        String tmpOrderGroup = saOrderItems.getPkOrder() + "-" + saOrderItems.getPkWares() + "-" + saOrderItems.getPkWaresSpecsSku() + "-" + saOrderItems.getIsGift() + "-" + saOrderItems.getSpecsNameId();
                        if (null == orderGroup) {
                            orderGroup = tmpOrderGroup;
                        }

                        if (!saOrderItems.getOrderStatus().equals(orderStatus)) {
                            // 明细状态不相同，则需要新建
                            orderStatus = saOrderItems.getOrderStatus();
                            // 处理订单
                            myOrder = BeanUtil.copyProperties(saOrder, MyOrderVO.class);
                            myOrder.setCreatorName(saOrder.getCreatorName());
                            myOrder.setCreatorCode(saOrder.getCreatorCode());
                            myOrder.setMemberName(saOrder.getMemberName());
                            myOrder.setMemberCode(saOrder.getMemberCode());
                            // 前台显示状态为明细状态
                            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());
                            myOrder.setOrderTypeVal(EOrderType.getEnumLabelByValue(myOrder.getOrderType()));

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

                            myOrderList.add(myOrder);
                        } else {
                            if (!tmpOrderGroup.equals(orderGroup)) {
                                // 订单明细商品分组不相同，需要新建
                                orderGroup = tmpOrderGroup;

                                // 明细状态相同，直接追加
                                myOrderItemsList.add(BeanUtil.copyProperties(saOrderItems, MyOrderItemsVO.class));
                            } else {
                                // 相同，则需要累计数量
                                MyOrderItemsVO tmpOrderItemsVO = myOrderItemsList.get(myOrderItemsList.size() - 1);
                                tmpOrderItemsVO.setQuantity(tmpOrderItemsVO.getQuantity() + saOrderItems.getQuantity());
                            }
                        }

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

}
