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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzs.common.core.constant.CountryConstants;
import com.hzs.common.core.constant.EnumsPrefixConstants;
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.utils.poi.ExcelUtil;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.core.web.page.TableDataInfo;
import com.hzs.common.domain.sale.ext.SaOrderExt;
import com.hzs.common.domain.sale.ext.SaOrderItemsExt;
import com.hzs.common.domain.sale.order.SaOrderRemarks;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.service.ITransactionCommonService;
import com.hzs.sale.order.controller.ParentOrderController;
import com.hzs.sale.order.controller.vo.StoreOrderTotalVo;
import com.hzs.sale.order.dto.OrderBusinessTemplate;
import com.hzs.sale.order.param.OrderQueryParam;
import com.hzs.sale.order.param.OrderSelectParam;
import com.hzs.sale.order.param.WaresOrderParam;
import com.hzs.sale.order.service.ISaOrderItemsService;
import com.hzs.sale.order.service.ISaOrderRemarksService;
import com.hzs.sale.order.service.ISaOrderService;
import com.hzs.sale.order.vo.*;
import com.hzs.sale.util.OrderUtil;
import com.hzs.system.base.IAreaServiceApi;
import com.hzs.system.sys.IUserServiceApi;
import com.hzs.system.sys.dto.UserAuthorityDTO;
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 org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 订单控制类
 */
@RestController
@RequestMapping("/manage/order")
@Slf4j
public class SaOrderController extends ParentOrderController {

    @Autowired
    private ITransactionCommonService iTransactionCommonService;
    @Autowired
    private ISaOrderService orderService;
    @Autowired
    private ISaOrderRemarksService orderRemarksService;
    @Autowired
    private ISaOrderItemsService orderItemsService;

    @DubboReference
    IAreaServiceApi areaServiceApi;
    @DubboReference
    IUserServiceApi iUserServiceApi;


