package com.fs.hisStore.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fs.common.annotation.Log;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.R;
import com.fs.common.core.domain.entity.SysRole;
import com.fs.common.core.domain.entity.SysUser;
import com.fs.common.core.domain.model.LoginUser;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.enums.BusinessType;
import com.fs.common.utils.CloudHostUtils;
import com.fs.common.utils.ParseUtils;
import com.fs.common.utils.ServletUtils;
import com.fs.common.utils.StringUtils;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.company.param.CompanyStoreOrderMoneyLogsListParam;
import com.fs.company.service.ICompanyMoneyLogsService;
import com.fs.company.vo.CompanyStoreOrderMoneyLogsVO;
import com.fs.config.cloud.CloudHostProper;
import com.fs.erp.domain.ErpDeliverys;
import com.fs.erp.domain.ErpOrderQuery;
import com.fs.erp.dto.ErpOrderQueryRequert;
import com.fs.erp.dto.ErpOrderQueryResponse;
import com.fs.erp.dto.df.DFConfigVo;
import com.fs.erp.service.IErpOrderService;
import com.fs.framework.web.service.TokenService;
import com.fs.his.domain.FsDfAccount;
import com.fs.his.domain.FsStoreOrderDf;
import com.fs.his.domain.FsUser;
import com.fs.his.enums.FsStoreOrderLogEnum;
import com.fs.his.param.FsStoreOrderSetErpPhoneParam;
import com.fs.his.service.IFsDfAccountService;
import com.fs.his.service.IFsExpressService;
import com.fs.his.service.IFsStoreOrderDfService;
import com.fs.his.service.IFsUserService;
import com.fs.his.service.impl.FsDfAccountServiceImpl;
import com.fs.his.utils.ConfigUtil;
import com.fs.his.vo.FsStoreOrderListAndStatisticsVo;
import com.fs.his.vo.FsStoreOrderListVO;
import com.fs.hisStore.config.FsErpConfig;
import com.fs.hisStore.domain.*;
import com.fs.his.dto.ExpressInfoDTO;
import com.fs.hisStore.dto.FsStoreOrderPayDeliveryDTO;
import com.fs.hisStore.dto.StoreOrderExpressExportDTO;
import com.fs.hisStore.dto.StoreOrderProductDTO;
import com.fs.hisStore.enums.ShipperCodeEnum;
import com.fs.hisStore.param.*;
import com.fs.hisStore.service.*;
import com.fs.hisStore.vo.*;
import com.fs.system.domain.SysConfig;
import com.fs.system.mapper.SysConfigMapper;
import com.fs.system.service.ISysRoleService;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

import static com.fs.his.utils.PhoneUtil.encryptPhone;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * 订单Controller
 *
 * @author fs
 * @date 2022-03-15
 */
@RestController
@RequestMapping("/store/store/storeOrder")
public class FsStoreOrderScrmController extends BaseController {
    @Autowired
    private IFsExpressService expressService;
    @Autowired
    private IFsStoreOrderScrmService fsStoreOrderService;
    @Autowired
    private IFsStoreOrderItemScrmService orderItemService;

    @Autowired
    private IFsUserService userService;

    @Autowired
    private IFsStoreOrderStatusScrmService orderStatusService;

    @Autowired
    IFsStorePaymentScrmService paymentService;

    @Autowired
    private CloudHostProper cloudHostProper;

    @Autowired
    private ICompanyMoneyLogsService moneyLogsService;
    @Autowired
    @Qualifier("erpOrderServiceImpl")
    private IErpOrderService gyOrderService;

    @Autowired
    @Qualifier("wdtErpOrderServiceImpl")
    private IErpOrderService wdtOrderService;
    @Autowired
    @Qualifier("hzOMSErpOrderServiceImpl")
    private IErpOrderService hzOMSErpOrderService;
    @Autowired
    @Qualifier("dfOrderServiceImpl")
    private IErpOrderService dfOrderService;
    @Autowired
    @Qualifier("k9OrderScrmServiceImpl")
    private IErpOrderService k9OrderService;
    @Autowired
    @Qualifier("JSTErpOrderServiceImpl")
    private IErpOrderService jSTOrderService;
    @Autowired
    private ConfigUtil configUtil;
    @Autowired
    private IFsStoreOrderAuditLogScrmService orderAuditLogService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private IFsStoreProductScrmService productScrmService;

    @Autowired
    SysConfigMapper sysConfigMapper;

    @Autowired
    private IFsDfAccountService fsDfAccountService;

    @Autowired
    private IFsStoreOrderDfService fsStoreOrderDfService;

    @Autowired
    private IFsStoreOrderLogsScrmService fsStoreOrderLogsService;

    @Value("${cloud_host.company_name}")
    private String signProjectName;

    private IErpOrderService getErpService(){
        //判断是否开启erp
        IErpOrderService erpOrderService = null;
        FsErpConfig erpConfig = configUtil.getErpConfig();
        Integer erpOpen = erpConfig.getErpOpen();
        if (erpOpen != null && erpOpen == 1) {
            //判断erp类型
            Integer erpType = erpConfig.getErpType();
            if (erpType != null) {
                if (erpType == 1){
                    //管易
                    erpOrderService =  gyOrderService;
                } else if (erpType == 2){
                    //旺店通
                    erpOrderService =  wdtOrderService;
                } else if (erpType == 3){
                    //
                    erpOrderService =  hzOMSErpOrderService;
                } else if (erpType == 4){
                    //代服
                    erpOrderService =  dfOrderService;
                }else if(erpType == 5){
                    erpOrderService=jSTOrderService;
                }else if(erpType == 6){
                    erpOrderService=k9OrderService;
                }
            }
        }
        return erpOrderService;
    }

