package com.gxwebsoft.open.controller;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.core.web.*;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.common.system.service.UserService;
import com.gxwebsoft.shop.entity.Order;
import com.gxwebsoft.shop.entity.OrderGoods;
import com.gxwebsoft.shop.entity.UserBalanceLog;
import com.gxwebsoft.shop.param.OrderGoodsParam;
import com.gxwebsoft.shop.service.OrderGoodsService;
import com.gxwebsoft.shop.service.OrderService;
import com.gxwebsoft.shop.service.UserBalanceLogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

import static com.gxwebsoft.common.core.constants.BalanceConstants.BALANCE_REFUND;
import static com.gxwebsoft.common.core.constants.OrderConstants.ORDER_STATUS_CANCEL;

/**
 * 订单商品记录表控制器
 *
 * @author 科技小王子
 * @since 2022-12-09 17:15:31
 */
@Api(tags = "订单商品记录表管理")
@RestController
@RequestMapping("/api/open/order-goods")
public class OpenOrderGoodsController extends BaseController {
    @Resource
    private OrderGoodsService orderGoodsService;
    @Resource
    private UserService userService;
    @Resource
    private UserBalanceLogService userBalanceLogService;
    @Resource
    private OrderService orderService;

    @PreAuthorize("hasAuthority('shop:orderGoods:list')")
    @OperationLog
    @ApiOperation("分页查询订单商品记录表")
    @GetMapping("/page")
    public ApiResult<PageResult<OrderGoods>> page(OrderGoodsParam param) {
        PageParam<OrderGoods, OrderGoodsParam> page = new PageParam<>(param);
        page.setDefaultOrder("gear asc, sort_number asc, create_time desc");
        return success(orderGoodsService.page(page, page.getWrapper()));
        // 使用关联查询
        //return success(orderGoodsService.pageRel(param));
    }

    @PreAuthorize("hasAuthority('shop:orderGoods:list')")
    @OperationLog
    @ApiOperation("查询全部订单商品记录表")
    @GetMapping()
    public ApiResult<List<OrderGoods>> list(OrderGoodsParam param) {
        PageParam<OrderGoods, OrderGoodsParam> page = new PageParam<>(param);
        page.setDefaultOrder("gear asc, sort_number asc, create_time desc");
        return success(orderGoodsService.list(page.getOrderWrapper()));
        // 使用关联查询
        //return success(orderGoodsService.listRel(param));
    }

    @PreAuthorize("hasAuthority('shop:orderGoods:list')")
    @OperationLog
    @ApiOperation("根据id查询订单商品记录表")
    @GetMapping("/{id}")
    public ApiResult<OrderGoods> get(@PathVariable("id") Integer id) {
        return success(orderGoodsService.getById(id));
        // 使用关联查询
        //return success(orderGoodsService.getByIdRel(id));
    }

    @PreAuthorize("hasAuthority('shop:orderGoods:save')")
    @OperationLog
    @ApiOperation("添加订单商品记录表")
    @PostMapping()
    public ApiResult<?> save(@RequestBody OrderGoods orderGoods) {
        // 记录当前登录用户id、租户id、商户编号
        User loginUser = getLoginUser();
        if (loginUser != null) {
          orderGoods.setUserId(loginUser.getUserId());
          orderGoods.setMerchantCode(getMerchantCode());
        }
        if (orderGoodsService.save(orderGoods)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('shop:orderGoods:update')")
    @OperationLog
    @ApiOperation("修改订单商品记录表")
    @PutMapping()
    public ApiResult<?> update(@RequestBody OrderGoods orderGoods) {
        if (orderGoodsService.updateById(orderGoods)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('shop:orderGoods:remove')")
    @OperationLog
    @ApiOperation("删除订单商品记录表")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (orderGoodsService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('shop:orderGoods:save')")
    @OperationLog
    @ApiOperation("批量添加订单商品记录表")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<OrderGoods> list) {
        if (orderGoodsService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('shop:orderGoods:update')")
    @OperationLog
    @ApiOperation("批量修改订单商品记录表")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<OrderGoods> batchParam) {
        if (batchParam.update(orderGoodsService, "order_goods_id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('shop:orderGoods:remove')")
    @OperationLog
    @ApiOperation("批量删除订单商品记录表")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (orderGoodsService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('shop:orderGoods:remove')")
    @ApiOperation("取消订单商品")
    @PostMapping("/cancel")
    @Transactional(rollbackFor = {Exception.class})
    public ApiResult<?> cancel(@RequestBody OrderGoods orderGoods) {
      // 验证签名
      isCheckSign();
      if (orderGoods.getOrderGoodsId() == null) {
        return fail("菜品不存在！");
      }
//      System.out.println("orderGoods = " + orderGoods);
      final Order byId = orderService.getById(orderGoods.getOrderId());
      // 取消报餐截止时间
      orderGoodsService.removeById(orderGoods);
//      System.out.println("orderGoods = " + orderGoods);
      // 退款
      User user = userService.getById(byId.getUserId());
//      System.out.println("user = " + user);
//      System.out.println("orderGoods.getGoodsPrice() = " + orderGoods.getGoodsPrice());
      BigDecimal balance = user.getBalance().add(orderGoods.getGoodsPrice());
      user.setBalance(balance);
      userService.updateById(user);
        // 记录余额明细
        UserBalanceLog userBalanceLog = new UserBalanceLog();
        userBalanceLog.setUserId(byId.getUserId());
        userBalanceLog.setScene(BALANCE_REFUND);
        userBalanceLog.setMoney(orderGoods.getGoodsPrice());
        userBalanceLog.setBalance(balance);
        userBalanceLog.setComments(orderGoods.getOrderId().toString());
        userBalanceLogService.save(userBalanceLog);
        final int count = orderGoodsService.count(new LambdaUpdateWrapper<OrderGoods>().eq(OrderGoods::getOrderId, orderGoods.getOrderId()).gt(OrderGoods::getTotalNum,0));
//        System.out.println("count = " + count);
        // 更新订单金额
        System.out.println("byId = " + byId);
        if (!byId.getTotalPrice().equals(0)) {
          byId.setTotalPrice(byId.getTotalPrice().subtract(orderGoods.getGoodsPrice()));
          orderService.updateById(byId);
        }

        // 无菜品就把订单删除
        if(count == 0){
          final Order order = new Order();
          order.setOrderId(orderGoods.getOrderId());
          order.setOrderStatus(ORDER_STATUS_CANCEL);
          orderService.removeById(orderGoods.getOrderId());
        }
        return success("菜品取消成功");
    }

}