    /**
     * 查询订单列表
     *
     * @return
     */
    @GetMapping("query-order-list")
    public TableDataInfo getQueryList(WaresOrderParam waresOrderParam) {
        if (waresOrderParam.getStartCreateDate() != null) {
            waresOrderParam.setStartCreateDate(DateUtils.getStartTime(waresOrderParam.getStartCreateDate()));
        }
        if (waresOrderParam.getEndCreateDate() != null) {
            waresOrderParam.setEndCreateDate(DateUtils.getEndTime(waresOrderParam.getEndCreateDate()));
        }
        if (waresOrderParam.getStartPayDate() != null) {
            waresOrderParam.setStartPayDate(DateUtils.getStartTime(waresOrderParam.getStartPayDate()));
        }
        if (waresOrderParam.getEndPayDate() != null) {
            waresOrderParam.setEndPayDate(DateUtils.getEndTime(waresOrderParam.getEndPayDate()));
        }
        Map<Integer, String> areaMap = areaServiceApi.getAreaMap(SecurityUtils.getPkCountry()).getData();
        waresOrderParam.setPkCountry(SecurityUtils.getPkCountry());

        // 获取管理员权限（角色地区范围、体系列表、团队列表）
        UserAuthorityDTO userAuthorityDTO = iUserServiceApi.getUserAuthority(SecurityUtils.getUserId()).getData();
        waresOrderParam.setAreaScopeList(userAuthorityDTO.getRoleAreaScopeList());
        waresOrderParam.setVertexIdList(userAuthorityDTO.getVertexIdList());
        waresOrderParam.setTeamList(userAuthorityDTO.getUserTeamList());
        startPage();
        if (waresOrderParam.getPkCountry() == CountryConstants.CHINA_COUNTRY) {
            waresOrderParam.setPkCountry(null);
        }
        List<WaresOrderVo> resultList = orderService.selectByOrderInfoList(waresOrderParam);
        for (WaresOrderVo waresOrderVo : resultList) {
            // 省
            if (waresOrderVo.getRecProvince() != null) {
                waresOrderVo.setRecProvinceName(areaMap.get(waresOrderVo.getRecProvince()));
            }
            //市
            if (waresOrderVo.getRecCity() != null) {
                waresOrderVo.setRecCityName(areaMap.get(waresOrderVo.getRecCity()));
            }
            // 县
            if (waresOrderVo.getRecCountry() != null) {
                waresOrderVo.setRecCountryName(areaMap.get(waresOrderVo.getRecCountry()));
            }
            // 发货方式
            if (null != waresOrderVo.getDeliveryWay()) {
                EDelivery eDelivery = EDelivery.getDelivery(waresOrderVo.getDeliveryWay());
                if (null != eDelivery) {
                    waresOrderVo.setDeliveryWayStr(eDelivery.getLabel());
                }
            }
            // 运输方式
            if (waresOrderVo.getTranType() != null) {
                waresOrderVo.setTranTypeStr(ETransportType.getETransportType(waresOrderVo.getTranType()).getLabel());
            }
            // 预售状态
            if (waresOrderVo.getPreSaleStatus() != null) {
                waresOrderVo.setPreSaleStatusStr(EPresaleStatus.getEPresaleStatus(waresOrderVo.getPreSaleStatus()).getLabel());
            }
            // 订单状态
            if (waresOrderVo.getOrderStatus() != null) {
                EOrderStatus orderStatusEnum = EOrderStatus.getEOrderStatus(waresOrderVo.getOrderStatus());
                if (orderStatusEnum != null) {
                    waresOrderVo.setOrderStatusStr(orderStatusEnum.getLabel());
                }
            }
            // 支付方式
            if (waresOrderVo.getPayType() != null) {
                EOrderPayType eOrderPayType = EOrderPayType.getEnumByValue(waresOrderVo.getPayType());
                if (null != eOrderPayType) {
                    waresOrderVo.setPayTypeStr(eOrderPayType.getLabel());
                }
            }
            // 订单类型
            if (waresOrderVo.getOrderType() != null) {
                EOrderType eOrderType = EOrderType.getEnumByValue(waresOrderVo.getOrderType());
                if (null != eOrderType) {
                    waresOrderVo.setOrderTypeStr(eOrderType.getLabel());
                }
            }
            // 供应方式
            if (StringUtils.isNotBlank(waresOrderVo.getOperateScope())) {
                ESupplyWay eSupplyWay = ESupplyWay.getESupplyWay(Integer.parseInt(waresOrderVo.getOperateScope()));
                if (null != eSupplyWay) {
                    waresOrderVo.setOperateScope(eSupplyWay.getLabel());
                }
            }

        }
        return getDataTable(resultList);
    }

