package com.ff.weijinxiao.controller;


import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.ff.weijinxiao.domain.*;
import com.ff.weijinxiao.jwt.JwtHelper;
import com.ff.weijinxiao.service.*;
import com.ff.weijinxiao.util.JsonTool;
import com.ff.weijinxiao.util.RandomUtil;
import com.ff.weijinxiao.util.ResultTool;
import com.ff.weijinxiao.util.jsonfilter.CustomerJsonSerializer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 订单接口
 */
@RestController
@RequestMapping("api/order")
@Api(value = "订单controller", tags = {"订单接口"})
public class OrderController {

    private static Logger logger = LoggerFactory.getLogger(OrderController.class);

    @Resource
    private OrderService orderService;

    @Resource
    private UserInfoService userInfoService;

    @Resource
    private CUserService cUserService;

    @Resource
    private OrderGoodsService orderGoodsService;

    @Resource
    private AccountBookService accountBookService;

    @Resource
    private GoodsBatchService goodsBatchService;

    public UserInfo getUserInfoByToken(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {
            return null;
        }
        String openId = JwtHelper.parseToken(token);
        if (StringUtils.isBlank(openId)) {
            return null;
        }

        CUser cUser = cUserService.findByOpenId(openId);
        if (null == cUser) {
            return null;
        }
        return cUser.getUserInfo();
    }

