package com.gxwebsoft.open.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.apps.utils.BcUtil;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.web.PageParam;
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.mapper.OrderMapper;
import com.gxwebsoft.shop.param.CartParam;
import com.gxwebsoft.shop.param.OrderGoodsParam;
import com.gxwebsoft.shop.param.OrderParam;
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.Date;
import java.util.List;

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

/**
 * 订单记录表控制器
 *
 * @author WebSoft
 * @since 2022-11-16 11:25:58
 */
@Api(tags = "订单记录表管理")
@RestController
@RequestMapping("/api/open/order")
public class OpenOrderController extends BaseController {
    @Resource
    private BcUtil bcUtil;
    @Resource
    private OrderService orderService;
    @Resource
    private OrderGoodsService orderGoodsService;
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private UserService userService;
    @Resource
    private UserBalanceLogService userBalanceLogService;

    @ApiOperation("查询全部订单记录表")
    @GetMapping()
    public ApiResult<List<Order>> list(OrderParam param) {
        // 验证签名
        isCheckSign();
        // 使用关联查询
        return success(orderService.listRel(param));
    }

    @PreAuthorize("hasAuthority('shop:order:list')")
    @ApiOperation("根据id查询订单记录表")
    @GetMapping("/{id}")
    public ApiResult<Order> get(@PathVariable("id") Integer id) {
        // 验证签名
        isCheckSign();
        return success(orderService.getById(id));
        // 使用关联查询
        //return success(orderService.getByIdRel(id));
    }

    @PreAuthorize("hasAuthority('shop:order:list')")
    @ApiOperation("查询报餐明细")
    @GetMapping("/getMyOrder")
    public ApiResult<Order> getMyOrder(CartParam cartParam) {
      Integer userId = 0;
      if(cartParam.getAgentUserId() != null){
        userId = cartParam.getAgentUserId();
      }else{
        userId = getLoginUserId();
      }
      System.out.println("cartParam = " + cartParam);
      System.out.println("userId = " + userId);
      // 验证签名
      isCheckSign();
      // 报餐明细（查询昨天这个时间点后下的订单）
      LambdaQueryWrapper<Order> lambdaQueryWrapper = new LambdaQueryWrapper<>();
      lambdaQueryWrapper
        .eq(Order::getUserId,userId)
        .eq(Order::getPayStatus,PAY_STATUS_SUCCESS)
        .eq(Order::getOrderStatus,ORDER_STATUS_DOING)
        .eq(Order::getDeleted,0)
        .eq(Order::getIsTemporary,0)
        .eq(Order::getDeliveryTime,cartParam.getDeliveryTime());
      Order order = orderService.getOne(lambdaQueryWrapper,false);
      // 查询订单商品
      if(order != null){
        OrderGoodsParam param = new OrderGoodsParam();
        param.setOrderId(order.getOrderId());
        // 是否按餐段查询
        if(cartParam.getIsPeriod() != null){
          param.setCategoryId(bcUtil.categoryId);
        }
        PageParam<OrderGoods, OrderGoodsParam> page = new PageParam<>(param);
        page.setDefaultOrder("gear asc, sort_number asc, create_time desc");
        order.setGoodsList(orderGoodsService.list(page.getOrderWrapper()));
      }
      // 是否允许临时报餐
      if(cartParam.getHasTemporary() != null){
        final OrderParam orderParam = new OrderParam();
        orderParam.setDeliveryTime(cartParam.getDeliveryTime());
        orderParam.setUserId(userId);
        orderParam.setPayStatus(PAY_STATUS_SUCCESS);
        final List<Order> list = orderService.listRel(orderParam);
//        System.out.println("list1 = " + list);
        if(list.size() > 0){
          final Order order1 = list.get(0);
          final Integer orderId = order1.getOrderId();
          final OrderGoodsParam orderGoodsParam = new OrderGoodsParam();
          orderGoodsParam.setOrderId(orderId);
          orderGoodsParam.setCategoryId(cartParam.getCategoryId());
//          System.out.println("orderGoodsParam = " + orderGoodsParam);
          final List<OrderGoods> goodsList1 = orderGoodsService.listRel(orderGoodsParam);
//          System.out.println("goodsList1 = " + goodsList1);
          if(goodsList1.size() > 0){
            order1.setGoodsList(goodsList1);
            return fail("请勿重复报餐",order1);
          }
        }
      }
      return success(order);
    }

    @ApiOperation("查询今日当前餐段菜品")
    @PostMapping("/currentOrderGoods")
    public ApiResult<List<OrderGoods>> currentOrderGoods(OrderGoodsParam param) {
      // 验证签名
      isCheckSign();
      // 使用关联查询
      param.setCategoryId(bcUtil.categoryId);
      return success(orderGoodsService.listRel(param));
    }