    /**
     * 商品订单详情接口
     */
    @GetMapping("get-order-list")
    public TableDataInfo getOrderList(WaresOrderParam waresOrderParam) {
        startPage();
        Map<Integer, String> areaMap = areaServiceApi.getAreaMap(SecurityUtils.getPkCountry()).getData();
        //  List<WaresOrderVo> resultList = orderService.selectByInvestmentList(waresOrderParam);
        waresOrderParam.setPkCountry(SecurityUtils.getPkCountry());
        if (waresOrderParam.getStartPayDate() != null) {
            waresOrderParam.setStartPayDate(DateUtils.getStartTime(waresOrderParam.getStartPayDate()));
        }
        if (waresOrderParam.getEndPayDate() != null) {
            waresOrderParam.setEndPayDate(DateUtils.getEndTime(waresOrderParam.getEndPayDate()));
        }
        if (waresOrderParam.getStartCreateDate() != null) {
            waresOrderParam.setStartCreateDate(DateUtils.getStartTime(waresOrderParam.getStartCreateDate()));
        }
        if (waresOrderParam.getEndCreateDate() != null) {
            waresOrderParam.setEndCreateDate(DateUtils.getEndTime(waresOrderParam.getEndCreateDate()));
        }
        List<WaresOrderVo> resultList = orderItemsService.selectByInvestmentList(waresOrderParam);
        for (WaresOrderVo waresOrderVo : resultList) {
            // 省
            if (waresOrderVo.getRecProvince() != null) {
                waresOrderVo.setRecProvinceName(areaMap.get(waresOrderVo.getRecProvince()));
            }
            //市
            if (waresOrderVo.getRecCity() != null) {
                waresOrderVo.setRecCityName(areaMap.get(waresOrderVo.getRecCity()));
            }
            // 县
            if (waresOrderVo.getRecCountry() != null) {
                waresOrderVo.setRecCountryName(areaMap.get(waresOrderVo.getRecCountry()));
            }
            // 发货方式
            if (null != waresOrderVo.getDeliveryWay()) {
                waresOrderVo.setDeliveryWayStr(EDelivery.getDelivery(waresOrderVo.getDeliveryWay()).getLabel());
            }
            // 运输方式
            if (waresOrderVo.getTranType() != null) {
                waresOrderVo.setTranTypeStr(ETransportType.getETransportType(waresOrderVo.getTranType()).getLabel());
            }

            // 预售状态
            if (waresOrderVo.getPreSaleStatus() != null) {
                waresOrderVo.setPreSaleStatusStr(EPresaleStatus.getEPresaleStatus(waresOrderVo.getPreSaleStatus()).getLabel());
            }
            // 订单状态
            if (waresOrderVo.getOrderStatus() != null) {
                waresOrderVo.setOrderStatusStr(EOrderStatus.getEOrderStatus(waresOrderVo.getOrderStatus()).getLabel());
            }
            // 支付方式
            if (waresOrderVo.getPayType() != null) {
                waresOrderVo.setPayTypeStr(EOrderPayType.getEnumByValue(waresOrderVo.getPayType()).getLabel());
            }
            // 订单类型
            if (waresOrderVo.getOrderType() != null) {
                waresOrderVo.setOrderTypeStr(EOrderType.getEnumByValue(waresOrderVo.getOrderType()).getLabel());
            }
            // 供应方式
            if (StringUtils.isNotBlank(waresOrderVo.getOperateScope())) {
                waresOrderVo.setOperateScope(ESupplyWay.getESupplyWay(Integer.parseInt(waresOrderVo.getOperateScope())).getLabel());
            }
            // 计算汇率
//            if(null!=waresOrderVo.getInExchangeRate()){
//                waresOrderVo.setOrderAchieve(waresOrderVo.getInExchangeRate().multiply(waresOrderVo.getOrderAchieve()));
//            }
            // 发货类型
            if (waresOrderVo.getShippingChannel() != null) {
                waresOrderVo.setShippingChannelStr(EShippingChannel.getEnumByValue(waresOrderVo.getShippingChannel()).getLabel());
            }
            // 计算产品总计
            waresOrderVo.setProductPriceTotal(waresOrderVo.getProductPrice().multiply(BigDecimal.valueOf(waresOrderVo.getQuantity())));

        }
        return getDataTable(resultList);
    }