    @PostMapping("/update")
    @ApiOperation(value = "更新订单信息", notes = "更新订单信息")
    public Map<String, Object> updateOrder(@RequestBody Order order, HttpServletRequest request) {
        try {
            orderService.saveOrder(order);
            return ResultTool.genSuccessResult("修改成功");
        } catch (Exception e) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_2, "修改失败:" + e.getMessage());
        }
    }

    @PostMapping("/create")
    @ApiOperation(value = "创建订单信息", notes = "创建订单信息")
    public Map<String, Object> saveOrder(@RequestBody Order order, HttpServletRequest request) {
        try {
            logger.info(order.toString());
            Double salePrice = order.getSalesPrice();
            if (null == salePrice) {
                salePrice = 0.00;
                order.setSalesPrice(0.00);
            }
            Double costPrice = order.getCostPrice();
            if (null == costPrice) {
                costPrice = 0.00;
                List<OrderGoods> orderGoodsList = order.getOrderGoodsList();
                if (null != orderGoodsList && orderGoodsList.size() > 0) {
                    for (OrderGoods orderGoods : orderGoodsList) {
                        Double purchasePrice = orderGoods.getGoodsBatch().getPurchasePrice();
                        if (null != purchasePrice) {
                            costPrice += purchasePrice;
                        }
                    }
                }
            }
            order.setCostPrice(costPrice);
            Double freight = order.getFreight();
            if (null == freight) {
                freight = 0.00;
                order.setFreight(0.00);
            }
            Double profit = salePrice - costPrice - freight;
            order.setProfit(profit);
            logger.info(order.toString());
            UserInfo userInfo = getUserInfoByToken(request);
            if (null != userInfo) {
                order.setUid(userInfo.getUid());
            }
            order.setOnlyID(RandomUtil.genOnlyId());
            orderService.saveOrder(order);
            return ResultTool.genSuccessResult("创建成功");
        } catch (Exception e) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_2, "创建失败:" + e.getMessage());
        }
    }


    @PostMapping("/delete")
    @ApiOperation(value = "删除订单信息", notes = "删除订单信息")
    public Map<String, Object> deleteOrder(@ApiParam(required = true, value = "订单id") @RequestBody String jsonId) {
        Integer id = JsonTool.parseJsonIdStr(jsonId);
        if (id < 0) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "id参数错误");
        }
        Order order = orderService.findById(id);
        if (null == order) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "订单不存在");
        }
        order.setIsDelete(1);
        orderService.saveOrder(order);
        return ResultTool.genSuccessResult("删除成功");
    }

    @GetMapping("/findbyid")
    @ApiOperation(value = "根据id查询订单信息", notes = "根据id查询订单信息")
    public Map<String, Object> findById(@ApiParam(required = true, value = "订单id") @RequestParam String id,
                                        HttpServletRequest request) {

        Map<String, Object> result = new HashMap<>();
        try {
            Order order = orderService.findById(Integer.valueOf(id));
            if (null != order) {
                result.put("data", order);
                result.put("message", "查询成功");
                result.put("code", ResultTool.SuccessCode);
            } else {
                result.put("message", "查询失败，没有结果");
                result.put("code", ResultTool.ErrorCode_1);
            }

        } catch (Exception e) {
            e.printStackTrace();
            result.put("message", "查询失败" + e.getMessage());
            result.put("code", ResultTool.ErrorCode_2);
        }

        return result;
    }


    @GetMapping("/list")
    @ApiOperation(value = "查询订单列表", notes = "查询订单列表")
    public Map<String, Object> findList(@ApiParam(required = false, value = "订单名字") @RequestParam(required = false) String phone,
                                        HttpServletRequest request) {

        Map<String, Object> result = new HashMap<>();
        Map<String, Object> param = new HashMap<>();
        param.put("GT_id", 0);
        param.put("EQ_isDelete", 0);
        if (null != phone && phone.length() > 0) {
            param.put("LIKE_phone", phone);
        }
        List<Order> list = orderService.findList(param);
        if (null != list && list.size() > 0) {
            result.put("data", list);
            result.put("total", list.size());
            result.put("message", "查询成功");
            result.put("code", 10000);
        } else {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "没有查询到数据");
        }

        return result;
    }

    @GetMapping("/listpage")
    @ApiOperation(value = "查询订单分页列表", notes = "查询订单分页列表")
    public Map<String, Object> findListPage(@ApiParam(required = false, value = "页码 1开始") @RequestParam(required = false) Integer pageNo,
                                            @ApiParam(required = false, value = "每页显示条数 默认10") @RequestParam(required = false) Integer pageSize) {

        Map<String, Object> result = new HashMap<>();
        Map<String, Object> param = new HashMap<>();
        if (null == pageNo) {
            pageNo = 1;
        } else if (pageNo < 1) {
            pageNo = 1;
        }
        if (null == pageSize) {
            pageSize = 10;
        }
        param.put("GT_id", 0);
        param.put("EQ_isDelete", 0);
        Page<Order> list = orderService.findPage(pageNo, pageSize, null, param);
        if (null != list && list.getTotalElements() > 0) {
            List<Order> data = list.getContent();
            for (Order order : data) {
                UserInfo userInfo = userInfoService.findByUid(order.getUid());
                if (null != userInfo) {
                    order.setUserName(userInfo.getWechatName());
                }
            }
            result.put("data", list);
            result.put("message", "分页查询成功");
            result.put("code", 10000);
        } else {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "没有查询到数据");
        }

        return result;
    }

    @PostMapping("/wxapi/update")
    @ApiOperation(value = "更新订单信息", notes = "更新订单信息")
    public Map<String, Object> wxupdateOrder(@RequestBody Order order, HttpServletRequest request) {
        try {
            orderService.saveOrder(order);
            return ResultTool.genSuccessResult("修改成功");
        } catch (Exception e) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_2, "修改失败:" + e.getMessage());
        }
    }

    @GetMapping("/wxapi/getLastPrice")
    @ApiOperation(value = "获取上次销售价格", notes = "上次销售价格")
    public Map<String, Object> getLastPrice(@ApiParam(required = true, value = "商品id") @RequestParam(required = true) Integer productId,
                                            @ApiParam(required = true, value = "客户id") @RequestParam(required = true) Integer customerId,
                                            HttpServletRequest request) {
        logger.info("\ngetLastPrice : {},{}", productId, request.getHeader("token"));
        Map<String, Object> result = new HashMap<>();
        UserInfo userInfo = getUserInfoByToken(request);
        Map<String, Object> param = new HashMap<>();
        param.put("GT_id", 0);
        param.put("EQ_isDelete", 0);
        param.put("EQ_uid", userInfo.getUid());
        param.put("EQ_customer.id", customerId);
        param.put("EQ_orderGoodsList.goods.id", productId);
        List<Order> list = orderService.findList(param);
        if (null != list && list.size() > 0) {
            for (Order order : list) {
                List<OrderGoods> orderGoodsList = order.getOrderGoodsList();
                if (null != orderGoodsList && orderGoodsList.size() > 0) {
                    for (OrderGoods orderGoods : orderGoodsList) {
                        if (orderGoods.getGoods().getId().equals(productId)) {
                            result.put("data", orderGoods.getSalesVolume());
                            result.put("message", "查询成功");
                            result.put("code", 10000);
                            return result;
                        }
                    }
                }
            }

            result.put("data", 0);
            result.put("total", list.size());
            result.put("message", "查询成功");
            result.put("code", 10000);
        } else {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "没有查询到数据");
        }

        return result;
    }

    @Transactional
    @PostMapping("/wxapi/create")
    @ApiOperation(value = "创建订单信息", notes = "创建订单信息")
    public Map<String, Object> wxsaveOrder(@RequestBody Order order, HttpServletRequest request) {
        logger.info("wxsaveOrder: {}", order);
        try {
            logger.info(order.toString());
            Double salePrice = order.getSalesPrice();//销售总价
            if (null == salePrice) {
                salePrice = 0.00;
                order.setSalesPrice(0.00);
            }
            Double costPrice = order.getCostPrice();
            if (null == costPrice) {
                costPrice = 0.00;
                List<OrderGoods> orderGoodsList = order.getOrderGoodsList();
                if (null != orderGoodsList && orderGoodsList.size() > 0) {
                    for (OrderGoods orderGoods : orderGoodsList) {
                        GoodsBatch gb = orderGoods.getGoodsBatch();
                        gb = goodsBatchService.findById(gb.getId());
                        Double purchasePrice = gb.getPurchasePrice();
                        if (null != purchasePrice) {
                            costPrice += purchasePrice * orderGoods.getNumber(); //成本总价
                        }
                    }
                }
            }
            //order.setSubmitDate(new Date());//销售日期，前端传过来
            order.setCostPrice(costPrice);
            Double freight = order.getFreight();
            if (null == freight) {
                freight = 0.00;
                order.setFreight(0.00);
            }
            Double profit = salePrice - costPrice - freight;
            order.setProfit(profit);
            logger.info(order.toString());
            order.setOnlyID(RandomUtil.genOnlyId());
            UserInfo userInfo = getUserInfoByToken(request);
            if (null != userInfo) {
                order.setUid(userInfo.getUid());
            }
            AccountBook accountBook = accountBookService.getDefaultAccountBook(userInfo);
            order.setAccountBook(accountBook);
            List<OrderGoods> orderGoodsList = order.getOrderGoodsList();
            if (null != orderGoodsList && orderGoodsList.size() > 0) {
                for (OrderGoods orderGoods : orderGoodsList) {
                    orderGoods.setUid(userInfo.getUid());
                    orderGoods.setOnlyID(RandomUtil.genOnlyId());
                    orderGoods.setSubmitDate(order.getSubmitDate());
                    GoodsBatch goodsBatch = goodsBatchService.findByOnlyID(orderGoods.getGoodsBatch().getOnlyID());
                    if (null != goodsBatch) {
                        Double stockNumber = goodsBatch.getStockNumber();
                        Double saledNumber = orderGoods.getNumber();
                        if (null == stockNumber) {
                            stockNumber = 0.0;
                        }
                        if (null == saledNumber) {
                            saledNumber = 0.0;
                        }
                        goodsBatch.setStockNumber(stockNumber - saledNumber);
                        goodsBatchService.saveGoodsBatch(goodsBatch);//更新库存
                    }
                    orderGoods.setGoodCost(goodsBatch.getPurchasePrice());//成本
                    orderGoods.setProfit(orderGoods.getSalesVolume() - orderGoods.getGoodCost());//单个利润
                    orderGoods.setSellPrice(orderGoods.getSalesVolume());// 单价
                    if (null != goodsBatch.getSupplier()) {
                        orderGoods.setSupplierId(goodsBatch.getSupplier().getOnlyID());
                    }
                    orderGoodsService.saveOrderGoods(orderGoods);

                }
            }
            orderService.saveOrder(order);
            return ResultTool.genSuccessResult("创建成功");
        } catch (Exception e) {
            e.printStackTrace();
            return ResultTool.genFailResult(ResultTool.ErrorCode_2, "创建失败:" + e.getMessage());
        }
    }

    @GetMapping("/wxapi/listpage")
    @ApiOperation(value = "查询订单分页列表", notes = "查询订单分页列表")
    public Map<String, Object> wxfindListPage(@ApiParam(required = false, value = "商品条码/商品名称/客户姓名") @RequestParam(required = false) String orCondition,
                                              //@ApiParam(required = false, value = "商品名称") @RequestParam(required = false) String goodsName,
                                              //@ApiParam(required = false, value = "客户姓名") @RequestParam(required = false) String customName,
                                              @ApiParam(required = true, value = "账本id") @RequestParam(required = true) Integer accountBookId,
                                              @ApiParam(required = false, value = "记账人id") @RequestParam(required = false) Integer userInfoId,
                                              @ApiParam(required = false, value = "客户id") @RequestParam(required = false) Integer customId,
                                              @ApiParam(required = true, value = "统计维度 1=日 2=月 3=年 4=日期区间") @RequestParam Integer dim,
                                              @ApiParam(required = false, value = "指定统计日 格式yyyy-MM-dd") @RequestParam(required = false) String day,
                                              @ApiParam(required = false, value = "指定统计月 格式yyyy-MM") @RequestParam(required = false) String month,
                                              @ApiParam(required = false, value = "指定统计年 格式yyyy") @RequestParam(required = false) String year,
                                              @ApiParam(required = false, value = "当统计纬度为4时，开始日期:yyyy-MM-dd") @RequestParam(required = false) String beginDate,
                                              @ApiParam(required = false, value = "当统计纬度为4时，结束日期:yyyy-MM-dd") @RequestParam(required = false) String endDate,
                                              @ApiParam(required = false, value = "页码 1开始") @RequestParam(required = false) Integer pageNo,
                                              @ApiParam(required = false, value = "每页显示条数 默认10") @RequestParam(required = false) Integer pageSize,
                                              HttpServletRequest request) throws JsonProcessingException {
        logger.info("order listpage accountBookId={},dim={} ,day={}, month={}, year={}", accountBookId, dim, day, month, year);
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> param = new HashMap<>();
        Map<String, Object> orParam = new HashMap<>();
        if (null == pageNo) {
            pageNo = 1;
        } else if (pageNo < 1) {
            pageNo = 1;
        }
        if (null == pageSize) {
            pageSize = 10;
        }
        param.put("GT_id", 0);
        param.put("EQ_isDelete", 0);
        param.put("EQ_accountBook.id", accountBookId);
        if (null != userInfoId) {
            param.put("EQ_accountBook.userInfos.id", userInfoId);
        }
        if (null != customId) {
            param.put("EQ_customer.id", customId);
        }
        if (StringUtils.isNotBlank(orCondition)) {
            orParam.put("LIKE_orderGoodsList.goodsBatch.goodsBarcode", orCondition);
            orParam.put("LIKE_orderGoodsList.goods.name", orCondition);
            orParam.put("LIKE_customer.name", orCondition);
        }
        UserInfo userInfo = getUserInfoByToken(request);
        if (null == userInfo) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "获取失败，未注册有效账号");
        }
        //param.put("EQ_uid", userInfo.getUid());
        if (null == dim) {
            dim = 1;
        }
        if (dim == 1) {
            //按日
            String reportDay = "";
            if (StringUtils.isNotBlank(day)) {
                reportDay = day;
            } else {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                reportDay = sdf.format(new Date());
            }
            String beginTime = reportDay + " 00:00:00";
            String endTime = reportDay + " 23:59:59";
            logger.info("beginTime:" + beginTime + " endTime:" + endTime);
            param.put("GTE_submitDate", beginTime);
            param.put("LTE_submitDate", endTime);
        } else if (dim == 2) {
            //按月
            String beginTime = "";
            String endTime = "";
            if (StringUtils.isBlank(month)) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
                month = sdf.format(new Date());
            }
            beginTime = month + "-01 00:00:00";
            endTime = UserInfoController.getLastDayOfMonth(Integer.valueOf(month.substring(0, 4)), Integer.valueOf(month.substring(5, 7))) + " 23:59:59";
            logger.info("beginTime:" + beginTime + " endTime:" + endTime);
            param.put("GTE_submitDate", beginTime);
            param.put("LTE_submitDate", endTime);
        } else if (dim == 3) {
            //按年
            if (StringUtils.isBlank(year)) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
                year = sdf.format(new Date());
            }
            String beginTime = year + "-01-01 00:00:00";
            String endTime = year + "-12-31 23:59:59";
            logger.info("beginTime:" + beginTime + " endTime:" + endTime);
            param.put("GTE_submitDate", beginTime);
            param.put("LTE_submitDate", endTime);
        } else if (dim == 4) {
            if (StringUtils.isBlank(beginDate) || StringUtils.isBlank(endDate)) {
                return ResultTool.genFailResult(ResultTool.ErrorCode_1, "开始日期和结束日期不能为空");
            }
            param.put("GTE_submitDate", beginDate + " 00:00:00");
            param.put("LTE_submitDate", endDate + " 23:59：59");
        }
        Page<Order> list = orderService.findPage(pageNo, pageSize, orParam, param);
        if (null != list && list.getTotalElements() > 0) {
            List<Order> data = list.getContent();
            List<Object> fData = new ArrayList<>();
            for (Order order : data) {
                UserInfo user = userInfoService.findByUid(order.getUid());
                if (null != user) {
                    order.setUserName(user.getWechatName());
                }
                CustomerJsonSerializer customerJsonSerializer = new CustomerJsonSerializer();
                customerJsonSerializer.filter(AccountBook.class, "id", null);
                String dataStr = customerJsonSerializer.toJson(order);
                fData.add(JSONObject.parse(dataStr));
            }
            result.put("data", fData);
            result.put("message", "分页查询成功");
            result.put("code", 10000);
        } else {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "没有查询到数据");
        }

        return result;
    }

    @GetMapping("/wxapi/findCustomByAccountBookId")
    @ApiOperation(value = "根据账本id查询客户信息", notes = "根据账本id查询客户信息")
    public Map<String, Object> findCustomByAccountBookId(@ApiParam(required = true, value = "账本id") @RequestParam Integer accountBookId,
                                                         HttpServletRequest request) {

        Map<String, Object> result = new HashMap<>();
        Map<String, Object> param = new HashMap<>();
        param.put("GT_id", 0);
        param.put("EQ_isDelete", 0);
        param.put("EQ_accountBook.id", accountBookId);
        UserInfo userInfo = getUserInfoByToken(request);
        if (null == userInfo) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "获取失败，未注册有效账号");
        }
        param.put("EQ_uid", userInfo.getUid());
        List<Order> orders = orderService.findList(param);
        if (null != orders && orders.size() > 0) {
            List<Customer> customers = new ArrayList<>();
            for (Order order : orders) {
                if (null != order.getCustomer() && !customers.contains(order.getCustomer())) {
                    customers.add(order.getCustomer());
                }
            }
            result.put("data", customers);
            result.put("message", "查询成功");
            result.put("code", ResultTool.SuccessCode);
        } else {
            result.put("data", null);
            result.put("message", "没有获取到数据");
            result.put("code", ResultTool.ErrorCode_1);
        }
        return result;
    }

    @GetMapping("/wxapi/findbyid")
    @ApiOperation(value = "根据id查询订单信息", notes = "根据id查询订单信息")
    public Map<String, Object> wxfindById(@ApiParam(required = true, value = "订单id") @RequestParam String id,
                                          HttpServletRequest request) {

        Map<String, Object> result = new HashMap<>();
        try {
            Order order = orderService.findById(Integer.valueOf(id));
            if (null != order) {
                UserInfo userInfo = getUserInfoByToken(request);
                if (null == userInfo) {
                    return ResultTool.genFailResult(ResultTool.ErrorCode_1, "获取失败，未注册有效账号");
                }
                order.setUserName(userInfo.getWechatName());
                result.put("data", order);
                result.put("message", "查询成功");
                result.put("code", ResultTool.SuccessCode);
            } else {
                result.put("message", "查询失败，没有结果");
                result.put("code", ResultTool.ErrorCode_1);
            }

        } catch (Exception e) {
            e.printStackTrace();
            result.put("message", "查询失败" + e.getMessage());
            result.put("code", ResultTool.ErrorCode_2);
        }

        return result;
    }

