package io.controller;


import io.annotation.Login;
import io.annotation.LoginUser;
import io.common.constant.Constant;
import io.common.exception.RenException;
import io.common.page.PageData;
import io.common.utils.Result;
import io.common.validator.AssertUtils;
import io.common.validator.ValidatorUtils;
import io.common.validator.group.AddGroup;
import io.common.validator.group.DefaultGroup;
import io.common.validator.group.UpdateGroup;
import io.entity.UserEntity;
import io.modules.item.dto.AccountDTO;
import io.modules.item.dto.ItemDTO;
import io.modules.item.dto.OrderDTO;
import io.modules.item.service.AccountService;
import io.modules.item.service.ItemService;
import io.modules.item.service.OrderService;
import io.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 订单表
 */
@RestController
@RequestMapping("/api/order")
@Tag(name="订单表")
@CrossOrigin
public class OrderController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private ItemService itemService;
    @Autowired
    private  UserService userService;
    @Autowired
    private  AccountService accountService;

    @Value("${upload.url}")
    private String uploadUrl;

    @GetMapping("page")
    @Operation(summary = "分页")
    @Parameters({
        @Parameter(name = Constant.PAGE, description = "当前页码，从1开始", in = ParameterIn.QUERY, required = true, ref="int") ,
        @Parameter(name = Constant.LIMIT, description = "每页显示记录数", in = ParameterIn.QUERY,required = true, ref="int") ,
        @Parameter(name = Constant.ORDER_FIELD, description = "排序字段", in = ParameterIn.QUERY, ref="String") ,
        @Parameter(name = Constant.ORDER, description = "排序方式，可选值(asc、desc)", in = ParameterIn.QUERY, ref="String")
    })
    @Login
    public Result<PageData<OrderDTO>> page(@Parameter(hidden = true) @RequestParam Map<String, Object> params,@Parameter(hidden = true) @RequestAttribute("userId") Long userId){
        params.put("userId",userId.toString());
        PageData<OrderDTO> page = orderService.page(params);
        List<OrderDTO> collect = page.getList().stream().map(e -> {
            ItemDTO item = itemService.get(e.getItemId());
            if(item != null){
                item.setImage(uploadUrl +  item.getImage());
            }
            e.setItem(item);
            return e;
        }).collect(Collectors.toList());

        page.setList(collect);
        return new Result<PageData<OrderDTO>>().ok(page);
    }

    @GetMapping("{id}")
    @Operation(summary = "信息")
    public Result<OrderDTO> get(@PathVariable("id") Long id){
        OrderDTO data = orderService.get(id);
        return new Result<OrderDTO>().ok(data);
    }

    @PostMapping
    @Operation(summary = "保存")
    @Login
    public Result save(@RequestBody OrderDTO dto, @Parameter(hidden = true) @LoginUser UserEntity user){

        //判断余额是否充足
        BigDecimal balance = user.getBalance();
        BigDecimal totalAmount = dto.getTotalAmount();
        if (!isBalanceSufficient(balance, totalAmount)) {
            throw new RenException("账户余额不足，当前余额: " + balance + "，需支付: " + totalAmount);
        }

        //余额充足
        BigDecimal subtract = user.getBalance().subtract(totalAmount);
        user.setBalance(subtract);
        userService.updateById(user);
        //添加日志
        AccountDTO account = new AccountDTO();
        account.setUserId(user.getId());
        account.setNote("购买");
        account.setBalance(subtract);
        accountService.save(account);
        dto.setUserId(user.getId());
        orderService.save(dto);
        return new Result();
    }


    public boolean isBalanceSufficient(BigDecimal userBalance, BigDecimal requiredAmount) {
        // 1. 检查参数是否为null（安全防护）
        if (userBalance == null || requiredAmount == null) {
            throw new IllegalArgumentException("金额参数不能为null");
        }

        // 2. 比较余额是否足够（使用compareTo方法）
        //    compareTo返回:
        //    -1 表示 userBalance < requiredAmount
        //    0  表示 userBalance = requiredAmount
        //    1  表示 userBalance > requiredAmount
        return userBalance.compareTo(requiredAmount) >= 0;
    }

    @PutMapping
    @Operation(summary = "修改")
    public Result update(@RequestBody OrderDTO dto){
        orderService.update(dto);
        return new Result();
    }

    @DeleteMapping("{id}")
    @Operation(summary = "删除")
    public Result delete(@PathVariable Long id) {
        Long[] ids = new Long[]{id};
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");
        orderService.delete(ids);
        return new Result();
    }
}