    /**
     * 商品订单详情导出
     *
     * @param response
     * @param waresOrderParam
     */
    @PostMapping("get-order-info-export")
    public void getOrderList(WaresOrderParam waresOrderParam, HttpServletResponse response) {
        Map<Integer, String> areaMap = areaServiceApi.getAreaMap(SecurityUtils.getPkCountry()).getData();
        // 导出缺少国家筛选
        waresOrderParam.setPkCountry(SecurityUtils.getPkCountry());
        if (waresOrderParam.getStartPayDate() != null) {
            waresOrderParam.setStartPayDate(DateUtils.getStartTime(waresOrderParam.getStartPayDate()));
        }
        if (waresOrderParam.getEndPayDate() != null) {
            waresOrderParam.setEndPayDate(DateUtils.getEndTime(waresOrderParam.getEndPayDate()));
        }
        if (waresOrderParam.getStartCreateDate() != null) {
            waresOrderParam.setStartCreateDate(DateUtils.getStartTime(waresOrderParam.getStartCreateDate()));
        }
        if (waresOrderParam.getEndCreateDate() != null) {
            waresOrderParam.setEndCreateDate(DateUtils.getEndTime(waresOrderParam.getEndCreateDate()));
        }
        List<WaresOrderVo> resultList = orderItemsService.selectByInvestmentList(waresOrderParam);
        for (WaresOrderVo waresOrderVo : resultList) {
            // 省
            if (waresOrderVo.getRecProvince() != null) {
                waresOrderVo.setRecProvinceName(areaMap.get(waresOrderVo.getRecProvince()));
            }
            //市
            if (waresOrderVo.getRecCity() != null) {
                waresOrderVo.setRecCityName(areaMap.get(waresOrderVo.getRecCity()));
            }
            // 县
            if (waresOrderVo.getRecCountry() != null) {
                waresOrderVo.setRecCountryName(areaMap.get(waresOrderVo.getRecCountry()));
            }
            // 发货方式
            waresOrderVo.setDeliveryWayStr(EDelivery.getDelivery(waresOrderVo.getDeliveryWay()).getLabel());
            // 运输方式
            if (waresOrderVo.getTranType() != null) {
                waresOrderVo.setTranTypeStr(ETransportType.getETransportType(waresOrderVo.getTranType()).getLabel());
            }

            // 预售状态
            if (waresOrderVo.getPreSaleStatus() != null) {
                waresOrderVo.setPreSaleStatusStr(EPresaleStatus.getEPresaleStatus(waresOrderVo.getPreSaleStatus()).getLabel());
            }
            // 订单状态
            if (waresOrderVo.getOrderStatus() != null) {
                waresOrderVo.setOrderStatusStr(EOrderStatus.getEOrderStatus(waresOrderVo.getOrderStatus()).getLabel());
            }
            // 支付方式
            if (waresOrderVo.getPayType() != null) {
                waresOrderVo.setPayTypeStr(EOrderPayType.getEnumByValue(waresOrderVo.getPayType()).getLabel());
            }
            // 订单类型
            if (waresOrderVo.getOrderType() != null) {
                waresOrderVo.setOrderTypeStr(EOrderType.getEnumByValue(waresOrderVo.getOrderType()).getLabel());
            }
            // 供应方式
            if (StringUtils.isNotBlank(waresOrderVo.getOperateScope())) {
                waresOrderVo.setOperateScope(ESupplyWay.getESupplyWay(Integer.parseInt(waresOrderVo.getOperateScope())).getLabel());
            }
            // 计算汇率
            waresOrderVo.setOrderAchieve(waresOrderVo.getInExchangeRate().multiply(waresOrderVo.getOrderAchieve()));
            // 发货类型
            if (waresOrderVo.getShippingChannel() != null) {
                waresOrderVo.setShippingChannelStr(EShippingChannel.getEnumByValue(waresOrderVo.getShippingChannel()).getLabel());
            }
        }
//        Integer quantity = 0;
//        for (WaresOrderVo waresOrderVo : resultList) {
//            quantity +=waresOrderVo.getQuantity();
//        }
//        System.out.println("数量:"+quantity);
        List<WaresOrderInfoVo> waresOrderInfoList = resultList.stream().map(a -> {
            WaresOrderInfoVo waresOrderInfoVo = BeanUtil.copyProperties(a, WaresOrderInfoVo.class);
            waresOrderInfoVo.setProductPrice(waresOrderInfoVo.getProductPrice());
            waresOrderInfoVo.setProductTotalPrice(waresOrderInfoVo.getProductPrice().multiply(new BigDecimal(waresOrderInfoVo.getQuantity())));
            return waresOrderInfoVo;
        }).collect(Collectors.toList());
        ExcelUtil<WaresOrderInfoVo> util = new ExcelUtil<>(WaresOrderInfoVo.class);
        util.exportExcel(response, waresOrderInfoList, "商品订单详情导出");
    }


