package com.fs.app.controller.live;

import com.fs.app.controller.AppBaseController;
import com.fs.common.annotation.RepeatSubmit;
import com.fs.common.core.domain.R;
import com.fs.his.domain.FsUser;
import com.fs.his.service.IFsUserService;
import com.fs.live.domain.Live;
import com.fs.live.domain.LiveCompletionPointsRecord;
import com.fs.live.service.ILiveCompletionPointsRecordService;
import com.fs.live.service.ILiveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 直播完课积分Controller
 */
@RestController
@RequestMapping("/app/live/completion")
public class LiveCompletionPointsController extends AppBaseController {

    @Autowired
    private ILiveCompletionPointsRecordService completionPointsRecordService;

    @Autowired
    private IFsUserService fsUserService;

    @Autowired
    private ILiveService liveService;

    /**
     * 领取完课积分
     */
    @PostMapping("/receive")
    @RepeatSubmit
    public R receive(@RequestParam Long recordId) {
        Long userId = Long.parseLong(getUserId());
        LiveCompletionPointsRecord record = completionPointsRecordService.receiveCompletionPoints(recordId, userId);
        return R.ok().put("data", record);
    }

    /**
     * 获取用户未领取的积分列表
     */
    @GetMapping("/unreceived")
    public R getUnreceived(@RequestParam Long liveId) {
        Long userId = Long.parseLong(getUserId());
        List<LiveCompletionPointsRecord> records = completionPointsRecordService.getUserUnreceivedRecords(liveId, userId);
        return R.ok().put("data", records);
    }

    /**
     * 查询用户积分领取记录
     */
    @GetMapping("/records")
    public R getRecords(@RequestParam Long liveId) {
        Long userId = Long.parseLong(getUserId());
        List<LiveCompletionPointsRecord> records = completionPointsRecordService.getUserRecords(liveId, userId);
        return R.ok().put("data", records);
    }

    /**
     * 查询用户积分余额和看直播信息统计
     */
    @GetMapping("/info")
    public R getInfo(@RequestParam Long liveId) {
        Long userId = Long.parseLong(getUserId());

        // 1. 获取用户积分余额
        FsUser user = fsUserService.selectFsUserByUserId(userId);
        Long integral = user != null && user.getIntegral() != null ? user.getIntegral() : 0L;


        Live live = liveService.selectLiveByLiveId(liveId);

        // 3. 获取完课记录列表(包含已领取和未领取)
        List<LiveCompletionPointsRecord> records = completionPointsRecordService.getUserRecords(liveId, userId);

        // 4. 统计信息
        long totalPoints = records.stream()
                .filter(r -> r.getReceiveStatus() == 1)
                .mapToLong(LiveCompletionPointsRecord::getPointsAwarded)
                .sum();

        long unreceivedCount = records.stream()
                .filter(r -> r.getReceiveStatus() == 0)
                .count();

        Map<String, Object> result = new HashMap<>();
        result.put("integral", integral);  // 当前积分余额
        result.put("totalPoints", totalPoints);  // 本直播间累计获得积分
        result.put("totalDays", records.size());  // 累计看直播天数
        result.put("unreceivedCount", unreceivedCount);  // 未领取记录数
        result.put("records", records);  // 完课记录列表

        // 5. 添加直播状态和时间信息
        if (live != null) {
            result.put("status", live.getStatus());  // 直播状态
            result.put("startTime", live.getStartTime());  // 预告时间
            result.put("duration", live.getDuration());  // 直播总时长(秒)

            // 当status=2作为真开开始hide时间
            if (live.getStatus() != null && live.getStatus() == 2) {
                LocalDateTime now = LocalDateTime.now();

                result.put("serverTime", now);
                result.put("totalDuration", live.getDuration());  // 直播总时长(秒)
            }
        }

        return R.ok().put("data", result);
    }

    /**
     * 用于测试和调试
     */
    @PostMapping("/test/create")
    public R testCreateRecord(@RequestParam Long liveId, @RequestParam(required = false) Long watchDuration) {
        Long userId = Long.parseLong(getUserId());

        try {
            // 调用完课记录创建方法（watchDuration为null时会自动从数据库累计）
            completionPointsRecordService.checkAndCreateCompletionRecord(liveId, userId, watchDuration);
            return R.ok("完课记录创建成功，请查看records接口查看结果");
        } catch (Exception e) {
            return R.error("创建失败: " + e.getMessage());
        }
    }
}
