package com.gxwebsoft.common.system.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.gxwebsoft.common.core.annotation.OperationLog;
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.PageResult;
import com.gxwebsoft.common.system.entity.Cart;
import com.gxwebsoft.common.system.entity.Order;
import com.gxwebsoft.common.system.entity.OrderGoods;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.common.system.mapper.MenuMapper;
import com.gxwebsoft.common.system.param.MenuParam;
import com.gxwebsoft.common.system.param.OrderParam;
import com.gxwebsoft.common.system.service.MenuService;
import com.gxwebsoft.common.system.service.OrderGoodsService;
import com.gxwebsoft.common.system.service.OrderService;
import com.gxwebsoft.common.system.service.UserService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

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

/**
 * 订单控制器
 *
 * @author 科技小王子
 * @since 2024-10-16 12:32:52
 */
@Tag(name = "订单管理")
@RestController
@RequestMapping("/api/system/order")
public class OrderController extends BaseController {
    @Resource
    private OrderService orderService;
    @Resource
    private OrderGoodsService orderGoodsService;
    @Resource
    private MenuService menuService;
    @Resource
    private MenuMapper menuMapper;
    @Resource
    private UserService userService;

    /** 检查用户审核状态：auditStatus==null(老用户)或1(已通过)返回true，否则false */
    private boolean checkUserAuditStatus(User loginUser) {
        if (loginUser == null) return false;
        User user = userService.getByIdRel(loginUser.getUserId());
        if (user == null) return false;
        Integer auditStatus = user.getAuditStatus();
        // auditStatus == null 表示老用户（功能上线前注册的），默认放行
        return auditStatus == null || auditStatus == 1;
    }

    @Operation(summary = "分页查询订单")
    @GetMapping("/page")
    public ApiResult<PageResult<Order>> page(OrderParam param) {
        // 使用关联查询
      final User loginUser = getLoginUser();
      if (loginUser == null) {
        return fail("请先登陆",null);
      }
      // 非平台权限
      if (!loginUser.getTenantId().equals(5)) {
        param.setUserId(loginUser.getUserId());
      }
      return success(orderService.pageRel(param));
    }

    @PreAuthorize("hasAuthority('sys:order:list')")
    @OperationLog
    @Operation(summary = "查询全部订单")
    @GetMapping()
    public ApiResult<List<Order>> list(OrderParam param) {
      final User loginUser = getLoginUser();
      // 非平台权限
      if (!loginUser.getTenantId().equals(5)) {
        param.setUserId(loginUser.getUserId());
      }
        // 使用关联查询
        return success(orderService.listRel(param));
    }

    @PreAuthorize("hasAuthority('sys:order:list')")
    @OperationLog
    @Operation(summary = "根据id查询订单")
    @GetMapping("/{id}")
    public ApiResult<Order> get(@PathVariable("id") Integer id) {
        // 使用关联查询
        return success(orderService.getByIdRel(id));
    }

    @Operation(summary = "添加订单")
    @PostMapping()
    public ApiResult<?> save(@RequestBody Order order) {
        // 记录当前登录用户id
        User loginUser = getLoginUser();
        if(loginUser == null){
          return fail("请先登录");
        }
        if (!checkUserAuditStatus(loginUser)) {
            return fail("您的账号尚未通过审核，暂时无法下单");
        }
        if (ObjectUtil.isEmpty(order.getType())) {
          return fail("订单类型不能为空");
        }
        // 封装订单信息
        order.setUserId(loginUser.getUserId());
        order.setTenantId(loginUser.getTenantId());
        order.setOrderNo(Long.toString(IdUtil.getSnowflakeNextId()));
        order.setPhone(loginUser.getPhone());
        order.setRealName(loginUser.getRealName());
        // 购买商品
        if (order.getType().equals(0)) {
          order.setVersion(0);
        }
        // 购买插件
        if (order.getType().equals(1)) {
          order.setVersion(1);
        }

        if (orderService.save(order)) {
          // 余额支付
          if(order.getPayType().equals(0)){
            if (loginUser.getBalance().compareTo(order.getPayPrice()) < 0) {
              return fail("余额不足"+loginUser.getBalance()+"==="+order.getPayPrice());
            }
            return success("支付成功");
          }
        }
        return fail("添加失败");
    }

