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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
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.member.base.CuMember;
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.security.utils.SecurityUtils;
import com.hzs.common.core.utils.TransactionUtils;
import com.hzs.member.store.ICuStoreServiceApi;
import com.hzs.member.store.dto.StoreDto;
import com.hzs.member.storeconfig.IBdStoreMonthCheckConfigApi;
import com.hzs.member.storeconfig.dto.StoreMonthCheckConfigDto;
import com.hzs.sale.deliver.service.ISaDeliverService;
import com.hzs.sale.order.controller.param.StoreOrderDeliveryParam;
import com.hzs.sale.order.controller.vo.MemberStoreSummaryVo;
import com.hzs.sale.order.param.*;
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 lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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;

    @DubboReference
    private ICurrencyServiceApi iCurrencyServiceApi;
    @DubboReference
    private IAreaServiceApi iAreaServiceApi;
    @DubboReference
    private ICuStoreServiceApi storeServiceApi;
    @DubboReference
    private IBdStoreMonthCheckConfigApi storeMonthCheckConfigApi;

    /**
     * 查询订单
     *
     * @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();
        // 返回的订单数据
        List<MyOrderVO> myOrderList = new ArrayList<>();

        startPage();
        List<SaOrderExt> orderList = iSaOrderService.myOrderList(param, SecurityUtils.getUserId(), null);
        if (CollectionUtil.isNotEmpty(orderList)) {
            // 当前国家汇率
            CurrencyDTO currencyDTO = iCurrencyServiceApi.getCurrency(pkCountry).getData();

            // 查询到的订单对应的订单明细列表
            List<SaOrderItemsExt> orderItemsList = iSaOrderItemsService.queryListByOrderId(orderList.stream().map(SaOrderExt::getPkId).collect(Collectors.toList()));
            // 订单结算国列表
            List<Integer> pkCountryList = orderList.stream().map(SaOrderExt::getPkCountry).distinct().collect(Collectors.toList());

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

            // 遍历订单，转换成前台显示内容
            for (SaOrderExt saOrder : orderList) {
                Integer isShowPayButton = 0;
                if (saOrder.getOrderType().equals(EOrderType.REGISTER_ORDER.getValue())){
                    // 注册订单 + 24小时
                    Date earlierDate = DateUtil.offsetHour(saOrder.getCreationTime(), 24);
                    if (earlierDate.compareTo(DateUtils.currentDate()) < 0){
                        isShowPayButton = 1 ;
                    }
                }

                // 返回订单数据
                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);
                            // 是否展示支付按钮 0 展示 1 隐藏
                            myOrder.setIsShowPayButton(isShowPayButton);
                            // 前台显示状态为明细状态
                            myOrder.setOrderStatus(saOrderItems.getOrderStatus());
                            myOrder.setDeliveryWay(saOrder.getDeliveryWay());
                            // 订单显示金额 = 订单金额 + 运费
                            //     myOrder.setOrderAmount(myOrder.getOrderAmount().add(myOrder.getPostage()));
                            myOrder.setOrderAmount(myOrder.getOrderAmount());

                            if (saOrder.getPkCountry().equals(CountryConstants.CHINA_COUNTRY)) {
                                // 如果是中国订单
                                myOrder.setOrderAchieve(myOrder.getOrderAchieve().multiply(baseExchangeRate));
                            }
                            // 复消积分订单
                            if (saOrder.getOrderType().equals(EOrderType.RESALE_INTEGRAL_ORDER.getValue())) {
                                myOrder.setOrderAchieve(BigDecimal.ZERO);
                            }
                            if (!saOrder.getPkCountry().equals(pkCountry)) {
                                if (baseExchangeRate.compareTo(currencyDTO.getInExchangeRate()) != 0) {
                                    // 订单结算国与登录结算国不相同，需要处理金额转换（订单金额 除 订单结算国汇率 乘 登录结算国汇率）
                                    myOrder.setOrderAmount(myOrder.getOrderAmount().divide(baseExchangeRate, 6, BigDecimal.ROUND_HALF_UP).multiply(currencyDTO.getInExchangeRate()).setScale(6, BigDecimal.ROUND_HALF_UP));
                                }
                            }

                            if (saOrder.getDeliveryWay() != null && saOrder.getDeliveryWay().equals(EDelivery.SHOP_PICKED_UP.getValue())) {
                                // 店铺自提 显示店铺地址
                                String recProvince = areaMap.get(saOrder.getProvince());
                                if (StringUtils.isNotEmpty(recProvince)) {
                                    myOrder.setRecProvince(recProvince);
                                }
                                String recCity = areaMap.get(saOrder.getCity());
                                if (StringUtils.isNotEmpty(recCity)) {
                                    myOrder.setRecCity(recCity);
                                }
                                myOrder.setAddress(saOrder.getAddress());
                            } else {
                                String recProvince = areaMap.get(saOrder.getOrderRecProvince());
                                if (StringUtils.isNotEmpty(recProvince)) {
                                    myOrder.setRecProvince(recProvince);
                                }
                                String recCity = areaMap.get(saOrder.getOrderRecCity());
                                if (StringUtils.isNotEmpty(recCity)) {
                                    myOrder.setRecCity(recCity);
                                }
                                myOrder.setAddress(saOrder.getOrderRecAddress());
                            }

                            // 处理订单明细
                            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;
        //     return getDataTable(orderList);
    }

    /**
     * 我的订单列表 店铺
     *
     * @param param 查询参数
     * @return
     */
    @GetMapping("/store-list")
    public TableDataInfo storeList(MyOrderParam param) {
        Long pkMember = SecurityUtils.getUserId();
        R<StoreDto> memberStore = storeServiceApi.getMemberStore(pkMember);
        StoreDto store = memberStore.getData();
        if (store == null || store.getPkId() == null) {
            //非店铺会员无返回
            return getDataTable(new ArrayList<>());
        }
        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();
        List<SaOrderExt> orderList = iSaOrderService.myStoreOrderList(param, store.getPkId(), null);
        if (CollectionUtil.isNotEmpty(orderList)) {
            // 当前国家汇率
            CurrencyDTO currencyDTO = iCurrencyServiceApi.getCurrency(pkCountry).getData();

            // 查询到的订单对应的订单明细列表
            List<SaOrderItemsExt> orderItemsList = iSaOrderItemsService.queryListByOrderId(orderList.stream().map(SaOrderExt::getPkId).collect(Collectors.toList()));

            // 调用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);
                            // 前台显示状态为明细状态
                            myOrder.setOrderStatus(saOrderItems.getOrderStatus());
                            // 发货方式
                            myOrder.setDeliveryWay(saOrderItems.getDeliveryWay());
                            // 订单显示金额 = 订单金额 + 运费
                            //     myOrder.setOrderAmount(myOrder.getOrderAmount().add(myOrder.getPostage()));
                            myOrder.setOrderAmount(myOrder.getOrderAmount());

                            if (saOrder.getPkCountry().equals(CountryConstants.CHINA_COUNTRY)) {
                                // 如果是中国订单
                                myOrder.setOrderAchieve(myOrder.getOrderAchieve().multiply(baseExchangeRate));
                            }
                            if (saOrder.getOrderType().equals(EOrderType.RESALE_INTEGRAL_ORDER.getValue())) {
                                myOrder.setOrderAchieve(BigDecimal.ZERO);
                            }
                            if (!saOrder.getPkCountry().equals(pkCountry)) {
                                // 订单结算国与登录结算国不相同，需要处理金额转换（订单金额 除 订单结算国汇率 乘 登录结算国汇率）
                                myOrder.setOrderAmount(myOrder.getOrderAmount().divide(baseExchangeRate, 2, BigDecimal.ROUND_HALF_UP).multiply(currencyDTO.getInExchangeRate()).setScale(2, BigDecimal.ROUND_HALF_UP));
                            }
                            if (saOrder.getDeliveryWay() != null && saOrder.getDeliveryWay().equals(EDelivery.SHOP_PICKED_UP.getValue())) {
                                // 店铺自提 显示店铺地址
                                String recProvince = areaMap.get(saOrder.getProvince());
                                if (StringUtils.isNotEmpty(recProvince)) {
                                    myOrder.setRecProvince(recProvince);
                                }
                                String recCity = areaMap.get(saOrder.getCity());
                                if (StringUtils.isNotEmpty(recCity)) {
                                    myOrder.setRecCity(recCity);
                                }
                                myOrder.setAddress(saOrder.getAddress());
                            } else {
                                String recProvince = areaMap.get(saOrder.getOrderRecProvince());
                                if (StringUtils.isNotEmpty(recProvince)) {
                                    myOrder.setRecProvince(recProvince);
                                }
                                String recCity = areaMap.get(saOrder.getOrderRecCity());
                                if (StringUtils.isNotEmpty(recCity)) {
                                    myOrder.setRecCity(recCity);
                                }
                                myOrder.setAddress(saOrder.getOrderRecAddress());
                            }
//                            if (saOrder.getOrderRecProvince() != null){
//                                String recProvince = areaMap.get(saOrder.getOrderRecProvince());
//                                if (StringUtils.isNotEmpty(recProvince)) {
//                                    myOrder.setRecProvince(recProvince);
//                                }
//                                String recCity = areaMap.get(saOrder.getOrderRecCity());
//                                if (StringUtils.isNotEmpty(recCity)) {
//                                    myOrder.setRecCity(recCity);
//                                }
//
//                                myOrder.setAddress(saOrder.getOrderRecAddress());
//                            }else {
//                                String recProvince = areaMap.get(saOrder.getProvince());
//                                if (StringUtils.isNotEmpty(recProvince)) {
//                                    myOrder.setRecProvince(recProvince);
//                                }
//                                String recCity = areaMap.get(saOrder.getCity());
//                                if (StringUtils.isNotEmpty(recCity)) {
//                                    myOrder.setRecCity(recCity);
//                                }
//                                myOrder.setAddress(saOrder.getAddress());
//                            }


                            // 处理订单明细
                            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;
    }

    /**
     * 订单详情
     *
     * @param orderCode 订单编号
     * @return
     */
    @GetMapping("/detail/{orderCode}")
    public AjaxResult detail(@PathVariable("orderCode") String orderCode) {
        // 所属国家
        Integer pkCountry = SecurityUtils.getPkCountry();
        // 查询订单以及详情
        SaOrderExt saOrder = iSaOrderService.queryOrderByCode(orderCode, pkCountry);
        return AjaxResult.success(this.handleSaOrderDetail(saOrder, pkCountry));
    }

    /**
     * 我的订单数量
     *
     * @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());
    }

    /**
     * 我的店铺订单数量
     *
     * @return
     */
    @GetMapping("/store-num")
    public AjaxResult storeNum() {
        Long pkMember = SecurityUtils.getUserId();
        Integer pkCountry = SecurityUtils.getPkCountry();
        R<StoreDto> memberStore = storeServiceApi.getMemberStore(pkMember);
        StoreDto store = memberStore.getData();
        int num = 0;
        if (store.getPkId() != null) {
            num = iSaOrderService.getStoreNum(Arrays.asList(EOrderStatus.PAY.getValue()), store.getPkId(), pkCountry);
        }

        return AjaxResult.success(MyOrderNumVO.builder()
                // 待发货数量
                .payNum(num)
                .build());
    }

    /**
     * 订单打印（目前只有海外有，暂时不需要处理三方订单）
     *
     * @param orderCode 订单编号
     * @return
     */
    @GetMapping("/print/{orderCode}")
    public AjaxResult print(@PathVariable("orderCode") String orderCode) {
        MyOrderPrintVO myOrderPrintVO = iSaOrderService.orderPrint(orderCode, SecurityUtils.getUserId(), SecurityUtils.getPkCountry());

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

        StringBuilder addresss = new StringBuilder();
        String recProvince = areaMap.get(myOrderPrintVO.getRecProvince());
        if (StringUtils.isNotEmpty(recProvince)) {
            addresss.append(recProvince);
        }
        String recCity = areaMap.get(myOrderPrintVO.getRecCity());
        if (StringUtils.isNotEmpty(recCity)) {
            addresss.append(recCity);
        }
        String recCounty = areaMap.get(myOrderPrintVO.getRecCounty());
        if (StringUtils.isNotEmpty(recCounty)) {
            addresss.append(recCounty);
        }
        addresss.append(myOrderPrintVO.getRecAddress());
        myOrderPrintVO.setRecAddress(addresss.toString());

        return AjaxResult.success(myOrderPrintVO);
    }

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

        QueryWrapper<SaOrder> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("ORDER_CODE", orderCode).and(wrapper -> wrapper.eq("PK_MEMBER", userId).or().eq(SystemFieldConstants.PK_CREATOR, userId));
        //      orderQueryWrapper.eq("PK_MEMBER", userId);

        SaOrder saOrder = iSaOrderService.getOne(orderQueryWrapper);
        if (null != saOrder) {
            if (EOrderStatus.PAY.getValue() != saOrder.getOrderStatus() &&  EOrderStatus.DELIVERED.getValue() != saOrder.getOrderStatus()) {
                // 订单状态待发货
                return AjaxResult.error(TransactionUtils.getContent(SaOrderMsgConstants.ORDER_STATUS_NOT));
            }
            //非自提订单必须是已收货状态才能确认收货
            if (saOrder.getDeliveryWay().equals(EDelivery.FAST_MAIL.getValue()) || saOrder.getDeliveryWay().equals(EDelivery.SHOP_DELIVERY.getValue())){
                List<SaOrderItems> orderItemList = iSaOrderItemsService.list(new QueryWrapper<SaOrderItems>().eq("PK_ORDER", saOrder.getPkId()));
                for (SaOrderItems saOrderItems : orderItemList) {
                    if (!saOrderItems.getOrderStatus().equals(EOrderStatus.DELIVERED.getValue())){
                        return AjaxResult.error(TransactionUtils.getContent(SaOrderMsgConstants.NOT_PAY_ORDER_STATUS_FH));
                    }
                }
            }
            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();

        QueryWrapper<SaOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ORDER_CODE", orderCode).and(wrapper -> wrapper.eq("PK_MEMBER", userId).or().eq(SystemFieldConstants.PK_CREATOR, 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();
    }

    /**
     * 订单详情处理
     *
     * @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[] 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;
    }

    /**
     * 店铺订单发货
     */
    @PostMapping("store-order-delivery")
    public AjaxResult storeOrderDelivery(@RequestBody StoreOrderDeliveryParam storeOrderDeliveryParam) {
        String orderCode = storeOrderDeliveryParam.getOrderCode();
        // 订单
        SaOrder order = iSaOrderService.getOne(new QueryWrapper<SaOrder>().eq("ORDER_CODE", orderCode));
        if (order == null) {
            return AjaxResult.error(TransactionUtils.getContent(SaOrderMsgConstants.ORDER_NOT_EXIST));
        }

        UpdateWrapper<SaOrderItems> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("PK_ORDER", order.getPkId());
        updateWrapper.set("ORDER_STATUS", EOrderStatus.DELIVERED.getValue());
        updateWrapper.set("MODIFIED_TIME", DateUtils.currentDate());
        iSaOrderItemsService.update(updateWrapper);

        return AjaxResult.success();
    }

    /**
     * 会员店铺统计订单列表
     */
    @GetMapping("member-store-summary")
    public TableDataInfo memberStoreSummary(MyOrderParam param) {

        Long pkMember = SecurityUtils.getUserId();
        R<StoreDto> memberStore = storeServiceApi.getMemberStore(pkMember);
        StoreDto store = memberStore.getData();
        if (store == null || store.getPkId() == null) {
            //非店铺会员无返回
            return getDataTable(new ArrayList<>());
        }

        R<StoreMonthCheckConfigDto> storeMonthCheckConfigDto = storeMonthCheckConfigApi.getByStoreMonthCheckConfig(store.getPkId());
        StoreMonthCheckConfigDto storeMonthCheckConfig = storeMonthCheckConfigDto.getData();
        if (storeMonthCheckConfig != null) {
            Date startDate = storeMonthCheckConfig.getStartDate();
            Date endDate = storeMonthCheckConfig.getEndDate();
            param.setCreationTimeStart(startDate);
            param.setCreationTimeEnd(endDate);
        } else {
            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();
        List<SaOrderExt> orderList = iSaOrderService.myStoreOrderList(param, store.getPkId(), null);
        // 订单金额
        BigDecimal amountTotal = BigDecimal.ZERO;
        // 订单业绩
        BigDecimal achieveTotal = BigDecimal.ZERO;
        if (CollectionUtil.isNotEmpty(orderList)) {
            // 当前国家汇率
            CurrencyDTO currencyDTO = iCurrencyServiceApi.getCurrency(pkCountry).getData();

            // 查询到的订单对应的订单明细列表
            List<SaOrderItemsExt> orderItemsList = iSaOrderItemsService.queryListByOrderId(orderList.stream().map(SaOrderExt::getPkId).collect(Collectors.toList()));

            // 调用system服务，获取地址
            Map<Integer, String> areaMap = iAreaServiceApi.getAreaMap(pkCountry).getData();
            for (SaOrderExt saOrderExt : orderList) {
                amountTotal = amountTotal.add(saOrderExt.getOrderAmount());
                achieveTotal = achieveTotal.add(saOrderExt.getOrderAchieve());
            }
            // 遍历订单，转换成前台显示内容
            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);
                            // 前台显示状态为明细状态
                            myOrder.setOrderStatus(saOrderItems.getOrderStatus());
                            // 发货方式
                            myOrder.setDeliveryWay(saOrderItems.getDeliveryWay());
                            // 订单显示金额 = 订单金额 + 运费
                            //     myOrder.setOrderAmount(myOrder.getOrderAmount().add(myOrder.getPostage()));
                            myOrder.setOrderAmount(myOrder.getOrderAmount());

                            if (saOrder.getPkCountry().equals(CountryConstants.CHINA_COUNTRY)) {
                                // 如果是中国订单
                                myOrder.setOrderAchieve(myOrder.getOrderAchieve().multiply(baseExchangeRate));
                            }
                            if (saOrder.getOrderType().equals(EOrderType.RESALE_INTEGRAL_ORDER.getValue())) {
                                myOrder.setOrderAchieve(BigDecimal.ZERO);
                            }
                            if (!saOrder.getPkCountry().equals(pkCountry)) {
                                // 订单结算国与登录结算国不相同，需要处理金额转换（订单金额 除 订单结算国汇率 乘 登录结算国汇率）
                                myOrder.setOrderAmount(myOrder.getOrderAmount().divide(baseExchangeRate, 2, BigDecimal.ROUND_HALF_UP).multiply(currencyDTO.getInExchangeRate()).setScale(2, BigDecimal.ROUND_HALF_UP));
                            }
                            if (saOrder.getDeliveryWay() != null && saOrder.getDeliveryWay().equals(EDelivery.SHOP_PICKED_UP.getValue())) {
                                // 店铺自提 显示店铺地址
                                String recProvince = areaMap.get(saOrder.getProvince());
                                if (StringUtils.isNotEmpty(recProvince)) {
                                    myOrder.setRecProvince(recProvince);
                                }
                                String recCity = areaMap.get(saOrder.getCity());
                                if (StringUtils.isNotEmpty(recCity)) {
                                    myOrder.setRecCity(recCity);
                                }
                                myOrder.setAddress(saOrder.getAddress());
                            } else {
                                String recProvince = areaMap.get(saOrder.getOrderRecProvince());
                                if (StringUtils.isNotEmpty(recProvince)) {
                                    myOrder.setRecProvince(recProvince);
                                }
                                String recCity = areaMap.get(saOrder.getOrderRecCity());
                                if (StringUtils.isNotEmpty(recCity)) {
                                    myOrder.setRecCity(recCity);
                                }
                                myOrder.setAddress(saOrder.getOrderRecAddress());
                            }

                            // 处理订单明细
                            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("member-store-summary-sum")
    public AjaxResult memberStoreSummarySum(MyOrderParam param){
        Long pkMember = SecurityUtils.getUserId();
        R<StoreDto> memberStore = storeServiceApi.getMemberStore(pkMember);
        StoreDto store = memberStore.getData();
        if (store == null || store.getPkId() == null) {
            //非店铺会员无返回
            return AjaxResult.success(MemberStoreSummaryVo.builder().achieveTotal(BigDecimal.ZERO).amountTotal(BigDecimal.ZERO).build());
        }
        R<StoreMonthCheckConfigDto> storeMonthCheckConfigDto = storeMonthCheckConfigApi.getByStoreMonthCheckConfig(store.getPkId());
        StoreMonthCheckConfigDto storeMonthCheckConfig = storeMonthCheckConfigDto.getData();
        if (storeMonthCheckConfig != null) {
            Date startDate = storeMonthCheckConfig.getStartDate();
            Date endDate = storeMonthCheckConfig.getEndDate();
            param.setCreationTimeStart(startDate);
            param.setCreationTimeEnd(endDate);
        } else {
            if (null != param.getCreationTimeStart()) {
                param.setCreationTimeStart(DateUtils.getStartTime(param.getCreationTimeStart()));
            }
            if (null != param.getCreationTimeEnd()) {
                param.setCreationTimeEnd(DateUtils.getEndTime(param.getCreationTimeEnd()));
            }
        }
        // 返回的订单数据
        List<MyOrderVO> myOrderList = new ArrayList<>();

        List<SaOrderExt> orderList = iSaOrderService.myStoreOrderList(param, store.getPkId(), null);
        // 订单金额
        BigDecimal amountTotal = BigDecimal.ZERO;
        // 订单业绩
        BigDecimal achieveTotal = BigDecimal.ZERO;
        if (CollectionUtil.isNotEmpty(orderList)) {
            for (SaOrderExt saOrderExt : orderList) {
                amountTotal = amountTotal.add(saOrderExt.getOrderAmount());
                if (saOrderExt.getOrderType()!=EOrderType.RESALE_ORDER.getValue()){
                    achieveTotal = achieveTotal.add(saOrderExt.getOrderAchieve());
                }

            }
        }
        return AjaxResult.success(MemberStoreSummaryVo.builder().achieveTotal(achieveTotal).amountTotal(amountTotal).build());
    }

}
