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.LambdaQueryWrapper;
import com.hzs.common.core.annotation.AccessPermissions;
import com.hzs.common.core.annotation.Log;
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.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.dto.OrderBusinessTemplate;
import com.hzs.sale.order.param.*;
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.IMenuColumnServiceApi;
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.*;
import java.util.stream.Collectors;

/**
 * 订单控制类
 *
 * @author: sui q
 * @time: 2022/8/27 16:20
 * @description:
 * @classname: OrderController
 * @package_name: com.hzs.sale.order.controller
 */
@RestController
@RequestMapping("/manage/order")
@Slf4j
public class SaOrderController extends ParentOrderController {

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

    @DubboReference
    IAreaServiceApi areaServiceApi;
    @DubboReference
    IUserServiceApi iUserServiceApi;
    @DubboReference
    IMenuColumnServiceApi iMenuColumnServiceApi;

    /**
     * 商品订单列表
     *
     * @return
     */
    @AccessPermissions("Commodity")
    @Log(module = EOperationModule.PRODUCT_ORDER, business = EOperationBusiness.PRODUCT_ORDER, method = EOperationMethod.SELECT)
    @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());
        waresOrderParam.setSystemType(SecurityUtils.getSystemType());

        // 获取管理员权限（角色地区范围、体系列表、团队列表）
        UserAuthorityDTO userAuthorityDTO = iUserServiceApi.getUserAuthority(SecurityUtils.getUserId()).getData();
        waresOrderParam.setAreaScopeList(userAuthorityDTO.getRoleAreaScopeList());
        waresOrderParam.setVertexIdList(userAuthorityDTO.getVertexIdList());
        waresOrderParam.setTeamList(userAuthorityDTO.getUserTeamList());

        startPage();
        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);
    }

    /**
     * 商品订单导出
     *
     * @return
     */
    @Log(module = EOperationModule.PRODUCT_ORDER, business = EOperationBusiness.PRODUCT_ORDER, method = EOperationMethod.EXPORT)
    @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());
        waresOrderParam.setSystemType(SecurityUtils.getSystemType());

        // 获取管理员权限（角色地区范围、体系列表、团队列表）
        UserAuthorityDTO userAuthorityDTO = iUserServiceApi.getUserAuthority(SecurityUtils.getUserId()).getData();
        waresOrderParam.setAreaScopeList(userAuthorityDTO.getRoleAreaScopeList());
        waresOrderParam.setVertexIdList(userAuthorityDTO.getVertexIdList());
        waresOrderParam.setTeamList(userAuthorityDTO.getUserTeamList());
        // startPage();
        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 && ETransportType.getETransportType(waresOrderVo.getTranType()) != null) {
                waresOrderVo.setTranTypeStr(ETransportType.getETransportType(waresOrderVo.getTranType()).getLabel());
            }
            // 预售状态
            if (waresOrderVo.getPreSaleStatus() != null && EPresaleStatus.getEPresaleStatus(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()) && ESupplyWay.getESupplyWay(Integer.parseInt(waresOrderVo.getOperateScope())) != null) {
                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>(WaresOrderVo.class, iMenuColumnServiceApi.queryMenuColumn("Commodity", SecurityUtils.getUserId()).getData());
        util.exportExcel(response, resultList, "商品订单导出");
    }

    /**
     * 商品订单详情接口
     */
    @AccessPermissions("Commodity")
    @Log(module = EOperationModule.PRODUCT_ORDER, business = EOperationBusiness.PRODUCT_ORDER_DETAIL, method = EOperationMethod.SELECT)
    @GetMapping("/get-order-list")
    public TableDataInfo getOrderList(WaresOrderParam waresOrderParam) {
        waresOrderParam.setPkCountry(SecurityUtils.getPkCountry());
        waresOrderParam.setSystemType(SecurityUtils.getSystemType());

        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()));
        }

        startPage();
        List<WaresOrderVo> resultList = orderItemsService.selectByInvestmentList(waresOrderParam);

        // 获取需要翻译的枚举翻译
        Map<String, String> transactionMap = iTransactionCommonService.exportEnumTransaction(EDelivery.values(), ESupplyWay.values());
        Map<Integer, String> areaMap = areaServiceApi.getAreaMap(SecurityUtils.getPkCountry()).getData();
        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(transactionMap.get(EnumsPrefixConstants.DELIVERY + waresOrderVo.getDeliveryWay()));
            }
            // 运输方式
            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
     */
    @Log(module = EOperationModule.PRODUCT_ORDER, business = EOperationBusiness.PRODUCT_ORDER_DETAIL, method = EOperationMethod.EXPORT)
    @PostMapping("/get-order-info-export")
    public void getOrderList(WaresOrderParam waresOrderParam, HttpServletResponse response) {
        // 导出缺少国家筛选
        waresOrderParam.setPkCountry(SecurityUtils.getPkCountry());
        waresOrderParam.setSystemType(SecurityUtils.getSystemType());

        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);

        Map<Integer, String> areaMap = areaServiceApi.getAreaMap(SecurityUtils.getPkCountry()).getData();
        // 获取需要翻译的枚举翻译
        Map<String, String> transactionMap = iTransactionCommonService.exportEnumTransaction(EDelivery.values(), ESupplyWay.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()));
            }
            // 发货方式
            if (waresOrderVo.getDeliveryWay() != null) {
                waresOrderVo.setDeliveryWayStr(transactionMap.get(EnumsPrefixConstants.DELIVERY + waresOrderVo.getDeliveryWay()));
            }

            // 运输方式
            if (waresOrderVo.getTranType() != null) {
                ETransportType transportType = ETransportType.getETransportType(waresOrderVo.getTranType());
                if (transportType != null) {
                    waresOrderVo.setTranTypeStr(transportType.getLabel());
                }
            }

            // 预售状态
            if (waresOrderVo.getPreSaleStatus() != null) {
                EPresaleStatus presaleStatus = EPresaleStatus.getEPresaleStatus(waresOrderVo.getPreSaleStatus());
                if (presaleStatus != null) {
                    waresOrderVo.setPreSaleStatusStr(presaleStatus.getLabel());
                }
            }
            // 订单状态
            if (waresOrderVo.getOrderStatus() != null) {
                EOrderStatus orderStatus = EOrderStatus.getEOrderStatus(waresOrderVo.getOrderStatus());
                if (orderStatus != null) {
                    waresOrderVo.setOrderStatusStr(orderStatus.getLabel());
                }
            }
            // 支付方式
            if (waresOrderVo.getPayType() != null) {
                EOrderPayType orderPayType = EOrderPayType.getEnumByValue(waresOrderVo.getPayType());
                if (orderPayType != null) {
                    waresOrderVo.setPayTypeStr(orderPayType.getLabel());
                }
            }
            // 订单类型
            if (waresOrderVo.getOrderType() != null) {
                EOrderType orderType = EOrderType.getEnumByValue(waresOrderVo.getOrderType());
                if (orderType != null) {
                    waresOrderVo.setOrderTypeStr(orderType.getLabel());
                }
            }
            // 供应方式
            if (StringUtils.isNotBlank(waresOrderVo.getOperateScope()) && ESupplyWay.getESupplyWay(Integer.parseInt(waresOrderVo.getOperateScope())) != null) {
                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());
            }
        }
        List<WaresOrderInfoVo> waresOrderInfoList = resultList.stream().map(a -> {
            WaresOrderInfoVo waresOrderInfoVo = BeanUtil.copyProperties(a, WaresOrderInfoVo.class);
            // 计算产品总计
            waresOrderInfoVo.setProductPrice(waresOrderInfoVo.getProductPrice());
            waresOrderInfoVo.setProductTotalPrice(waresOrderInfoVo.getProductPrice().multiply(BigDecimal.valueOf(waresOrderInfoVo.getQuantity())));
            return waresOrderInfoVo;
        }).collect(Collectors.toList());
        ExcelUtil<WaresOrderInfoVo> util = new ExcelUtil<>(WaresOrderInfoVo.class);
        util.exportExcel(response, waresOrderInfoList, "商品订单详情导出");
    }


    /**
     * 订单选择
     *
     * @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 LambdaQueryWrapper<SaOrderRemarks>().eq(SaOrderRemarks::getPkOrder, 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 LambdaQueryWrapper<SaOrderRemarks>().eq(SaOrderRemarks::getPkOrder, saOrderRemarks.getPkOrder()));
        }
        return AjaxResult.success();
    }

    /**
     * 单品销量列表
     */
    @GetMapping("/single-item-stat")
    public TableDataInfo singleItemStat(SingleItemStatParam singleItemStatParam) {
        if (StringUtils.isBlank(singleItemStatParam.getSkuCode())
                && StringUtils.isBlank(singleItemStatParam.getProductName())
                && singleItemStatParam.getOrderType() == null
                && singleItemStatParam.getStartPayDate() == null
                && singleItemStatParam.getEndPayDate() == null
        ) {
            return getDataTable(new ArrayList<>());
        }
        // 订单单品统计
        if (singleItemStatParam.getStartPayDate() != null) {
            singleItemStatParam.setStartPayDate(DateUtils.getStartTime(singleItemStatParam.getStartPayDate()));
            singleItemStatParam.setStartPayDateStr(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.getStartTime(singleItemStatParam.getStartPayDate())));
        } else {
            Date nowDate = DateUtils.currentMonthFirstDate();
            singleItemStatParam.setStartPayDate(DateUtils.getStartTime(nowDate));
            singleItemStatParam.setStartPayDateStr(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.getStartTime(nowDate)));
        }
        if (singleItemStatParam.getEndPayDate() != null) {
            singleItemStatParam.setEndPayDate(DateUtils.getEndTime(singleItemStatParam.getEndPayDate()));
            singleItemStatParam.setEndPayDateStr(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.getEndTime(DateUtils.addDate(singleItemStatParam.getEndPayDate(), 1))));
        } else {
            Date nowDate = DateUtils.currentDate();
            singleItemStatParam.setEndPayDate(DateUtils.getEndTime(nowDate));
            singleItemStatParam.setEndPayDateStr(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.getEndTime(DateUtils.addDate(nowDate, 1))));
        }
        startPage();
        List<SingleItemStatVo> singleItemStatList = orderService.singleItemStat(singleItemStatParam);
        for (SingleItemStatVo singleItemStat : singleItemStatList) {
            singleItemStat.setTotal(singleItemStat.getGiftQuantity() + singleItemStat.getProductQuantity());
        }
        return getDataTable(singleItemStatList);
    }

    /**
     * 单品销量列表 汇总
     *
     * @param singleItemStatParam
     * @param
     */
    @GetMapping("/get-single-item-stat-total")
    public AjaxResult getSingleItemStatTotal(SingleItemStatParam singleItemStatParam) {
        if (StringUtils.isBlank(singleItemStatParam.getSkuCode())
                && StringUtils.isBlank(singleItemStatParam.getProductName())
                && singleItemStatParam.getOrderType() == null
                && singleItemStatParam.getStartPayDate() == null
                && singleItemStatParam.getEndPayDate() == null
        ) {
            return AjaxResult.success();
        }
        // 订单单品统计
        if (singleItemStatParam.getStartPayDate() != null) {
            singleItemStatParam.setStartPayDate(DateUtils.getStartTime(singleItemStatParam.getStartPayDate()));
            singleItemStatParam.setStartPayDateStr(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.getStartTime(singleItemStatParam.getStartPayDate())));
        } else {
            Date nowDate = DateUtils.currentMonthFirstDate();
            singleItemStatParam.setStartPayDate(DateUtils.getStartTime(nowDate));
            singleItemStatParam.setStartPayDateStr(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.getStartTime(nowDate)));
        }
        if (singleItemStatParam.getEndPayDate() != null) {
            singleItemStatParam.setEndPayDate(DateUtils.getEndTime(singleItemStatParam.getEndPayDate()));
            singleItemStatParam.setEndPayDateStr(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.getEndTime(DateUtils.addDate(singleItemStatParam.getEndPayDate(), 1))));
        } else {
            Date nowDate = DateUtils.currentDate();
            singleItemStatParam.setEndPayDate(DateUtils.getEndTime(nowDate));
            singleItemStatParam.setEndPayDateStr(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.getEndTime(DateUtils.addDate(nowDate, 1))));
        }
        // 商品数量
        Integer waresQuantity = 0;
        // 产品数量
        Integer productQuantity = 0;
        // 赠品数量
        Integer giftQuantity = 0;
        // 总计
        Integer total = 0;
        // 查询计算总计
        List<SingleItemStatVo> siList = orderService.singleItemStat(singleItemStatParam);
        for (SingleItemStatVo singleItemStatVo : siList) {
            singleItemStatVo.setTotal(singleItemStatVo.getGiftQuantity() + singleItemStatVo.getProductQuantity());
            waresQuantity += singleItemStatVo.getWaresQuantity();
            productQuantity += singleItemStatVo.getProductQuantity();
            giftQuantity += singleItemStatVo.getGiftQuantity();
            total += singleItemStatVo.getTotal();
        }
        // 计算总计
        SingleItemStatVo singleItemStatVo = new SingleItemStatVo();
        if (siList.size() > 0) {
            singleItemStatVo.setWaresQuantity(waresQuantity);
            singleItemStatVo.setProductQuantity(productQuantity);
            singleItemStatVo.setGiftQuantity(giftQuantity);
            singleItemStatVo.setTotal(total);
        }
        return AjaxResult.success(singleItemStatVo);
    }

    /**
     * 订单单品统计导出
     */
    @PostMapping("/single-item-stat-export")
    public void singleItemStatExport(SingleItemStatParam singleItemStatParam, HttpServletResponse response) {
        if (StringUtils.isBlank(singleItemStatParam.getSkuCode())
                && StringUtils.isBlank(singleItemStatParam.getProductName())
                && singleItemStatParam.getOrderType() == null
                && singleItemStatParam.getStartPayDate() == null
                && singleItemStatParam.getEndPayDate() == null
        ) {
            ExcelUtil<SingleItemStatVo> util = new ExcelUtil<>(SingleItemStatVo.class);
            util.exportExcel(response, new ArrayList<>(), "订单单品统计导出");
        }
        // 订单单品统计
        if (singleItemStatParam.getStartPayDate() != null) {
            singleItemStatParam.setStartPayDate(DateUtils.getStartTime(singleItemStatParam.getStartPayDate()));
            singleItemStatParam.setStartPayDateStr(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.getStartTime(singleItemStatParam.getStartPayDate())));
        } else {
            Date nowDate = DateUtils.currentMonthFirstDate();
            singleItemStatParam.setStartPayDate(DateUtils.getStartTime(nowDate));
            singleItemStatParam.setStartPayDateStr(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.getStartTime(nowDate)));
        }
        if (singleItemStatParam.getEndPayDate() != null) {
            singleItemStatParam.setEndPayDate(DateUtils.getEndTime(singleItemStatParam.getEndPayDate()));
            singleItemStatParam.setEndPayDateStr(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.getEndTime(DateUtils.addDate(singleItemStatParam.getEndPayDate(), 1))));
        } else {
            Date nowDate = DateUtils.currentDate();
            singleItemStatParam.setEndPayDate(DateUtils.getEndTime(nowDate));
            singleItemStatParam.setEndPayDateStr(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.getEndTime(DateUtils.addDate(nowDate, 1))));
        }

        List<SingleItemStatVo> singleItemStatList = orderService.singleItemStat(singleItemStatParam);

        int waresQuantity = 0;
        // 产品数量
        int productQuantity = 0;
        // 赠品数量
        int giftQuantity = 0;
        // 合计
        int total = 0;
        for (SingleItemStatVo singleItemStat : singleItemStatList) {
            singleItemStat.setTotal(singleItemStat.getGiftQuantity() + singleItemStat.getProductQuantity());
            // 商品数
            waresQuantity = waresQuantity + singleItemStat.getWaresQuantity();
            // 产品数
            productQuantity = productQuantity + singleItemStat.getProductQuantity();
            // 赠品数量
            giftQuantity = giftQuantity + singleItemStat.getGiftQuantity();
            // 合计
            total = total + singleItemStat.getTotal();
        }
        SingleItemStatVo sit = new SingleItemStatVo();
        sit.setWaresQuantity(waresQuantity);
        sit.setProductQuantity(productQuantity);
        sit.setGiftQuantity(giftQuantity);
        sit.setTotal(total);

        List<SingleItemStatVo> resultList = new ArrayList<>(singleItemStatList);
        resultList.add(sit);
        ExcelUtil<SingleItemStatVo> util = new ExcelUtil<>(SingleItemStatVo.class);
        util.exportExcel(response, resultList, "订单单品统计导出");
    }

    /**
     * 订单开票列表
     *
     * @return
     */
    @AccessPermissions("SpInvoicing")
    @Log(module = EOperationModule.ORDER_INVOICING, business = EOperationBusiness.ORDER_INVOICING, method = EOperationMethod.SELECT)
    @GetMapping("/order-invoicing-list")
    public TableDataInfo orderInvoicingList(OrderInvoicingParam param) {
        if (param.getStartCreateDate() != null) {
            param.setStartCreateDate(DateUtils.getStartTime(param.getStartCreateDate()));
        }
        if (param.getEndCreateDate() != null) {
            param.setEndCreateDate(DateUtils.getEndTime(param.getEndCreateDate()));
        }
        if (param.getStartPayDate() != null) {
            param.setStartPayDate(DateUtils.getStartTime(param.getStartPayDate()));
        }
        if (param.getEndPayDate() != null) {
            param.setEndPayDate(DateUtils.getEndTime(param.getEndPayDate()));
        }
        param.setPkCountry(SecurityUtils.getPkCountry());
        param.setSystemType(SecurityUtils.getSystemType());

        // 获取管理员权限（角色地区范围、体系列表、团队列表）
        UserAuthorityDTO userAuthorityDTO = iUserServiceApi.getUserAuthority(SecurityUtils.getUserId()).getData();
        param.setAreaScopeList(userAuthorityDTO.getRoleAreaScopeList());
        param.setVertexIdList(userAuthorityDTO.getVertexIdList());
        param.setTeamList(userAuthorityDTO.getUserTeamList());

        startPage();
        List<OrderInvoicingVO> resultList = orderService.listOrderInvoicing(param);

        Map<Integer, String> areaMap = areaServiceApi.getAreaMap(SecurityUtils.getPkCountry()).getData();
        for (OrderInvoicingVO vo : resultList) {
            // 地区处理
            if (vo.getRecProvince() != null) {
                vo.setRecProvinceName(areaMap.get(vo.getRecProvince()));
            }
            if (vo.getRecCity() != null) {
                vo.setRecCityName(areaMap.get(vo.getRecCity()));
            }
            if (vo.getRecCounty() != null) {
                vo.setRecCountyName(areaMap.get(vo.getRecCounty()));
            }
        }
        return getDataTable(resultList);
    }

}
