package com.fs.hisStore.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.fs.common.annotation.DataScope;
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.page.TableDataInfo;
import com.fs.common.enums.BusinessType;
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.domain.CompanyUser;
import com.fs.company.service.ICompanyUserService;
import com.fs.config.cloud.CloudHostProper;
import com.fs.crm.domain.CrmCustomer;
import com.fs.crm.service.ICrmCustomerService;
import com.fs.framework.security.LoginUser;
import com.fs.framework.service.TokenService;
import com.fs.his.domain.FsUser;
import com.fs.his.service.IFsUserService;
import com.fs.hisStore.config.StoreConfig;
import com.fs.hisStore.domain.FsStoreOrderItemScrm;
import com.fs.hisStore.domain.FsStoreOrderScrm;
import com.fs.hisStore.domain.FsStoreOrderStatusScrm;
import com.fs.hisStore.domain.FsStorePaymentScrm;
import com.fs.hisStore.dto.ExpressInfoDTO;
import com.fs.hisStore.dto.FsStoreOrderPayDeliveryDTO;
import com.fs.hisStore.dto.StoreOrderProductDTO;
import com.fs.hisStore.enums.OrderLogEnum;
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.service.ISysConfigService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单Controller
 *
 * @author fs
 * @date 2022-03-15
 */

@RestController
@RequestMapping("/store/store/storeOrder")
public class FsStoreOrderScrmController extends BaseController
{
    @Autowired
    private IFsExpressScrmService expressService;
    @Autowired
    private IFsStoreOrderScrmService fsStoreOrderService;
    @Autowired
    private IFsStoreOrderItemScrmService orderItemService;

    @Autowired
    private IFsUserService userService;

    @Autowired
    private IFsStoreOrderStatusScrmService orderStatusService;
    @Autowired
    private IFsStorePaymentScrmService fsStorePaymentService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ICrmCustomerService crmCustomerService;
    @Autowired
    private IFsStoreOrderAuditLogScrmService orderAuditLogService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private ICompanyUserService companyUserService;
    @Autowired
    private CloudHostProper cloudHostProper;

    // 允许的文件扩展名
    private static final String[] ALLOWED_EXCEL_EXTENSIONS = {".xlsx", ".xls"};

    // 最大文件大小（5MB）
    private static final long MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB

    /**
     * 查询订单列表
     */
    @GetMapping("/list")
    public TableDataInfo list(FsStoreOrderParam param)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        param.setCompanyId(loginUser.getCompany().getCompanyId());
        startPage();
        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.selectFsStoreOrderListVO(param);
        return getDataTable(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);
    }


    //订单发货批量导入
    @Log(title = "发货同步导入", businessType = BusinessType.IMPORT)
    @PostMapping("/importDeliveryNoteExpress")
    public R importDeliveryNoteExpress(@RequestParam("file") MultipartFile file, @RequestParam(name = "shipmentType",required = false) Integer shipmentType) {
        // 1. 检查文件是否为空
        if (file.isEmpty()) {
            return R.error("上传的文件不能为空");
        }
        // 2. 检查文件大小
        if (file.getSize() > MAX_FILE_SIZE) {
            return R.error("文件大小不能超过5MB");
        }
        // 3. 检查文件扩展名
        String fileName = file.getOriginalFilename();
        if (fileName == null || !isValidExcelFile(fileName)) {
            return R.error("请上传Excel文件（.xlsx或.xls格式）");
        }

        ExcelUtil<FsStoreOrderDeliveryNoteExportVO> util=new ExcelUtil<>(FsStoreOrderDeliveryNoteExportVO.class);
        try {
            List<FsStoreOrderDeliveryNoteExportVO> dtoList = util.importExcel(file.getInputStream());
            if(dtoList.isEmpty()){
                return R.error("操作失败，导入数据不能小于1条！");
            }
            if(dtoList.size() > 200){
                return R.error("操作失败，导入数据不能大于200条！");
            }
            if(shipmentType == null){
                shipmentType = 2;
            }
            return fsStoreOrderService.importDeliveryNoteExpress(dtoList,null,shipmentType);
        }catch (Exception e){
            logger.error("发货导入异常", e);
            return R.error("导入失败：" + e.getMessage());
        }
    }

    private boolean isValidExcelFile(String fileName) {
        for (String ext : ALLOWED_EXCEL_EXTENSIONS) {
            if (fileName.toLowerCase().endsWith(ext)) {
                return true;
            }
        }
        return false;
    }


    @GetMapping("/allList")
    public TableDataInfo allList(FsStoreOrderParam param)
    {
        startPage();
        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.selectFsStoreOrderAllListVO(param);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('store:storeOrder:myList')")
    @GetMapping("/myList")
    public TableDataInfo myList(FsStoreOrderParam param)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        param.setCompanyId(loginUser.getCompany().getCompanyId());
        param.setCompanyUserId(loginUser.getUser().getUserId());
        startPage();
        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.selectFsStoreOrderListVO(param);
        return getDataTable(list);
    }


    @PreAuthorize("@ss.hasPermi('store:storeOrder:export')")
    @Log(title = "订单", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    @DataScope(deptAlias = "cu",userAlias = "cu")
    public AjaxResult export (FsStoreOrderParam param)
    {
        if (param.getBeginTime().equals("") && param.getEndTime().equals("")){
            param.setBeginTime(null);
            param.setEndTime(null);
        }
        if (fsStoreOrderService.isEntityNull(param)){
            return AjaxResult.error("请筛选数据导出");
        }
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        param.setCompanyId(loginUser.getCompany().getCompanyId());
        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<FsStoreOrderErpExportVO> list = fsStoreOrderService.selectFsStoreOrderListVOByExport(param);
        //对手机号脱敏
        if(list!=null){
            for(FsStoreOrderExportVO 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()));
                }
                vo.setCost(BigDecimal.ZERO);
            }
        }

        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: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=fsStorePaymentService.selectFsStorePaymentByOrderId(order.getId());

        CrmCustomer customer=null;
        if(order.getCustomerId()!=null&&order.getCustomerId()>0){
            customer=crmCustomerService.selectCrmCustomerById(order.getCustomerId());
        }

        List<FsStoreOrderAuditLogVO> auditLogs = orderAuditLogService.selectStoreOrderAuditLogVOByOrderId(order.getId());
        return R.ok().put("order", order).put("items", items).put("logs",logs).put("user",user).put("customer",customer).put("payments",payments)
                .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}")
    @PreAuthorize("@ss.hasPermi('store:storeOrder:queryPhone')")
    @Log(title = "查看电话", businessType = BusinessType.GRANT)
    public R getPhone(@PathVariable("id") Long id)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        if("广州郑多燕".equals(cloudHostProper.getCompanyName())){
            FsStoreOrderScrm order = fsStoreOrderService.selectFsStoreOrderById(id);
            return R.ok().put("userPhone",order.getUserPhone());
        } else {
            if (loginUser.getUser().getUserType().equals("00")){
                FsStoreOrderScrm order = fsStoreOrderService.selectFsStoreOrderById(id);
                String userPhone = order.getUserPhone();
                return R.ok().put("userPhone",userPhone);
            }
            return R.error("无权查看");
        }
    }

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

    /**
     * 新增订单
     */

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

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

    @PreAuthorize("@ss.hasPermi('store:storeOrder:add')")
    @PostMapping("/createUserOrder")
    public R createUserOrder(@Validated @RequestBody FsStoreOrderCreateUserParam param, HttpServletRequest request){

        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        param.setCompanyId(loginUser.getCompany().getCompanyId());
        param.setCompanyUserId(loginUser.getUser().getUserId());
        return fsStoreOrderService.createUserOrder(param);
    }


    @PreAuthorize("@ss.hasPermi('store:storeOrder:editPayPrice')")
    @PostMapping("/editPayPrice")
    public R editPayPrice(@RequestBody FsStoreOrderScrm fsStoreOrder)
    {

        if(fsStoreOrderService.updateFsStoreOrder(fsStoreOrder)>0){
            //写日志
            orderStatusService.create(fsStoreOrder.getId(), OrderLogEnum.ORDER_EDIT.getValue(),
                    OrderLogEnum.ORDER_EDIT.getDesc());
            return R.ok("操作成功");
        }
        else{
            return R.error("操作失败");
        }

    }

    @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:exportItems')")
    @Log(title = "订单明细导出", businessType = BusinessType.EXPORT)
    @GetMapping("/exportItems")
    public AjaxResult exportItems(FsStoreOrderParam param)
    {
        if (param.getBeginTime().equals("") && param.getEndTime().equals("")){
            param.setBeginTime(null);
            param.setEndTime(null);
        }
        if (fsStoreOrderService.isEntityNull(param)){
            return AjaxResult.error("请筛选数据导出");
        }
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        param.setCompanyId(loginUser.getCompany().getCompanyId());

        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<FsStoreOrderItemExportVO> list=orderItemService.selectFsStoreOrderItemListExportVO(param);
        //对手机号脱敏
        if(list!=null){
            for(FsStoreOrderItemExportVO vo:list){
                if(vo.getUserPhone()!=null){
                    String phone = vo.getUserPhone().replaceAll("(\\d{3})\\d*(\\d{1})", "$1****$2");
                    vo.setUserPhone(phone);
                }
                if (vo.getUserAddress()!=null){
                    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){
                    }
                }
                vo.setCost(BigDecimal.ZERO);
            }
        }
        ExcelUtil<FsStoreOrderItemExportVO> util = new ExcelUtil<FsStoreOrderItemExportVO>(FsStoreOrderItemExportVO.class);
        return util.exportExcel(list, "订单明细数据");
    }


    @GetMapping("/getCustomerOrderList")
    public TableDataInfo getCustomerOrderList(FsStoreOrderParam param) {
        startPage();
        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);
    }

    @PreAuthorize("@ss.hasPermi('store:storeOrder:bindCustomer')")
    @PostMapping("/bindCustomer")
    public R bindCustomer(@RequestBody FsStoreOrderBindCustomerParam param)
    {
        if(param.getCustomerIds().length>1){
            return R.error("只能关联一个客户");
        }
        for(Long customerId:param.getCustomerIds()){
            FsStoreOrderScrm order=new FsStoreOrderScrm();
            order.setId(param.getOrderId());
            order.setCustomerId(customerId);
            fsStoreOrderService.updateFsStoreOrder(order);
            //更新CRM客户订单数
            crmCustomerService.updateBuyCount(customerId);
        }
        return R.ok("操作成功");

    }

    @Log(title = "订单凭证上传", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('store:storeOrder:uploadCredentials')")
    @PostMapping("/uploadCredentials")
    public R UploadCredentials(@RequestBody FsStoreOrderScrm order)
    {
//        String[] imageUrls = order.getCredentials().split(",");
        if (order.getCertificates() == null ){
            return R.error("请选择图片上传");
        }
        fsStoreOrderService.uploadCredentials(order);
        return R.ok();
    }

    @Log(title = "修改地址", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('store:storeOrder:editAddress')")
    @PostMapping("/editAddress")
    public R editAddress(@RequestBody FsStoreOrderScrm order) throws ParseException
    {
        FsStoreOrderScrm storeOrder = fsStoreOrderService.selectFsStoreOrderById(order.getId());

        int a = fsStoreOrderService.updateFsStoreOrder(order);
        if (storeOrder.getExtendOrderId()!=null && a>0){
            fsStoreOrderService.createOmsOrder(storeOrder.getId());
        }

        return R.ok();
    }

    /**
     * 获取下单类型
     */
    @GetMapping("/getCreateOrderType")
    public R getCreateOrderType() {
        String json=configService.selectConfigByKey("store.config");
        StoreConfig config= JSONUtil.toBean(json,StoreConfig.class);
        Integer createSalesOrderType = config.getCreateSalesOrderType();
        return R.ok().put("createSalesOrderType",createSalesOrderType);
    }

    @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 + " 条订单");
    }
    /**
     * 修改订单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));
    }

    /**
     * 修改订单的代收金额
     */
    @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));
    }
}