    @Operation(summary = "修改订单")
    @PutMapping()
    public ApiResult<?> update(@RequestBody Order order) {
        if (orderService.updateById(order)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('sys:order:remove')")
    @OperationLog
    @Operation(summary = "删除订单")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (orderService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('sys:order:save')")
    @OperationLog
    @Operation(summary = "批量添加订单")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<Order> list) {
        if (orderService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('sys:order:update')")
    @OperationLog
    @Operation(summary = "批量修改订单")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<Order> batchParam) {
        if (batchParam.update(orderService, "order_id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('sys:order:remove')")
    @OperationLog
    @Operation(summary = "批量删除订单")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (orderService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

  @Operation(summary = "统一下单")
  @PostMapping("/createOrder")
  public ApiResult<?> createOrder(@RequestBody Cart cart) {
    final MenuParam menuParam = new MenuParam();
    // 记录当前登录用户id
    User loginUser = getLoginUser();
    if (loginUser != null) {
      if (!checkUserAuditStatus(loginUser)) {
          return fail("您的账号尚未通过审核，暂时无法下单");
      }
      // 封装订单数据
      final Order order = new Order();
      order.setType(cart.getType());
      order.setPayType(cart.getPayType());
      order.setPayPrice(cart.getPayPrice());
      order.setTotalPrice(cart.getTotalPrice());
      order.setMonth(cart.getMonth());
      order.setUserId(loginUser.getUserId());
      order.setOrderNo(Long.toString(IdUtil.getSnowflakeNextId()));
      order.setPhone(loginUser.getPhone());
      order.setComments(cart.getComments());
      order.setTenantId(loginUser.getTenantId());
      order.setRealName(loginUser.getRealName());
      order.setPayTime(DateUtil.date());

      // 购买商品
      if (order.getType().equals(0)) {
        order.setVersion(0);
      }
      // 购买插件
      if (order.getType().equals(1)) {
        order.setVersion(1);
      }
      // 判断支付方式
      if(order.getPayType() == null){
        return fail("支付方式不能为空");
      }
      // 商品描述(必填)
      if (StrUtil.isBlank(order.getComments())) {
        return fail("商品描述(必填)");
      }
      // 微信支付
      if(order.getPayType().equals(1)){
        // 微信openid(必填)
        if (StrUtil.isBlank(loginUser.getOpenid())) {
          return fail("微信openid(必填)");
        }
        // 微信支付(商品金额不能为0)
        if (order.getTotalPrice().compareTo(BigDecimal.ZERO) == 0) {
          return fail("商品金额不能为0");
        }
      }
      // 创建订单成功
      if (orderService.save(order)) {
        final ArrayList<OrderGoods> orderGoods = new ArrayList<>();
        if (order.getType().equals(1)) {
          cart.getList().forEach(item -> {
            final OrderGoods og = new OrderGoods();
            og.setOrderId(order.getOrderId());
            og.setType(order.getType());
            og.setItemId(item.getCompanyId());
            og.setMenuId(item.getMenuId());
            og.setPayPrice(item.getPrice());
            og.setMonth(order.getMonth());
            og.setTotalNum(order.getCartNum());
            og.setPayStatus(false);
            og.setOrderStatus(0);
            og.setTenantId(loginUser.getTenantId());
            og.setUserId(loginUser.getUserId());
            og.setComments(item.getTenantName());
            orderGoods.add(og);
            menuParam.setMenuId(item.getMenuId());
            menuParam.setTenantId(item.getTenantId());
          });
        }
        // 记录订单商品
        orderGoodsService.saveBatch(orderGoods);

        // 余额支付
        if(order.getPayType().equals(0)){
          if (loginUser.getBalance().compareTo(order.getPayPrice()) < 0) {
            return fail("余额不足"+loginUser.getBalance()+"==="+order.getPayPrice());
          }
          // 附加插件参数
          order.setMenuParam(menuParam);
          // 执行支付成功后事务
          orderService.paySuccess(order);
          return success("余额支付成功");
        }
      }
    }
    return fail("下单失败");
  }
}
