package com.gxwebsoft.shop.controller;

import cn.hutool.core.util.IdUtil;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.system.service.UserService;
import com.gxwebsoft.shop.entity.UserBalanceLog;
import com.gxwebsoft.shop.service.RechargeOrderService;
import com.gxwebsoft.shop.entity.RechargeOrder;
import com.gxwebsoft.shop.param.RechargeOrderParam;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.system.entity.User;
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.ArrayList;
import java.util.List;

import static com.gxwebsoft.common.core.constants.BalanceConstants.BALANCE_ADMIN;

/**
 * 会员充值订单表控制器
 *
 * @author 科技小王子
 * @since 2024-07-26 23:18:48
 */
@Api(tags = "会员充值订单表管理")
@RestController
@RequestMapping("/api/shop/recharge-order")
public class RechargeOrderController extends BaseController {
    @Resource
    private RechargeOrderService rechargeOrderService;
    @Resource
    private UserService userService;
    @Resource
    private UserBalanceLogService userBalanceLogService;

    @PreAuthorize("hasAuthority('shop:rechargeOrder:save')")
    @ApiOperation("会员充值")
    @PostMapping("/recharge")
    @Transactional(rollbackFor = {Exception.class})
    public ApiResult<?> recharge(@RequestBody RechargeOrder rechargeOrder) {
      // 充值
      User user = userService.getById(rechargeOrder.getUserId());
      BigDecimal balance = user.getBalance().add(rechargeOrder.getPayPrice());
      user.setBalance(balance);
      userService.updateById(user);
      // 保存充值记录
      rechargeOrder.setOrderNo(Long.toString(IdUtil.getSnowflakeNextId()));
      rechargeOrder.setBalance(balance);
      if (rechargeOrderService.save(rechargeOrder)) {
        // 记录余额明细
        UserBalanceLog userBalanceLog = new UserBalanceLog();
        userBalanceLog.setUserId(rechargeOrder.getUserId());
        userBalanceLog.setScene(BALANCE_ADMIN);
        userBalanceLog.setMoney(rechargeOrder.getPayPrice());
        userBalanceLog.setBalance(balance);
        userBalanceLog.setComments("操作人：" + getLoginUser().getNickname());
        userBalanceLog.setRemark(rechargeOrder.getComments());
        userBalanceLog.setMerchantCode(rechargeOrder.getMerchantCode());
        userBalanceLogService.save(userBalanceLog);
        return success("充值成功", user);
      }
      return fail("充值失败");
    }

    @PreAuthorize("hasAuthority('shop:rechargeOrder:list')")
    @ApiOperation("分页查询会员充值订单表")
    @GetMapping("/page")
    public ApiResult<PageResult<RechargeOrder>> page(RechargeOrderParam param) {
        // 使用关联查询
        return success(rechargeOrderService.pageRel(param));
    }

    @PreAuthorize("hasAuthority('shop:rechargeOrder:list')")
    @ApiOperation("查询全部会员充值订单表")
    @GetMapping()
    public ApiResult<List<RechargeOrder>> list(RechargeOrderParam param) {
        // 使用关联查询
        return success(rechargeOrderService.listRel(param));
    }

    @PreAuthorize("hasAuthority('shop:rechargeOrder:list')")
    @ApiOperation("根据id查询会员充值订单表")
    @GetMapping("/{id}")
    public ApiResult<RechargeOrder> get(@PathVariable("id") Integer id) {
        // 使用关联查询
        return success(rechargeOrderService.getByIdRel(id));
    }

    @ApiOperation("添加会员充值订单表")
    @PostMapping()
    public ApiResult<?> save(@RequestBody RechargeOrder rechargeOrder) {
        // 记录当前登录用户id
        User loginUser = getLoginUser();
        if (loginUser != null) {
         rechargeOrder.setUserId(loginUser.getUserId());
        }
        if (rechargeOrderService.save(rechargeOrder)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @ApiOperation("修改会员充值订单表")
    @PutMapping()
    public ApiResult<?> update(@RequestBody RechargeOrder rechargeOrder) {
        if (rechargeOrderService.updateById(rechargeOrder)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @ApiOperation("删除会员充值订单表")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (rechargeOrderService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('shop:rechargeOrder:save')")
    @ApiOperation("批量充值")
    @PostMapping("/batchRecharge")
    @Transactional(rollbackFor = {Exception.class})
    public ApiResult<?> batchRecharge(@RequestBody List<RechargeOrder> list) {
      if (rechargeOrderService.saveBatch(list)) {
          String nickname = getLoginUser().getNickname();
          ArrayList<User> users = new ArrayList<>(list.size());
          ArrayList<UserBalanceLog> logs = new ArrayList<>(list.size());

          list.forEach(d -> {
            User user = userService.getByIdRel(d.getUserId());
            BigDecimal balance = user.getBalance().add(d.getPayPrice());
            user.setBalance(balance);
            users.add(user);
            UserBalanceLog userBalanceLog = new UserBalanceLog();
            userBalanceLog.setUserId(d.getUserId());
            userBalanceLog.setScene(BALANCE_ADMIN);
            userBalanceLog.setMoney(d.getPayPrice());
            userBalanceLog.setBalance(balance);
            userBalanceLog.setComments("操作人：" + nickname);
            userBalanceLog.setRemark(d.getComments());
            userBalanceLog.setMerchantCode(d.getMerchantCode());
            logs.add(userBalanceLog);
          });

          // 批量充值
          userService.updateBatchById(users);
          // 记录余额明细
          userBalanceLogService.saveBatch(logs);
        return success("充值成功");
      }
      return fail("充值失败");
    }

    @PreAuthorize("hasAuthority('shop:rechargeOrder:update')")
    @ApiOperation("批量修改会员充值订单表")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<RechargeOrder> batchParam) {
        if (batchParam.update(rechargeOrderService, "order_id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('shop:rechargeOrder:remove')")
    @ApiOperation("批量删除会员充值订单表")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (rechargeOrderService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

}