    @PreAuthorize("hasAuthority('shop:order:list')")
    @ApiOperation("查询核销订单明细")
    @GetMapping("/getReceiptOrder")
    public ApiResult<?> getReceiptOrder(CartParam cartParam) {
      // 验证签名
      isCheckSign();
      Integer userId = 0;

      // 核销自己（查询今天他下的订单）
      if(cartParam.getUserId() != null){
        userId = cartParam.getUserId();
        OrderParam orderParam = new OrderParam();
        orderParam.setUserId(userId);
        orderParam.setPayStatus(PAY_STATUS_SUCCESS);
        orderParam.setOrderStatus(ORDER_STATUS_DOING);
        orderParam.setDeliveryTime(cartParam.getDeliveryTime());
        List<Order> list = orderService.listRel(orderParam);
        // 查询订单商品
        list.forEach(d -> {
          OrderGoodsParam param = new OrderGoodsParam();
          param.setOrderId(d.getOrderId());
          d.setGoodsList(orderGoodsService.listRel(param));
        });
        return success(list);
      }

      // 代核销模式
      if(cartParam.getDealerId() != null){
        userId = cartParam.getDealerId();
        return success(userId);
      }
      return fail("找不到报餐数据",null);
    }

    @PreAuthorize("hasAuthority('shop:order:save')")
    @ApiOperation("添加订单记录表")
    @PostMapping()
    public ApiResult<?> save(@RequestBody Order order) {
        // 验证签名
        isCheckSign();
        // 记录当前登录用户id、租户id
        User loginUser = getLoginUser();
        if (loginUser != null) {
          order.setUserId(loginUser.getUserId());
        }
        if (orderService.save(order)) {
            return success("添加成功",order);
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('shop:order:update')")
    @ApiOperation("修改订单记录表")
    @PutMapping()
    public ApiResult<?> update(@RequestBody Order order) {
        // 验证签名
        isCheckSign();
        if (orderService.updateById(order)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @ApiOperation("取消订单")
    @PostMapping("/cancel")
    @Transactional(rollbackFor = {Exception.class})
    public ApiResult<?> cancel(@RequestBody Order order) {
      // 验证签名
      isCheckSign();
      if (order.getOrderId() == null) {
        return fail("订单不存在！");
      }
      // 取消报餐截止时间
      Date date = DateUtil.date();
      int hours = date.getHours();
      System.out.println("hours = " + hours);
      if(hours > 19){
        return fail("每天晚上8点后截止取消报餐");
      }
      order.setOrderStatus(ORDER_STATUS_CANCEL);
      if (orderService.updateById(order)) {
        final Order orderInfo  = orderService.getById(order.getOrderId());
        // 退款
        User user = userService.getById(orderInfo.getUserId());
        System.out.println("user = " + user);
        BigDecimal balance = user.getBalance().add(orderInfo.getPayPrice());
        user.setBalance(balance);
        userService.updateById(user);
        // 记录余额明细
        UserBalanceLog userBalanceLog = new UserBalanceLog();
        userBalanceLog.setUserId(orderInfo.getUserId());
        userBalanceLog.setScene(BALANCE_REFUND);
        userBalanceLog.setMoney(orderInfo.getPayPrice());
        userBalanceLog.setBalance(balance);
        userBalanceLog.setComments(orderInfo.getOrderNo().toString());
        userBalanceLog.setMerchantCode(orderInfo.getMerchantCode());
        userBalanceLogService.save(userBalanceLog);
        return success("订单取消成功",orderInfo);
      }
      return fail("订单取消失败");
    }

    @ApiOperation("删除订单记录表")
    @GetMapping("/remove/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        // 验证签名
        isCheckSign();
        if (orderService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('shop:order:save')")
    @ApiOperation("批量添加订单记录表")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<Order> list) {
        // 验证签名
        isCheckSign();
        if (orderService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('shop:order:update')")
    @ApiOperation("批量修改订单记录表")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<Order> batchParam) {
        // 验证签名
        isCheckSign();
        if (batchParam.update(orderService, "order_id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('shop:order:remove')")
    @ApiOperation("批量删除订单记录表")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        // 验证签名
        isCheckSign();
        if (orderService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @ApiOperation("支付成功")
    @PostMapping("/setPayStatus")
    public ApiResult<?> setPayStatus(@RequestBody Order order){
      // 验证签名
      isCheckSign();
      if (orderService.updateById(order)) {
        return success("设置成功");
      }
      return fail("设置失败");
    }

    @ApiOperation("核销二维码")
    @PutMapping("/verification")
    public ApiResult<?> verification(@RequestBody Order order) {
      // 验证签名
      isCheckSign();
      order.setOrderStatus(ORDER_STATUS_COMPLETED);
      order.setReceiptTime(DateUtil.date());
      if (orderService.updateById(order)) {
        return success("核销成功");
      }
      return fail("核销失败");
    }
}