/*    @PostMapping("/wxapi/setstatus")
    @ApiOperation(value = "设置订单状态", notes = "设置订单状态")
    public Map<String, Object> setOrderStatus(@ApiParam(required = true, value = "状态信息 {\"orderId\":123,\"status\":2}") @RequestBody String jsonId) {
        Integer id = JsonTool.parseJsonIdStr(jsonId);
        if (id < 0) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "id参数错误");
        }
        Order order = orderService.setStatus(id);
        if (null == order) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "订单不存在");
        }
        order.setIsDelete(1);
        orderService.saveOrder(order);
        return ResultTool.genSuccessResult("删除成功");
    }*/

    @PostMapping("/wxapi/setpayed")
    @ApiOperation(value = "设置已付款", notes = "设置已付款")
    public Map<String, Object> setPayed(@ApiParam(required = true, value = "订单id") @RequestParam Integer orderId) {
        if (null == orderId || orderId <= 0) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "orderId参数错误");
        }
        Order order = orderService.findById(orderId);
        if (null == order) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "订单不存在");
        }
        order.setIsPayment(1);
        orderService.saveOrder(order);
        return ResultTool.genSuccessResult("设置已付款成功");
    }

    @PostMapping("/wxapi/setreceive")
    @ApiOperation(value = "设置已收款", notes = "设置已收款")
    public Map<String, Object> setReceive(@ApiParam(required = true, value = "订单id") @RequestParam Integer orderId) {
        if (null == orderId || orderId <= 0) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "orderId参数错误");
        }
        Order order = orderService.findById(orderId);
        if (null == order) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "订单不存在");
        }
        order.setIsReceivables(1);
        orderService.saveOrder(order);
        return ResultTool.genSuccessResult("设置已收款成功");
    }

    @PostMapping("/wxapi/setsend")
    @ApiOperation(value = "设置已发货", notes = "设置已发货")
    public Map<String, Object> setSend(@ApiParam(required = true, value = "订单id") @RequestParam Integer orderId,
                                       @ApiParam(required = false, value = "快递方式 1:快递；2:上门；3:自取") @RequestParam String deliveryType,
                                       @ApiParam(required = false, value = "快递公司") @RequestParam String courierCompany,
                                       @ApiParam(required = false, value = "快递单号") @RequestParam String courierNumber) {
        if (null == orderId || orderId <= 0) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "orderId参数错误");
        }
        Order order = orderService.findById(orderId);
        if (null == order) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "订单不存在");
        }
        order.setIsSend(1);
        if (StringUtils.isNotBlank(deliveryType)) {
            order.setDeliveryType(deliveryType);
        }
        if (null != deliveryType && "1".equals(deliveryType) && StringUtils.isNotBlank(courierCompany)) {
            order.setCourierCompany(courierCompany);
        }
        if (null != deliveryType && "1".equals(deliveryType) && StringUtils.isNotBlank(courierNumber)) {
            order.setCourierNumber(courierNumber);
        }
        orderService.saveOrder(order);
        return ResultTool.genSuccessResult("设置已发货成功");
    }

    @PostMapping("/wxapi/delete")
    @ApiOperation(value = "删除订单信息", notes = "删除订单信息")
    public Map<String, Object> wxdeleteOrder(@ApiParam(required = true, value = "订单id") @RequestBody String jsonId) {
        Integer id = JsonTool.parseJsonIdStr(jsonId);
        if (id < 0) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "id参数错误");
        }
        Order order = orderService.findById(id);
        if (null == order) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "订单不存在");
        }
        //order.setIsDelete(1);
        //恢复库存
        List<OrderGoods> orderGoodsList = order.getOrderGoodsList();
        if (null != orderGoodsList && orderGoodsList.size() > 0) {
            for (OrderGoods orderGoods : orderGoodsList) {
                GoodsBatch goodsBatch = goodsBatchService.findByOnlyID(orderGoods.getGoodsBatch().getOnlyID());
                if (null != goodsBatch) {
                    Double stockNumber = goodsBatch.getStockNumber();
                    Double saledNumber = orderGoods.getNumber();
                    if (null == stockNumber) {
                        stockNumber = 0.0;
                    }
                    if (null == saledNumber) {
                        saledNumber = 0.0;
                    }
                    goodsBatch.setStockNumber(stockNumber + saledNumber);
                    goodsBatchService.saveGoodsBatch(goodsBatch);//更新库存
                }
            }
        }
        orderService.deleteById(id);
        return ResultTool.genSuccessResult("删除成功");
    }
}
