package com.fs.app.controller.live;

import com.fs.app.annotation.Login;
import com.fs.app.controller.AppBaseController;
import com.fs.app.facade.LiveFacadeService;
import com.fs.common.core.domain.R;
import com.fs.common.utils.ServletUtils;
import com.fs.live.domain.LiveUserRedRecord;
import com.fs.live.param.RedPO;
import com.fs.live.service.ILiveUserRedRecordService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/app/live/liveRed")
public class LiveRedController extends AppBaseController {

    @Autowired
    private LiveFacadeService liveFacadeService;

    @Autowired
    private ILiveUserRedRecordService liveUserRedRecordService;

    /**
     * 领取红包
     */
    @Login
    @PostMapping("/claim")
    public R claim(@RequestBody RedPO red) {
        red.setUserId(Long.parseLong(getUserId()));
        return liveFacadeService.redClaim(red);
    }

    /**
     * 查询用户自己领取直播间的红包记录
     * @return 红包记录列表
     */
    @Login
    @GetMapping("/list")
    public R list() {
        try {
            String userId = getUserId();
            if (userId == null || userId.isEmpty()) {
                return R.error("用户未登录");
            }
            // 分页参数
            String pageNum = ServletUtils.getParameter("pageNum");
            String pageSize = ServletUtils.getParameter("pageSize");
            int page = pageNum != null && !pageNum.isEmpty() ? Integer.parseInt(pageNum) : 1;
            int size = pageSize != null && !pageSize.isEmpty() ? Integer.parseInt(pageSize) : 10;

            // 构建查询条件
            LiveUserRedRecord query = new LiveUserRedRecord();
            query.setUserId(Long.parseLong(userId));

            // 分页查询
            PageHelper.startPage(page, size);
            List<LiveUserRedRecord> list = liveUserRedRecordService.selectLiveUserRedRecordList(query);
            PageInfo<LiveUserRedRecord> pageInfo = new PageInfo<>(list);

            return R.ok().put("data", pageInfo);
        } catch (Exception e) {
            log.error("查询用户红包记录失败", e);
            return R.error("查询失败：" + e.getMessage());
        }
    }

}