    /**
     * 查询订单列表
     */
    @PreAuthorize("@ss.hasPermi('store:storeOrder:list')")
    @PostMapping("/list")
    public TableDataInfo list(@RequestBody FsStoreOrderParam param) {
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        if(!StringUtils.isEmpty(param.getCreateTimeRange())){
            param.setCreateTimeList(param.getCreateTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getPayTimeRange())){
            param.setPayTimeList(param.getPayTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getDeliveryImportTimeRange())){
            param.setDeliveryImportTimeList(param.getDeliveryImportTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getDeliverySendTimeRange())){
            param.setDeliverySendTimeList(param.getDeliverySendTimeRange().split("--"));
        }
        param.setNotHealth(1);
        List<FsStoreOrderVO> list = fsStoreOrderService.selectFsStoreOrderListVO(param);
        //金牛需求 区别其他项目 status = 6 (金牛代服管家) ,其他项目请避免使用订单状态status = 6
        TableDataInfo dataTable = getDataTable(list);
        if (CloudHostUtils.hasCloudHostName("康年堂")){
            dataTable.setMsg("knt");
        }
        if (list != null) {
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            for (FsStoreOrderVO vo : list) {
                if(vo.getPhone()!=null){
                    vo.setPhone(vo.getPhone().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
                }
                if(ObjectUtil.isNotEmpty(vo.getUserPhone())){
                    vo.setUserPhone(vo.getUserPhone().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
                }
                if (CloudHostUtils.hasCloudHostName("康年堂")){
                    //查询顺丰代服账号
                    FsStoreOrderDf df = fsStoreOrderDfService.selectFsStoreOrderDfByOrderId(vo.getId());
                    if (df != null){
                        vo.setErpAccount(df.getLoginAccount());
                    }
                }
                //
                if ((loginUser.getPermissions().contains("his:storeAfterSales:finance")) || loginUser.getPermissions().contains("*:*:*") && (vo.getCost() != null && vo.getTotalNum() != null)) {
                    vo.setFPrice(vo.getCost().multiply(BigDecimal.valueOf(vo.getTotalNum())));
                } else {
                    vo.setPayPostage(BigDecimal.ZERO);
                    vo.setCost(BigDecimal.ZERO);
                    vo.setFPrice(BigDecimal.ZERO);
                    vo.setPayDelivery(BigDecimal.ZERO);
                    vo.setBarCode("");
                    vo.setCateName("");
                    vo.setBankTransactionId("");
                }
            }
        }
        FsStoreOrderListAndStatisticsVo vo = new FsStoreOrderListAndStatisticsVo();
        BeanUtils.copyProperties(dataTable, vo);
        if (dataTable.getTotal()>0){
            Map<String, BigDecimal> statistics= fsStoreOrderService.selectFsStoreOrderStatistics(param);
            if (statistics != null && statistics.size() >= 3){
                vo.setPayPriceTotal(statistics.get("pay_price").toString());
                vo.setPayMoneyTotal(statistics.get("pay_money").toString());
                vo.setPayRemainTotal(statistics.get("pay_remain").toString());
            }else {
                vo.setPayPriceTotal("0");
                vo.setPayMoneyTotal("0");
                vo.setPayRemainTotal("0");
            }
            //商品数量合计
            String productStatistics= fsStoreOrderService.selectFsStoreOrderProductStatistics(param);
            if (StringUtils.isNotBlank(productStatistics)){
                vo.setProductInfo(productStatistics);
            } else {
                vo.setProductInfo("");
            }

        }
        return vo;
    }

    @PreAuthorize("@ss.hasPermi('store:storeOrder:payRemainList')")
    @GetMapping("/payRemainList")
    public TableDataInfo payRemainList(FsStoreOrderParam param) {
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        if(!StringUtils.isEmpty(param.getCreateTimeRange())){
            param.setCreateTimeList(param.getCreateTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getPayTimeRange())){
            param.setPayTimeList(param.getPayTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getDeliveryImportTimeRange())){
            param.setDeliveryImportTimeList(param.getDeliveryImportTimeRange().split("--"));
        }
        List<FsStoreOrderVO> list = fsStoreOrderService.selectPayRemainListVO(param);
        if (list != null) {
            for (FsStoreOrderVO vo : list) {
                if(vo.getPhone()!=null){
                    vo.setPhone(vo.getPhone().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
                }
                if(vo.getUserPhone()!=null){
                    vo.setUserPhone(vo.getUserPhone().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
                }

            }
        }
        return getDataTable(list);
    }

    /**
     * 导出付尾款订单列表
     */
    @Log(title = "付尾款订单", businessType = BusinessType.EXPORT)
    @GetMapping("/payRemainExport")
    public AjaxResult payRemainExport(FsStoreOrderParam param) {
        if(!StringUtils.isEmpty(param.getCreateTimeRange())){
            param.setCreateTimeList(param.getCreateTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getPayTimeRange())){
            param.setPayTimeList(param.getPayTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getDeliveryImportTimeRange())){
            param.setDeliveryImportTimeList(param.getDeliveryImportTimeRange().split("--"));
        }
        List<FsStorePayRemainOrderExportVO> list = fsStoreOrderService.selectFsStorePayRemainOrderListVOByExport(param);
        //对手机号脱敏
        if (list != null) {
            for (FsStorePayRemainOrderExportVO vo : list) {
                if (vo.getPhone() != null) {
                    vo.setPhone(vo.getPhone().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
                }
                if (vo.getUserPhone() != null) {
                    vo.setUserPhone(vo.getUserPhone().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
                }
                if (vo.getUserAddress()!=null){
                    vo.setUserAddress(ParseUtils.parseAddress(vo.getUserAddress()));
                }

            }
        }
        ExcelUtil<FsStorePayRemainOrderExportVO> util = new ExcelUtil<FsStorePayRemainOrderExportVO>(FsStorePayRemainOrderExportVO.class);
        return util.exportExcel(list, "付尾款订单数据");
    }

    /**
     * 导出订单列表
     */
    @PreAuthorize("@ss.hasPermi('store:storeOrder:export')")
    @Log(title = "订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public AjaxResult export(@RequestBody FsStoreOrderParam param) {
        if ("".equals(param.getBeginTime()) && "".equals(param.getEndTime())){
            param.setBeginTime(null);
            param.setEndTime(null);
        }
        if (fsStoreOrderService.isEntityNull(param)){
            return AjaxResult.error("请筛选数据导出");
        }
        if(!StringUtils.isEmpty(param.getCreateTimeRange())){
            param.setCreateTimeList(param.getCreateTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getPayTimeRange())){
            param.setPayTimeList(param.getPayTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getDeliverySendTimeRange())){
            param.setDeliverySendTimeList(param.getDeliverySendTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getDeliveryImportTimeRange())){
            param.setDeliveryImportTimeList(param.getDeliveryImportTimeRange().split("--"));
        }
        param.setNotHealth(1);
        List<FsStoreOrderErpExportVO> list = fsStoreOrderService.selectFsStoreOrderListVOByExport(param);

        //对手机号脱敏
        if (list != null) {
            SysRole sysRole = isCheckPermission();

            for (FsStoreOrderErpExportVO vo : list) {
                if (vo.getPhone() != null && sysRole.getIsCheckPhone() != 1) {
                    vo.setPhone(vo.getPhone().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
                }
                if (vo.getUserPhone() != null && sysRole.getIsCheckPhone() != 1) {
                    vo.setUserPhone(vo.getUserPhone().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
                }
                if (vo.getUserAddress()!=null && sysRole.getIsCheckAddress() != 1){
                    vo.setUserAddress(ParseUtils.parseAddress(vo.getUserAddress()));
                }
                //商品明细
                String orderItem = orderItemService.selectFsStoreOrderItemByOrderId(vo.getId());
                vo.setOrderItem(orderItem);

            }
        }
        String filter = param.getFilter();
        // 1. 处理filter参数：将逗号分隔的字符串拆分为ArrayList<String>
        ArrayList<String> filterList = new ArrayList<>();
        if (StringUtils.isNotBlank(filter)) {
            // 按逗号拆分，同时去除可能的空格（如filter传"orderId, orderCode"时兼容）
            String[] filterArr = filter.split("\\s*,\\s*");
            filterList.addAll(Arrays.asList(filterArr));
        }
        // 动态导出：根据选中的字段生成Excel
        ExcelUtil<FsStoreOrderErpExportVO> util = new ExcelUtil<FsStoreOrderErpExportVO>(FsStoreOrderErpExportVO.class);
        AjaxResult result;
        // 如果有选中的字段，只导出这些字段
        if (filter != null && !filter.isEmpty()) {
            return util.exportExcelSelectedColumns(list, "订单数据", filterList);
        } else {
            // 导出所有字段
            return util.exportExcel(list, "订单数据");
        }
    }

    @Autowired
    private ISysRoleService sysRoleService;
    private SysRole isCheckPermission() {
        SysRole sysRole = new SysRole();
        SysUser user = getLoginUser().getUser();
        boolean flag = user.isAdmin();
        if (flag) {
            sysRole.setIsCheckPhone(1);
            sysRole.setIsCheckAddress(1);
        } else {
            List<SysRole> roles = user.getRoles();
            if (roles != null && !roles.isEmpty()) {
                Long[] roleIds = roles.stream().map(SysRole::getRoleId).toArray(Long[]::new);
                return sysRoleService.getIsCheckPermission(roleIds);
            }
        }
        return sysRole;
    }


    /**
     * 导出订单列表（明文）
     */
    @PreAuthorize("@ss.hasPermi('store:storeOrder:export:details')")
    @Log(title = "订单", businessType = BusinessType.EXPORT)
    @PostMapping("/exportDetails")
    public AjaxResult exportDetails(@RequestBody FsStoreOrderParam param) {
        if ("".equals(param.getBeginTime()) && "".equals(param.getEndTime())){
            param.setBeginTime(null);
            param.setEndTime(null);
        }
        if (fsStoreOrderService.isEntityNull(param)){
            return AjaxResult.error("请筛选数据导出");
        }
        if(!StringUtils.isEmpty(param.getCreateTimeRange())){
            param.setCreateTimeList(param.getCreateTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getPayTimeRange())){
            param.setPayTimeList(param.getPayTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getDeliverySendTimeRange())){
            param.setDeliverySendTimeList(param.getDeliverySendTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getDeliveryImportTimeRange())){
            param.setDeliveryImportTimeList(param.getDeliveryImportTimeRange().split("--"));
        }
        param.setNotHealth(1);
        List<FsStoreOrderErpExportVO> list = fsStoreOrderService.selectFsStoreOrderListVOByExport(param);
        String filter = param.getFilter();
        // 1. 处理filter参数：将逗号分隔的字符串拆分为ArrayList<String>
        ArrayList<String> filterList = new ArrayList<>();
        if (StringUtils.isNotBlank(filter)) {
            // 按逗号拆分，同时去除可能的空格（如filter传"orderId, orderCode"时兼容）
            String[] filterArr = filter.split("\\s*,\\s*");
            filterList.addAll(Arrays.asList(filterArr));
        }
        // 动态导出：根据选中的字段生成Excel
        ExcelUtil<FsStoreOrderErpExportVO> util = new ExcelUtil<FsStoreOrderErpExportVO>(FsStoreOrderErpExportVO.class);
        AjaxResult result;
        // 如果有选中的字段，只导出这些字段
        if (filter != null && !filter.isEmpty()) {
            return util.exportExcelSelectedColumns(list, "订单数据", filterList);
        } else {
            // 导出所有字段
            return util.exportExcel(list, "订单数据");
        }
    }

    @PreAuthorize("@ss.hasPermi('store:storeOrder:exportItems')")
    @Log(title = "订单明细导出", businessType = BusinessType.EXPORT)
    @GetMapping("/exportItems")
    public AjaxResult exportItems(FsStoreOrderParam param) {
        if ("".equals(param.getBeginTime()) && "".equals(param.getEndTime())){
            param.setBeginTime(null);
            param.setEndTime(null);
        }
        if (fsStoreOrderService.isEntityNull(param)){
            return AjaxResult.error("请筛选数据导出");
        }
        if(!StringUtils.isEmpty(param.getCreateTimeRange())){
            param.setCreateTimeList(param.getCreateTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getPayTimeRange())){
            param.setPayTimeList(param.getPayTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getDeliveryImportTimeRange())){
            param.setDeliveryImportTimeList(param.getDeliveryImportTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getDeliverySendTimeRange())){
            param.setDeliverySendTimeList(param.getDeliverySendTimeRange().split("--"));
        }
        param.setNotHealth(1);
        List<FsStoreOrderItemExportVO> list = orderItemService.selectFsStoreOrderItemListExportVO(param);
        //对手机号脱敏
        if (list != null) {
            SysRole sysRole = isCheckPermission();
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());

            for (FsStoreOrderItemExportVO vo : list) {
                if (vo.getUserPhone() != null && sysRole.getIsCheckPhone() != 1) {
                    String phone = vo.getUserPhone().replaceAll("(\\d{3})\\d*(\\d{1})", "$1****$2");
                    vo.setUserPhone(phone);
                }
                if (vo.getUserAddress()!=null && sysRole.getIsCheckAddress() != 1){
                    vo.setUserAddress(ParseUtils.parseAddress(vo.getUserAddress()));
                }
                if (!StringUtils.isEmpty(vo.getJsonInfo())) {
                    try {
                        StoreOrderProductDTO orderProductDTO = JSONObject.parseObject(vo.getJsonInfo(), StoreOrderProductDTO.class);
                        BeanUtil.copyProperties(orderProductDTO, vo);
                    } catch (Exception e) {
                    }
                }
                //
                if ((loginUser.getPermissions().contains("his:storeAfterSales:finance") || loginUser.getPermissions().contains("*:*:*") ) && !Objects.isNull(vo.getCost())) {
                    vo.setFPrice(vo.getCost().multiply(BigDecimal.valueOf(vo.getTotalNum())));
                } else {
                    vo.setPayPostage(BigDecimal.ZERO);
                    vo.setCost(BigDecimal.ZERO);
                    vo.setFPrice(BigDecimal.ZERO);
                    vo.setBarCode("");
                    vo.setCateName("");
                    vo.setBankTransactionId("");
                }
            }
        }
        ExcelUtil<FsStoreOrderItemExportVO> util = new ExcelUtil<FsStoreOrderItemExportVO>(FsStoreOrderItemExportVO.class);
        return util.exportExcel(list, "订单明细数据");
    }

    /**
     * 订单明细导出（明文）
     * **/
    @PreAuthorize("@ss.hasPermi('store:storeOrder:exportItems:details')")
    @Log(title = "订单明细导出", businessType = BusinessType.EXPORT)
    @GetMapping("/exportItemsDetails")
    public AjaxResult exportItemsDetails(FsStoreOrderParam param) {
        if ("".equals(param.getBeginTime()) && "".equals(param.getEndTime())){
            param.setBeginTime(null);
            param.setEndTime(null);
        }
        if (fsStoreOrderService.isEntityNull(param)){
            return AjaxResult.error("请筛选数据导出");
        }
        if(!StringUtils.isEmpty(param.getCreateTimeRange())){
            param.setCreateTimeList(param.getCreateTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getPayTimeRange())){
            param.setPayTimeList(param.getPayTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getDeliveryImportTimeRange())){
            param.setDeliveryImportTimeList(param.getDeliveryImportTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getDeliverySendTimeRange())){
            param.setDeliverySendTimeList(param.getDeliverySendTimeRange().split("--"));
        }
        param.setNotHealth(1);
        List<FsStoreOrderItemExportVO> list = orderItemService.selectFsStoreOrderItemListExportVO(param);
        if("北京卓美".equals(signProjectName)){
            List<FsStoreOrderItemExportZMVO> zmvoList = list.stream()
                    .map(vo -> {
                        FsStoreOrderItemExportZMVO zmvo = new FsStoreOrderItemExportZMVO();
                        try {
                            BeanUtil.copyProperties( vo,zmvo);
                        } catch (Exception e) {
                            // 处理异常
                            e.printStackTrace();
                        }
                        return zmvo;
                    })
                    .collect(Collectors.toList());
            //对手机号脱敏
            if (zmvoList != null) {
                LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
                for (FsStoreOrderItemExportZMVO vo : zmvoList) {
                    if (!StringUtils.isEmpty(vo.getJsonInfo())) {
                        try {
                            StoreOrderProductDTO orderProductDTO = JSONObject.parseObject(vo.getJsonInfo(), StoreOrderProductDTO.class);
                            BeanUtil.copyProperties(orderProductDTO, vo);
                        } catch (Exception e) {
                        }
                    }
                    //
                    if ((loginUser.getPermissions().contains("his:storeAfterSales:finance") || loginUser.getPermissions().contains("*:*:*") ) && !Objects.isNull(vo.getCost())) {
                        vo.setFPrice(vo.getCost().multiply(BigDecimal.valueOf(vo.getTotalNum())));
                    } else {
                        vo.setPayPostage(BigDecimal.ZERO);
                        vo.setCost(BigDecimal.ZERO);
                        vo.setFPrice(BigDecimal.ZERO);
                        vo.setBarCode("");
                        vo.setCateName("");
                        vo.setBankTransactionId("");
                    }
                }
            }
            ExcelUtil<FsStoreOrderItemExportZMVO> util = new ExcelUtil<FsStoreOrderItemExportZMVO>(FsStoreOrderItemExportZMVO.class);
            return util.exportExcel(zmvoList, "订单明细数据");
        }

        //对手机号脱敏
        if (list != null) {
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            for (FsStoreOrderItemExportVO vo : list) {
                if (!StringUtils.isEmpty(vo.getJsonInfo())) {
                    try {
                        StoreOrderProductDTO orderProductDTO = JSONObject.parseObject(vo.getJsonInfo(), StoreOrderProductDTO.class);
                        BeanUtil.copyProperties(orderProductDTO, vo);
                    } catch (Exception e) {
                    }
                }
                //
                if ((loginUser.getPermissions().contains("his:storeAfterSales:finance") || loginUser.getPermissions().contains("*:*:*") ) && !Objects.isNull(vo.getCost())) {
                    vo.setFPrice(vo.getCost().multiply(BigDecimal.valueOf(vo.getTotalNum())));
                } else {
                    vo.setPayPostage(BigDecimal.ZERO);
                    vo.setCost(BigDecimal.ZERO);
                    vo.setFPrice(BigDecimal.ZERO);
                    vo.setBarCode("");
                    vo.setCateName("");
                    vo.setBankTransactionId("");
                }
            }
        }
        ExcelUtil<FsStoreOrderItemExportVO> util = new ExcelUtil<FsStoreOrderItemExportVO>(FsStoreOrderItemExportVO.class);
        return util.exportExcel(list, "订单明细数据");
    }

    @GetMapping("/orderItemsNum")
    public R orderItemsNum(FsStoreOrderParam param) {

        if(!StringUtils.isEmpty(param.getCreateTimeRange())){
            param.setCreateTimeList(param.getCreateTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getPayTimeRange())){
            param.setPayTimeList(param.getPayTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getDeliveryImportTimeRange())){
            param.setDeliveryImportTimeList(param.getDeliveryImportTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getDeliverySendTimeRange())){
            param.setDeliverySendTimeList(param.getDeliverySendTimeRange().split("--"));
        }
        param.setNotHealth(1);
        Long orderItemsNum = orderItemService.countFsStoreOrderItemListExportVO(param);
        return R.ok().put("orderItemsNum","订单明细数目："+orderItemsNum);
    }

    /**
     * 获取订单详细信息
     */
    @PreAuthorize("@ss.hasPermi('store:storeOrder:query')")
    @GetMapping(value = "/{id}")
    public R getInfo(@PathVariable("id") Long id) {
        FsStoreOrderScrm order = fsStoreOrderService.selectFsStoreOrderById(id);
        order.setUserPhone(ParseUtils.parsePhone(order.getUserPhone()));
        order.setUserAddress(ParseUtils.parseAddress(order.getUserAddress()));
        FsUser user = userService.selectFsUserById(order.getUserId());
        if (user != null) {
            user.setPhone(ParseUtils.parsePhone(user.getPhone()));
        }
        FsStoreOrderItemScrm itemMap = new FsStoreOrderItemScrm();
        itemMap.setOrderId(order.getId());
        List<FsStoreOrderItemScrm> items = orderItemService.selectFsStoreOrderItemList(itemMap);
        FsStoreOrderStatusScrm statusMap = new FsStoreOrderStatusScrm();
        statusMap.setOrderId(order.getId());
        List<FsStoreOrderStatusScrm> logs = orderStatusService.selectFsStoreOrderStatusList(statusMap);
        List<FsStorePaymentScrm> payments=paymentService.selectFsStorePaymentByOrderId(order.getId());
        List<CompanyStoreOrderMoneyLogsVO> tuiMoneyLogs=new ArrayList<>();
        if(order.getCompanyId()!=null){
            CompanyStoreOrderMoneyLogsListParam moneyLogsMap=new CompanyStoreOrderMoneyLogsListParam();
            moneyLogsMap.setCompanyId(order.getCompanyId());
            moneyLogsMap.setBusinessId(order.getId().toString());
            tuiMoneyLogs=moneyLogsService.selectCompanyStoreOrderMoneyLogsList(moneyLogsMap);
        }

        List<FsStoreOrderAuditLogVO> auditLogs = orderAuditLogService.selectStoreOrderAuditLogVOByOrderId(order.getId());
        return R.ok().put("order", order).put("items", items).put("logs", logs).put("user", user).put("payments",payments).put("tuiMoneyLogs",tuiMoneyLogs)
                .put("auditLogs",auditLogs);
    }

    @GetMapping(value = "/queryAddress/{id}")
    @PreAuthorize("@ss.hasPermi('store:storeOrder:queryAddress')")
    public R getAddress(@PathVariable("id") Long id)
    {
        FsStoreOrderScrm order = fsStoreOrderService.selectFsStoreOrderById(id);
        String address = order.getUserAddress();
        return R.ok().put("address",address);
    }

    @GetMapping(value = "/queryPhone/{id}")
    @Log(title = "查看电话", businessType = BusinessType.GRANT)
    @PreAuthorize("@ss.hasPermi('store:storeOrder:queryPhone')")
    public R getPhone(@PathVariable("id") Long id)
    {
        FsStoreOrderScrm order = fsStoreOrderService.selectFsStoreOrderById(id);
        String userPhone = order.getUserPhone();
        return R.ok().put("userPhone",userPhone);
    }

    @PreAuthorize("@ss.hasPermi('store:storeOrder:express')")
    @GetMapping(value = "/getExpress/{id}")
    public R getExpress(@PathVariable("id") Long id) {
        FsStoreOrderScrm order = fsStoreOrderService.selectFsStoreOrderById(id);
        ExpressInfoDTO expressInfoDTO = null;
        if (StringUtils.isNotEmpty(order.getDeliveryId())) {
            String lastFourNumber = "";
            if (order.getDeliverySn().equals(ShipperCodeEnum.SF.getValue()) || order.getDeliverySn().equals(ShipperCodeEnum.ZTO.getValue())) {
                lastFourNumber = order.getUserPhone();
                if (lastFourNumber.length() == 11) {
                    lastFourNumber = StrUtil.sub(lastFourNumber, lastFourNumber.length(), -4);
                }
            }
            expressInfoDTO = expressService.getExpressInfo(order.getOrderCode(), order.getDeliverySn(), order.getDeliveryId(), lastFourNumber);
        }
        return R.ok().put("data", expressInfoDTO);
    }

    /**
     * 新增订单
     */
    @PreAuthorize("@ss.hasPermi('store:storeOrder:add')")
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FsStoreOrderScrm fsStoreOrder) {
        return toAjax(fsStoreOrderService.insertFsStoreOrder(fsStoreOrder));
    }

    /**
     * 修改订单
     */
    @PreAuthorize("@ss.hasPermi('store:storeOrder:edit')")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FsStoreOrderScrm fsStoreOrder) {
        return toAjax(fsStoreOrderService.updateFsStoreOrder(fsStoreOrder));
    }
    /**
     * 修改订单itemJson
     */
    @Log(title = "修改订单itemJson", businessType = BusinessType.UPDATE)
    @GetMapping("/updateStoreOrderItemJson/{orderId}/{backendEditProductType}")
    public AjaxResult updateStoreOrderItemJson(@PathVariable("orderId") Long orderId,@PathVariable("backendEditProductType") Integer backendEditProductType) {
        return toAjax(fsStoreOrderService.updateStoreOrderItemJson(orderId,backendEditProductType));
    }
    /**
     * 修改物流
     * @param fsStoreOrder
     * @return
     */
    @Log(title = "修改物流", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('store:storeOrder:editDeliveryId')")
    @PutMapping("/editDeliveryId")
    public AjaxResult editDeliveryId(@RequestBody FsStoreOrderScrm fsStoreOrder) {
        return toAjax(fsStoreOrderService.updateFsStoreOrder(fsStoreOrder));
    }

    @Log(title = "同步管易物流单号", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('store:storeOrder:updateErpOrder')")
    @PostMapping("/updateErpOrder")
    public R updateErpOrder(@Validated @RequestBody FsStoreOrderExpressEditParam param) {
        FsStoreOrderScrm order = fsStoreOrderService.selectFsStoreOrderById(param.getOrderId());
        FsErpConfig erpConfig = configUtil.getErpConfig();
        List<Long> noErpCompany = erpConfig.getNoErpCompany();
        if (noErpCompany.contains(order.getCompanyId())) {
            logger.info("订单:{},相关公司不推送erp", order.getOrderCode());
            return R.ok("订单:"+ order.getOrderCode()+"相关公司不推送erp");
        }
        IErpOrderService erpOrderService = getErpService();
        ErpOrderQueryRequert request = new ErpOrderQueryRequert();
        request.setCode(order.getExtendOrderId());
        ErpOrderQueryResponse response = erpOrderService.getScrmOrder(request);
        if(response.getOrders()!=null&&response.getOrders().size()>0){
            for(ErpOrderQuery orderQuery : response.getOrders()){
                if(orderQuery.getDeliverys()!=null&&orderQuery.getDeliverys().size()>0){
                    for(ErpDeliverys delivery:orderQuery.getDeliverys()){
                        if(delivery.getDelivery()&& StringUtils.isNotEmpty(delivery.getMail_no())){
                            //更新商订单状态
                            fsStoreOrderService.updateDeliveryOrder(param.getOrderId(), delivery.getMail_no(),delivery.getExpress_code(),delivery.getExpress_name());
                            return R.ok();
                        }
                    }

                }
            }
        }
        return R.error("未查询到快递信息");
    }

    /**
     * 删除订单
     */
    @PreAuthorize("@ss.hasPermi('store:storeOrder:remove')")
    @Log(title = "订单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(fsStoreOrderService.deleteFsStoreOrderByIds(ids));
    }


    @PostMapping("/createUserOrder")
    public R createUserOrder(@Validated @RequestBody FsStoreOrderCreateUserParam param, HttpServletRequest request) {
        return fsStoreOrderService.createUserOrder(param);
    }

    @Log(title = "确认订单", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('store:storeOrder:finishOrder')")
    @PostMapping("/finishOrder")
    public R finishOrder(@Validated @RequestBody FsStoreOrderFinishParam param, HttpServletRequest request) {
        return fsStoreOrderService.finishOrder(param.getOrderId());
    }

    @PreAuthorize("@ss.hasPermi('store:storeOrder:auditPayRemain')")
    @PostMapping("/auditPayRemain")
    public R auditPayRemain(@Validated @RequestBody FsStoreOrderAuditPayRemainParam param, HttpServletRequest request) {
        return fsStoreOrderService.auditPayRemain(param.getOrderId());
    }


    @Log(title = "导入", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('store:storeOrder:importExpress')")
    @PostMapping("/importExpress")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<StoreOrderExpressExportDTO> util = new ExcelUtil<StoreOrderExpressExportDTO>(StoreOrderExpressExportDTO.class);
        List<StoreOrderExpressExportDTO> list = util.importExcel(file.getInputStream());
        String message = fsStoreOrderService.importExpress(list, updateSupport);
        return AjaxResult.success(message);
    }

    //下载模板
    @GetMapping("/importTemplate")
    public AjaxResult importTemplate() {
        ExcelUtil<StoreOrderExpressExportDTO> util = new ExcelUtil<StoreOrderExpressExportDTO>(StoreOrderExpressExportDTO.class);
        return util.importTemplateExcel("物流回单数据");
    }


    @GetMapping("/getStoreOrder")
    public R getStoreOrder(@RequestParam("orderCode") String orderCode) {
        FsStoreOrderVO vo = fsStoreOrderService.selectFsStoreOrderVOByOrderCode(orderCode);
        return R.ok().put("data", vo);
    }

    @Log(title = "冻结、解冻佣金", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('store:storeOrder:editTuiMoney')")
    @PostMapping("/editTuiMoney")
    public R editTuiMoney(@Validated @RequestBody FsStoreOrderEditTuiMoneyParam param, HttpServletRequest request) {
        return fsStoreOrderService.editTuiMoney(param);
    }

    @Log(title = "退款", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('store:storeOrder:refundOrderMoney')")
    @PostMapping("/refundOrderMoney")
    public synchronized R refundOrderMoney(@Validated @RequestBody FsStoreOrderRefundParam param, HttpServletRequest request) {
        return fsStoreOrderService.refundOrderMoney(param.getOrderId());
    }
    @PreAuthorize("@ss.hasPermi('store:storeOrder:getEroOrder')")
    @GetMapping("/getEroOrder")
    public R getEroOrder(@RequestParam("extendOrderId") String extendOrderId) {
        IErpOrderService erpOrderService = getErpService();
        ErpOrderQueryRequert request = new ErpOrderQueryRequert();
        request.setCode(extendOrderId);
        ErpOrderQueryResponse response = erpOrderService.getScrmOrder(request);
        return R.ok().put("data",response);
    }

    @PreAuthorize("@ss.hasPermi('store:storeOrder:updateExpress')")
    @PostMapping("/updateExpress")
    public R updateExpress(@Validated @RequestBody FsStoreOrderExpressEditParam param, HttpServletRequest request) {
        return fsStoreOrderService.updateExpress(param);
    }

    @Log(title = "同步物流", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('store:storeOrder:syncExpress')")
    @PostMapping("/syncExpress")
    public R syncExpress(@Validated @RequestBody FsStoreOrderExpressEditParam param, HttpServletRequest request) {
        return fsStoreOrderService.syncExpress(param);
    }


    @Log(title = "分佣", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('store:storeOrder:addTuiMoney')")
    @PostMapping("/addTuiMoney")
    public R addTuiMoney(@Validated @RequestBody FsStoreOrderAddTuiMoneyParam param, HttpServletRequest request) {
        return fsStoreOrderService.addTuiMoney(param);
    }


    @GetMapping("/getCustomerOrderList")
    public TableDataInfo getCustomerOrderList(FsStoreOrderParam param) {
//        startPage();
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<FsStoreOrderVO> list = fsStoreOrderService.selectFsCustomerStoreOrderListVO(param);
        if (list != null) {
            for (FsStoreOrderVO vo : list) {
                if(vo.getPhone()!=null){
                    vo.setPhone(vo.getPhone().replaceAll("(\\d{3})\\d*(\\d{1})", "$1****$2"));
                }
                if(vo.getUserPhone()!=null){
                    vo.setUserPhone(vo.getUserPhone().replaceAll("(\\d{3})\\d*(\\d{1})", "$1****$2"));
                }

            }
        }
        return getDataTable(list);
    }

    @Log(title = "手动推管易", businessType = BusinessType.INSERT)
    @ApiOperation("创建ERP订单")
    @PreAuthorize("@ss.hasPermi('store:storeOrder:createErpOrder')")
    @GetMapping("/createErpOrder")
    public R createErpOrder(@RequestParam("orderCode") String orderCode) throws Exception
    {
        logger.info("手动推管易订单号：{}",orderCode);
        FsStoreOrderScrm order=fsStoreOrderService.selectFsStoreOrderByOrderCode(orderCode);
        return fsStoreOrderService.createOmsOrder(order.getId());
    }

    /**
     * 订单维度分页查询接口
     * @param param 查询条件
     * @return AjaxResult
     * **/
    @GetMapping("/orderDimensionStatisticsList")
    public TableDataInfo orderDimensionStatisticsList(OrderStatisticsParam param){
        return getDataTable(fsStoreOrderService.selectOrderDimensionStatisticsList(param));
    }

    /**
     * 导出订单维度统计接口
     * @param param 查询条件
     * @return AjaxResult
     * **/
    @Log(title = "订单维度统计", businessType = BusinessType.EXPORT)
    @GetMapping("/orderDimensionStatisticsExport")
    public AjaxResult orderDimensionStatisticsExport(OrderStatisticsParam param){
        List<OrderStatisticsVo> list = fsStoreOrderService.selectOrderDimensionStatisticsList(param);
//        switch (param.getGroupType()){
//            case 2:
//                List<OrderCateStatisticsVo> cateStatisticsVoList = convertTo(list,OrderCateStatisticsVo.class);
//                ExcelUtil<OrderCateStatisticsVo> cateUtil = new ExcelUtil<>(OrderCateStatisticsVo.class);
//                return cateUtil.exportExcel(cateStatisticsVoList, "订单标签维度统计");
//            case 3:
//                List<OrderProductStatisticsVo> productStatisticsVoList =  convertTo(list,OrderProductStatisticsVo.class);
//                ExcelUtil<OrderProductStatisticsVo> productUtil = new ExcelUtil<>(OrderProductStatisticsVo.class);
//                return productUtil.exportExcel(productStatisticsVoList, "订单商品维度统计");
//        }

        ExcelUtil<OrderStatisticsVo> util = new ExcelUtil<>(OrderStatisticsVo.class);
        return util.exportExcel(list, "订单员工维度统计");
    }

    /**
     * 发货单导出接口
     * **/
    @PreAuthorize("@ss.hasPermi('store:storeOrder:exportShippingOrder')")
    @GetMapping("/exportShippingOrder")
    public AjaxResult exportShippingOrder(FsStoreOrderParam param){
        if ("".equals(param.getBeginTime()) && "".equals(param.getEndTime())){
            param.setBeginTime(null);
            param.setEndTime(null);
        }
        if(fsStoreOrderService.isEntityNull(param)){
            param = new FsStoreOrderParam();
        }
        if(!StringUtils.isEmpty(param.getCreateTimeRange())){
            param.setCreateTimeList(param.getCreateTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getPayTimeRange())){
            param.setPayTimeList(param.getPayTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getDeliveryImportTimeRange())){
            param.setDeliveryImportTimeList(param.getDeliveryImportTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getDeliverySendTimeRange())){
            param.setDeliverySendTimeList(param.getDeliverySendTimeRange().split("--"));
        }
        param.setNotHealth(1);
        List<FsStoreOrderDeliveryNoteExportVO> storeOrderDeliveryNoteExportVOList=fsStoreOrderService.getDeliveryNote(param);
        ExcelUtil<FsStoreOrderDeliveryNoteExportVO> util = new ExcelUtil<>(FsStoreOrderDeliveryNoteExportVO.class);
        //通过商品ID获取关键字
        String firstKeyword = storeOrderDeliveryNoteExportVOList.stream()
                .map(FsStoreOrderDeliveryNoteExportVO::getKeyword)
                .findFirst()
                .orElse("无订单");
        String fileName="077AC"+firstKeyword+new SimpleDateFormat("yyyyMMdd").format(new Date());
        return util.exportExcel(storeOrderDeliveryNoteExportVOList, fileName);
    }

    /**
     * 对象列表类型转换
     */
    public static <T> List<T> convertTo(List<?> sourceList, Class<T> targetClass) {
        if (sourceList == null || sourceList.isEmpty()) {
            return Collections.emptyList();
        }

        List<T> resultList = new ArrayList<>(sourceList.size());
        try {
            for (Object source : sourceList) {
                T target = targetClass.getDeclaredConstructor().newInstance();
                BeanUtils.copyProperties(source, target);
                resultList.add(target);
            }
        } catch (Exception e) {
            throw new RuntimeException("数据转换异常", e);
        }
        return resultList;
    }

    /**
     * 查询erp默认手机号
     * @return
     */
    @GetMapping(value = "/queryErpPhone")
    public AjaxResult queryErpPhone()
    {
        SysConfig sysConfig = sysConfigMapper.selectConfigByConfigKey("erp.phone");
        List<String> list = new ArrayList<>();
        if(sysConfig!=null){
            String configValue = sysConfig.getConfigValue();
            if(StringUtils.isNotEmpty(configValue)){
                list = JSON.parseArray(configValue, String.class);
            }
        }
        return AjaxResult.success(list);
    }

    /**
     * 设置erp默认手机号
     * @param phoneList
     * @return
     */
    @PostMapping(value = "/saveErpPhone")
    public AjaxResult saveErpPhone(@RequestBody List<String> phoneList)
    {
        //去重
        phoneList = phoneList.stream().distinct().collect(Collectors.toList());
        SysConfig sysConfig = sysConfigMapper.selectConfigByConfigKey("erp.phone");
        sysConfig.setConfigValue(JSON.toJSONString(phoneList));
        return AjaxResult.success(sysConfigMapper.updateConfig(sysConfig));
    }

    /**
     * 批量设置erp手机号
     */
    @PreAuthorize("@ss.hasPermi('his:storeOrder:createErpOrder')")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PostMapping("/editErpPhone")
    public AjaxResult editErpPhone(@RequestBody FsStoreOrderScrmSetErpPhoneParam param)
    {
        param.setOpeName(getLoginUser().getUser().getNickName());
        List<String> erpPhone = param.getErpPhone();
        if (erpPhone == null || erpPhone.isEmpty()) {
            return AjaxResult.error("请选择手机号");
        }
        return toAjax(fsStoreOrderService.batchUpdateErpByOrderIds(param));
    }

    /**
     * 获取erp账户
     */
    @GetMapping("/getErpAccount")
    public R getErpAccount()
    {
        List<String> list = new ArrayList<>();
        if (CloudHostUtils.hasCloudHostName("金牛明医","康年堂")) {
            List<FsDfAccount> erpAccounts = fsDfAccountService.selectFsDfAccountList(null);
            list = erpAccounts.stream().map(FsDfAccount::getLoginAccount).collect(Collectors.toList());
        }
        return R.ok().put("data", list);
    }

    @Log(title = "手动推管易", businessType = BusinessType.INSERT)
    @ApiOperation("批量创建ERP订单")
    @PreAuthorize("@ss.hasPermi('his:storeOrder:createErpOrder')")
    @PostMapping(value = "/batchCreateErpOrder")
    public R batchCreateErpOrder(@RequestBody FsStoreOrderScrmSetErpPhoneParam param)
    {
        String nickName = getLoginUser().getUser().getNickName();
        String loginAccount = param.getLoginAccount();
        if (StringUtils.isBlank(loginAccount)){
            return R.error("未选择推送erp账户");
        }
        FsStoreOrderDf df = getDFInfo(loginAccount);
        if (df.getLoginAccount() == null){
            return R.error("未查询到所选erp账户");
        }
        List<Long> orderIds = param.getOrderIds();
        if (orderIds  == null || orderIds.isEmpty()) {
            if(!StringUtils.isEmpty(param.getCreateTimeRange())){
                param.setCreateTimeList(param.getCreateTimeRange().split("--"));
            }
            if(!StringUtils.isEmpty(param.getPayTimeRange())){
                param.setPayTimeList(param.getPayTimeRange().split("--"));
            }
            if(!StringUtils.isEmpty(param.getDeliveryImportTimeRange())){
                param.setDeliveryImportTimeList(param.getDeliveryImportTimeRange().split("--"));
            }
            if(!StringUtils.isEmpty(param.getDeliverySendTimeRange())){
                param.setDeliverySendTimeList(param.getDeliverySendTimeRange().split("--"));
            }
            param.setNotHealth(1);
            List<FsStoreOrderVO> list = fsStoreOrderService.selectFsStoreOrderListVO(param);
            orderIds = list.stream().map(FsStoreOrderVO::getId).collect(Collectors.toList());
        }
        if (orderIds.isEmpty()){
            return R.ok();
        }
        orderIds.forEach(orderId->{
            try {
                df.setOrderId(orderId);
                FsStoreOrderDf temp = fsStoreOrderDfService.selectFsStoreOrderDfByOrderId(df.getOrderId());
                if (temp == null){
                    df.setParcelQuantity(param.getParcelQuantity()); //设置包裹数量
                    fsStoreOrderDfService.insertFsStoreOrderDf(df);
                    fsStoreOrderLogsService.create(orderId, FsStoreOrderLogEnum.SET_PUSH_ACCOUNT.getValue(),
                            nickName + " " +FsStoreOrderLogEnum.SET_PUSH_ACCOUNT.getDesc() + ":" + df.getLoginAccount());
                }
                fsStoreOrderService.createOmsOrder(orderId);
                fsStoreOrderLogsService.create(orderId, FsStoreOrderLogEnum.PUSH_ORDER_ERP.getValue(),
                        nickName + " " +FsStoreOrderLogEnum.PUSH_ORDER_ERP.getDesc() + ":" + df.getLoginAccount());
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }

        });
        return R.ok();
    }


    @ApiOperation("批量设置订单账户")
    @PreAuthorize("@ss.hasPermi('his:storeOrder:createErpOrder')")
    @PostMapping(value = "/batchSetErpOrder")
    public R batchSetErpOrder(@RequestBody FsStoreOrderScrmSetErpPhoneParam param)
    {
        String nickName = getLoginUser().getUser().getNickName();
        String loginAccount = param.getLoginAccount();
        if (StringUtils.isBlank(loginAccount)){
            return R.error("未选择erp账户");
        }
        FsStoreOrderDf df = getDFInfo(loginAccount);
        if (df.getLoginAccount() == null){
            return R.error("未查询到所选erp账户");
        }
        List<Long> orderIds = param.getOrderIds();
        if (orderIds  == null || orderIds.isEmpty()) {
            if(!StringUtils.isEmpty(param.getCreateTimeRange())){
                param.setCreateTimeList(param.getCreateTimeRange().split("--"));
            }
            if(!StringUtils.isEmpty(param.getPayTimeRange())){
                param.setPayTimeList(param.getPayTimeRange().split("--"));
            }
            if(!StringUtils.isEmpty(param.getDeliveryImportTimeRange())){
                param.setDeliveryImportTimeList(param.getDeliveryImportTimeRange().split("--"));
            }
            if(!StringUtils.isEmpty(param.getDeliverySendTimeRange())){
                param.setDeliverySendTimeList(param.getDeliverySendTimeRange().split("--"));
            }
            param.setNotHealth(1);
            List<FsStoreOrderVO> list = fsStoreOrderService.selectFsStoreOrderListVO(param);
            orderIds = list.stream().map(FsStoreOrderVO::getId).collect(Collectors.toList());
        }
        if (orderIds.isEmpty()){
            return R.ok();
        }
        orderIds.forEach(orderId->{
            df.setOrderId(orderId);
            FsStoreOrderDf temp = fsStoreOrderDfService.selectFsStoreOrderDfByOrderId(df.getOrderId());
            df.setParcelQuantity(param.getParcelQuantity());
            if (temp != null){
                df.setUpdateTime(new Date());
                fsStoreOrderDfService.updateFsStoreOrderDf(df);
            } else {
                fsStoreOrderDfService.insertFsStoreOrderDf(df);
            }
            fsStoreOrderLogsService.create(orderId, FsStoreOrderLogEnum.SET_PUSH_ACCOUNT.getValue(),
                    nickName + " " +FsStoreOrderLogEnum.SET_PUSH_ACCOUNT.getDesc() + ":" + df.getLoginAccount());
        });
        return R.ok();
    }

    @ApiOperation("批量审核订单")
    @Log(title = "订单管理", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('store:storeOrder:batchAudit')")
    @PostMapping("/batchAudit")
    public R batchAuditOrder(@Validated @RequestBody FsStoreOrderBatchAuditParam param) {
        if (param.getOrderIds() == null || param.getOrderIds().isEmpty()) {
            return R.error("订单ID列表不能为空");
        }
        if (param.getIsAudit() == null) {
            return R.error("审核状态不能为空");
        }
        int count = fsStoreOrderService.batchAuditOrder(param);
        return R.ok("成功审核 " + count + " 条订单");
    }

    @ApiOperation("订单备注")
    @Log(title = "订单管理", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('store:storeOrder:remark')")
    @PostMapping("/remark")
    public R remark(@Validated @RequestBody FsStoreOrderScrm param) {
        if (param.getId() == null || param.getId() < 1) {
            return R.error("订单ID错误");
        }
        if (StringUtils.isEmpty(param.getOrderRemark())) {
            return R.error("订单备注不能为空");
        }
        return fsStoreOrderService.orderRemark(param);
    }

    /**
     * 修改订单的代收金额
     */
    @PreAuthorize("@ss.hasPermi('store:storeOrder:editPayDelivery')")
    @Log(title = "订单-修改代收金额", businessType = BusinessType.UPDATE)
    @PutMapping("/editPayDelivery")
    public AjaxResult editPayDelivery(@RequestBody FsStoreOrderPayDeliveryDTO fsStoreOrderPayDeliveryDTO) {
        FsStoreOrderScrm fsStoreOrderScrm = new FsStoreOrderScrm();
        BeanUtils.copyProperties(fsStoreOrderPayDeliveryDTO, fsStoreOrderScrm);
        return toAjax(fsStoreOrderService.updateFsStoreOrder(fsStoreOrderScrm));
    }

    private FsStoreOrderDf getDFInfo(String loginAccount) {
        //查询订单账户 判断是否存在该订单账户
        List<FsDfAccount> erpAccounts = fsDfAccountService.selectFsDfAccountList(null);
        FsStoreOrderDf df = new FsStoreOrderDf();
        for (FsDfAccount erpAccount : erpAccounts) {
            if (loginAccount.equals(erpAccount.getLoginAccount())){
                //添加df记录
                df.setAppKey(erpAccount.getDfAppKey());
                df.setAppSecret(erpAccount.getDfAppsecret());
                df.setLoginAccount(loginAccount);
                df.setMonthlyCard(erpAccount.getMonthlyCard());
                df.setExpressProductCode(erpAccount.getExpressProductCode());
                df.setStatus(0);
                break;
            }
        }
        return df;
    }
}