    /**
     * 商品订单导出
     *
     * @return
     */
    @PostMapping("get-order-list-export")
    public void getOrderListExport(HttpServletResponse response, WaresOrderParam waresOrderParam) {
        if (waresOrderParam.getStartCreateDate() != null) {
            waresOrderParam.setStartCreateDate(DateUtils.getStartTime(waresOrderParam.getStartCreateDate()));
        }
        if (waresOrderParam.getEndCreateDate() != null) {
            waresOrderParam.setEndCreateDate(DateUtils.getEndTime(waresOrderParam.getEndCreateDate()));
        }
        if (waresOrderParam.getStartPayDate() != null) {
            waresOrderParam.setStartPayDate(DateUtils.getStartTime(waresOrderParam.getStartPayDate()));
        }
        if (waresOrderParam.getEndPayDate() != null) {
            waresOrderParam.setEndPayDate(DateUtils.getEndTime(waresOrderParam.getEndPayDate()));
        }
        Map<Integer, String> areaMap = areaServiceApi.getAreaMap(SecurityUtils.getPkCountry()).getData();
        waresOrderParam.setPkCountry(SecurityUtils.getPkCountry());

        // 获取管理员权限（角色地区范围、体系列表、团队列表）
        UserAuthorityDTO userAuthorityDTO = iUserServiceApi.getUserAuthority(SecurityUtils.getUserId()).getData();
        waresOrderParam.setAreaScopeList(userAuthorityDTO.getRoleAreaScopeList());
        waresOrderParam.setVertexIdList(userAuthorityDTO.getVertexIdList());
        waresOrderParam.setTeamList(userAuthorityDTO.getUserTeamList());
        // startPage();
        if (waresOrderParam.getPkCountry() == CountryConstants.CHINA_COUNTRY) {
            waresOrderParam.setPkCountry(null);
        }
        List<WaresOrderVo> resultList = orderService.selectByOrderInfoList(waresOrderParam);
        // 获取需要翻译的枚举翻译
        Map<String, String> transactionMap = iTransactionCommonService.exportEnumTransaction(EDelivery.values(), ESupplyWay.values(), ETransportType.values(), EPresaleStatus.values(), EOrderType.values(), EOrderStatus.values(), EOrderPayType.values(), ESaleType.values(), EShippingChannel.values());
        for (WaresOrderVo waresOrderVo : resultList) {
            // 省
            if (waresOrderVo.getRecProvince() != null) {
                waresOrderVo.setRecProvinceName(areaMap.get(waresOrderVo.getRecProvince()));
            }
            //市
            if (waresOrderVo.getRecCity() != null) {
                waresOrderVo.setRecCityName(areaMap.get(waresOrderVo.getRecCity()));
            }
            // 县
            if (waresOrderVo.getRecCountry() != null) {
                waresOrderVo.setRecCountryName(areaMap.get(waresOrderVo.getRecCountry()));
            }
            // 发货方式
            waresOrderVo.setDeliveryWayStr(EDelivery.getDelivery(waresOrderVo.getDeliveryWay()).getLabel());
            // 运输方式
            if (waresOrderVo.getTranType() != null) {
                waresOrderVo.setTranTypeStr(ETransportType.getETransportType(waresOrderVo.getTranType()).getLabel());
            }
            // 预售状态
            if (waresOrderVo.getPreSaleStatus() != null) {
                waresOrderVo.setPreSaleStatusStr(EPresaleStatus.getEPresaleStatus(waresOrderVo.getPreSaleStatus()).getLabel());
            }
            // 订单状态
            if (waresOrderVo.getOrderStatus() != null) {
                EOrderStatus orderStatusEnum = EOrderStatus.getEOrderStatus(waresOrderVo.getOrderStatus());
                if (orderStatusEnum != null) {
                    waresOrderVo.setOrderStatusStr(orderStatusEnum.getLabel());
                }
            }
            // 支付方式
            if (waresOrderVo.getPayType() != null) {
                waresOrderVo.setPayTypeStr(EOrderPayType.getEnumByValue(waresOrderVo.getPayType()).getLabel());
            }
            // 订单类型
            if (waresOrderVo.getOrderType() != null) {
                waresOrderVo.setOrderTypeVal(transactionMap.get(EnumsPrefixConstants.ORDER_TYPE + waresOrderVo.getOrderType()));
            }
            // 供应方式
            if (StringUtils.isNotBlank(waresOrderVo.getOperateScope())) {
                waresOrderVo.setOperateScope(ESupplyWay.getESupplyWay(Integer.parseInt(waresOrderVo.getOperateScope())).getLabel());
            }
            // 发货类型
            waresOrderVo.setShippingChannelVal(transactionMap.get(EnumsPrefixConstants.E_SHIPPING_CHANNEL + waresOrderVo.getShippingChannel()));
            waresOrderVo.setLogisticsCode(waresOrderVo.getLogisticsCode());
            waresOrderVo.setLogisticsCompany(waresOrderVo.getLogisticsCompany());
        }
        ExcelUtil<WaresOrderVo> util = new ExcelUtil<>(WaresOrderVo.class);
        util.exportExcel(response, resultList, "商品订单导出");
    }


    /**
     * 订单选择
     *
     * @param param
     * @return
     */
    @GetMapping("/order-select")
    public TableDataInfo memberSelect(OrderSelectParam param) {
        List<OrderSelectVO> resultList = new ArrayList<>();

        startPage();
        handleOrderSelect(resultList, param);

        return getDataTable(resultList);
    }

    /**
     * 订单选择下载模板
     *
     * @param response
     */
    @PostMapping("/order-select-template")
    public void orderSelectTemplate(HttpServletResponse response) {
        ExcelUtil<OrderBusinessTemplate> util = new ExcelUtil<>(OrderBusinessTemplate.class);
        util.exportExcel(response, null, "订单信息");
    }

    /**
     * 订单选择导入数据
     *
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/order-select-import")
    public AjaxResult orderSelectImport(MultipartFile file) throws Exception {
        ExcelUtil<OrderBusinessTemplate> util = new ExcelUtil<>(OrderBusinessTemplate.class);
        List<OrderBusinessTemplate> templateList = util.importExcel(file.getInputStream());

        // 返回结果
        List<OrderSelectVO> resultList = new ArrayList<>();

        if (CollectionUtil.isNotEmpty(templateList)) {
            OrderSelectParam param = new OrderSelectParam();
            param.setOrderCodeList(templateList.stream().map(OrderBusinessTemplate::getOrderCode).collect(Collectors.toList()));

            handleOrderSelect(resultList, param);
        }
        return AjaxResult.success(resultList);
    }

    /**
     * 处理选择订单数据
     *
     * @param resultList
     * @param param
     */
    private void handleOrderSelect(List<OrderSelectVO> resultList, OrderSelectParam param) {
        List<SaOrderItemsExt> saOrderItemsExtList = orderService.queryOrderSelect(param, SecurityUtils.getPkCountry());

        if (CollectionUtil.isNotEmpty(saOrderItemsExtList)) {
            // 调用system服务，获取地址
            Map<Integer, String> areaMap = areaServiceApi.getAreaMap(SecurityUtils.getPkCountry()).getData();

            for (SaOrderItemsExt saOrderItemsExt : saOrderItemsExtList) {
                OrderSelectVO orderSelectVO = BeanUtil.copyProperties(saOrderItemsExt, OrderSelectVO.class);
                // 处理省市县
                OrderUtil.handleOrderAddress(areaMap, orderSelectVO);
                resultList.add(orderSelectVO);
            }
        }
    }

    /**
     * 添加订单备注
     */
    @PostMapping("update-order-remarks")
    public AjaxResult updateOrderRemarks(@RequestBody SaOrderRemarks saOrderRemarks) {
        SaOrderRemarks orderRemarks = orderRemarksService.getOne(new QueryWrapper<SaOrderRemarks>().eq("PK_ORDER", saOrderRemarks.getPkOrder()));
        if (orderRemarks == null) {
            saOrderRemarks.setCreationTime(DateUtils.currentDateTime());
            saOrderRemarks.setPkCountry(SecurityUtils.getPkCountry());
            saOrderRemarks.setPkCreator(SecurityUtils.getUserId());
            saOrderRemarks.setStatus(EYesNo.NO.getIntValue());
            orderRemarksService.save(saOrderRemarks);
        } else {
            orderRemarks.setModifiedTime(DateUtils.currentDateTime());
            orderRemarks.setPkModified(SecurityUtils.getUserId());
            orderRemarks.setRemarks(saOrderRemarks.getRemarks());
            orderRemarksService.update(orderRemarks, new QueryWrapper<SaOrderRemarks>().eq("PK_ORDER", saOrderRemarks.getPkOrder()));
        }
        return AjaxResult.success();
    }


    /**
     * 会员店铺统计订单列表
     */
    @GetMapping("member-store-summary")
    public TableDataInfo memberStoreSummary(OrderQueryParam orderQueryParam) {
        // 返回的订单数据
        List<StoreOrderTotalVo> storeOrderTotalVoList = new ArrayList<>();
        orderQueryParam.setPkCountry(SecurityUtils.getPkCountry());
        startPage();
//        List<SaOrderExt> orderList = orderService.myStoreOrderList(param, param.getPkStore(), pkCountry);
        List<SaOrderExt> orderList = orderService.queryStoreSaOrderByParam(orderQueryParam);
        for (SaOrderExt saOrderExt : orderList) {
            for (SaOrderItemsExt saOrderItemsExt : saOrderExt.getOrderItemsExtList()) {
                StoreOrderTotalVo storeOrderTotalVo = BeanUtil.copyProperties(saOrderExt, StoreOrderTotalVo.class);
                storeOrderTotalVo.setProductCode(saOrderItemsExt.getProductCode());
                storeOrderTotalVo.setProductName(saOrderItemsExt.getProductName());
                storeOrderTotalVo.setSpecsName(saOrderItemsExt.getSpecsName());
                storeOrderTotalVo.setQuantity(saOrderItemsExt.getQuantity());
                storeOrderTotalVoList.add(storeOrderTotalVo);
            }
        }
        TableDataInfo tableDataInfo = getDataTable(orderList);
        tableDataInfo.setRows(storeOrderTotalVoList);
        return tableDataInfo;
    }

    /**
     * 会员店铺统计订单导出
     *
     * @param orderQueryParam
     * @return
     */
    @PostMapping("member-store-summary-export")
    public void memberStoreSummaryExport(OrderQueryParam orderQueryParam, HttpServletResponse response) {
//        List<OrderVo> resultList = new ArrayList<>();
//
//        // 获取需要翻译的枚举翻译
//        Map<String, String> transactionMap = iTransactionCommonService.exportEnumTransaction(EOrderType.values(),EYesNo.values(),ESupplyWay.values(),EOrderStatus.values());
//
////        if (param.getPkStore() != null){
////            R<StoreMonthCheckConfigDto> storeMonthCheckConfigDto = storeMonthCheckConfigApi.getByStoreMonthCheckConfig(param.getPkStore());
////            StoreMonthCheckConfigDto storeMonthCheckConfig = storeMonthCheckConfigDto.getData();
////        }
//        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 = orderService.myStoreOrderList(param, param.getPkStore(), pkCountry);
//        // 订单金额
//        BigDecimal amountTotal = BigDecimal.ZERO;
//        // 订单业绩
//        BigDecimal achieveTotal = BigDecimal.ZERO;
//        if (CollectionUtil.isNotEmpty(orderList)) {
//            // 当前国家汇率
//            CurrencyDTO currencyDTO = iCurrencyServiceApi.getCurrency(pkCountry).getData();
//            // 查询到的订单对应的订单明细列表
//            List<SaOrderItemsExt> orderItemsList = orderItemsService.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.setOrderTypeVal(transactionMap.get(EnumsPrefixConstants.ORDER_TYPE +saOrder.getOrderType()));
//                            myOrder.setMemberCode(saOrder.getMemberCode());
//                            myOrder.setMemberName(saOrder.getMemberName());
//
//                            myOrder.setStoreName(saOrder.getStoreName());
//                            // 前台显示状态为明细状态
//                            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());
//                            }
//                            myOrder.setStoreName(saOrder.getStoreName());
//                            // 处理订单明细
//                            myOrderItemsList = new ArrayList<>();
//                            myOrderItemsList.add(BeanUtil.copyProperties(saOrderItems, MyOrderItemsVO.class));
//                            myOrder.setItemList(myOrderItemsList);
//                            OrderVo saOrderVo = BeanUtil.copyProperties(myOrder, OrderVo.class);
//                            saOrderVo.setOrderStatusVal(transactionMap.get(EnumsPrefixConstants.ORDER_STATUS + myOrder.getOrderStatus()));
//                            saOrderVo.setRecProvince(myOrder.getRecProvince());
//                            saOrderVo.setRecCity(myOrder.getRecCity());
//                            saOrderVo.setRecCounty(myOrder.getRecCounty());
//                            resultList.add(saOrderVo);
//                            myOrderList.add(myOrder);
//                        } else {
//                            // 明细状态相同，直接追加
//                            myOrderItemsList.add(BeanUtil.copyProperties(saOrderItems, MyOrderItemsVO.class));
//                        }
//
//                        // 订单ID处理过
//                        isHandle = true;
//                        continue;
//                    }
//                    if (isHandle) {
//                        // 订单明细遍历，如果订单曾经处理过，则此处跳出本次订单明细遍历
//                        break;
//                    }
//                }
//            }
//        }
        List<StoreOrderTotalVo> storeOrderTotalVoList = new ArrayList<>();
        orderQueryParam.setPkCountry(SecurityUtils.getPkCountry());
//        List<SaOrderExt> orderList = orderService.myStoreOrderList(param, param.getPkStore(), pkCountry);
        List<SaOrderExt> orderList = orderService.queryStoreSaOrderByParam(orderQueryParam);
        for (SaOrderExt saOrderExt : orderList) {
            for (SaOrderItemsExt saOrderItemsExt : saOrderExt.getOrderItemsExtList()) {
                StoreOrderTotalVo storeOrderTotalVo = BeanUtil.copyProperties(saOrderExt, StoreOrderTotalVo.class);
                storeOrderTotalVo.setProductCode(saOrderItemsExt.getProductCode());
                storeOrderTotalVo.setProductName(saOrderItemsExt.getProductName());
                storeOrderTotalVo.setSpecsName(saOrderItemsExt.getSpecsName());
                storeOrderTotalVo.setQuantity(saOrderItemsExt.getQuantity());
                for (EOrderType orderType : EOrderType.values()) {
                    if (saOrderExt.getOrderType() == orderType.getValue()) {
                        storeOrderTotalVo.setOrderTypeVal(orderType.getLabel());
                        break;
                    }
                }
                for (EOrderStatus orderStatus : EOrderStatus.values()) {
                    if (saOrderExt.getOrderStatus() == orderStatus.getValue()) {
                        storeOrderTotalVo.setOrderStatusVal(orderStatus.getLabel());
                        break;
                    }
                }
                storeOrderTotalVoList.add(storeOrderTotalVo);
            }
        }
        ExcelUtil<StoreOrderTotalVo> util = new ExcelUtil<>(StoreOrderTotalVo.class);
        util.exportExcel(response, storeOrderTotalVoList, "会员店铺订单统计导出");
    }
}
