package com.ytpm.controller.qnjz;

import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ytpm.advertise.enums.AdSourceTypeEnum;
import com.ytpm.app.model.YtDyzAdRecord;
import com.ytpm.app.model.YtDyzUser;
import com.ytpm.app.param.AppQueryUserTodayTimeParam;
import com.ytpm.app.param.AppUserParam;
import com.ytpm.app.param.AppUserQueryParam;
import com.ytpm.app.param.AppUserTodayBannedParam;
import com.ytpm.app.param.YtAppUserListParam;
import com.ytpm.app.view.HourCountView;
import com.ytpm.app.view.YtAppUserListView;
import com.ytpm.dao.qnjz.QNAdRecordMapper;
import com.ytpm.dao.qnjz.QNLoginRecordMapper;
import com.ytpm.dao.qnjz.QNQuestionMapper;
import com.ytpm.dao.qnjz.QNUserMapper;
import com.ytpm.general.RepMessage;
import com.ytpm.general.Result;
import com.ytpm.general.ResultTable;
import lombok.extern.slf4j.Slf4j;
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 javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/qn/user")
public class QnUserController {
    @Resource
    private QNUserMapper qnUserMapper;
    @Resource
    private QNLoginRecordMapper qnloginRecordMapper;
    @Resource
    QNAdRecordMapper qnadRecordMapper;
    @Resource
    private QNQuestionMapper qnquestionMapper;

    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * 查询app 所有玩家
     */
    @PostMapping("/queryAll")
    public ResultTable<YtAppUserListView> queryAll(@RequestBody YtAppUserListParam param) {
        PageHelper.startPage(param.getPage(), param.getLimit());
        List<YtAppUserListView> dyzUsers = qnUserMapper.queryAll(param);
        if (dyzUsers.isEmpty()) return ResultTable.resultTableOk(new PageInfo<YtAppUserListView>(dyzUsers));
        List<YtDyzAdRecord> adRecords = qnadRecordMapper.getByUserIds(
                dyzUsers.stream().map(YtAppUserListView::getUserId).collect(Collectors.joining(",")));
        Map<String, List<YtDyzAdRecord>> userAdMap = adRecords.stream().collect(
                Collectors.groupingBy(YtDyzAdRecord::getUserId));
        setUserExtInfo(dyzUsers,userAdMap);
        return ResultTable.resultTableOk(new PageInfo<YtAppUserListView>(dyzUsers));
    }

    /**
     * 设置用户扩展信息
     */
    private void setUserExtInfo(List<YtAppUserListView> dyzUsers, Map<String, List<YtDyzAdRecord>> userAdMap) {
        for (YtAppUserListView user : dyzUsers) {
            user.setLoginRecordList(qnloginRecordMapper.getLoginRecords(user.getUserId()));
            //获取今日收益 | 今日视频播放数
            if (userAdMap.containsKey(user.getUserId())) {
                List<YtDyzAdRecord> ytDyzAdRecords = userAdMap.get(user.getUserId());
                List<YtDyzAdRecord> collect = ytDyzAdRecords.stream().filter(
                        s -> DateUtil.isSameDay(DateUtil.date(),DateUtil.parseDate(s.getFinishTime()))).collect(Collectors.toList());
                BigDecimal todayIncome = collect.stream().map(YtDyzAdRecord::getRevenue).reduce(BigDecimal.ZERO, BigDecimal::add);
                user.setTodayVideo((int) collect.stream().filter(
                        s->s.getAdSourceType()== AdSourceTypeEnum.rewarded_video.getAdSourceType()).count());
                user.setTodayIncome(todayIncome);
            } else {
                user.setTodayIncome(BigDecimal.ZERO);
                user.setTodayVideo(0);
            }
        }
    }
    /**
     * 计算广告记录列表中今日的收益
     *
     * @param records 广告记录列表
     * @return 今日收益总额（BigDecimal）
     */
    public static BigDecimal calculateTodayIncome(List<YtDyzAdRecord> records) {
        // 空列表快速返回
        if (records == null || records.isEmpty()) {
            return BigDecimal.ZERO;
        }

        // 获取今天的日期范围
        LocalDate today = LocalDate.now();
        LocalDateTime startOfDay = today.atStartOfDay();
        LocalDateTime endOfDay = today.plusDays(1).atStartOfDay();

        // 预计算今天的日期字符串前缀（优化性能）
        String todayPrefix = today.format(DateTimeFormatter.ISO_DATE) + " ";

        return calculateTodayIncome(records, startOfDay, endOfDay, todayPrefix);
    }

    /**
     * 计算广告记录列表中今日的收益（带日期范围参数，适用于批量处理）
     *
     * @param records     广告记录列表
     * @param startOfDay  今日开始时间
     * @param endOfDay    今日结束时间
     * @param todayPrefix 今日日期前缀（格式："yyyy-MM-dd "）
     * @return 今日收益总额（BigDecimal）
     */
    public static BigDecimal calculateTodayIncome(
            List<YtDyzAdRecord> records,
            LocalDateTime startOfDay,
            LocalDateTime endOfDay,
            String todayPrefix) {

        // 空列表快速返回
        if (records == null || records.isEmpty()) {
            return BigDecimal.ZERO;
        }

        BigDecimal totalToday = BigDecimal.ZERO;

        for (YtDyzAdRecord record : records) {
            String dateStr = record.getFinishTime();

            // 1. 日期字符串是否存在且以今日日期开头
            if (dateStr == null || !dateStr.startsWith(todayPrefix)) {
                continue;
            }
            try {
                // 2. 解析日期时间
                LocalDateTime recordTime = LocalDateTime.parse(dateStr, DATE_TIME_FORMATTER);

                // 3. 检查是否在今日范围内
                if (recordTime.isBefore(startOfDay) || recordTime.isAfter(endOfDay.minusNanos(1))) {
                    continue;
                }
                // 4. 累加
                BigDecimal revenue = record.getRevenue();
                if (revenue != null) {
                    totalToday = totalToday.add(revenue);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return totalToday;
    }



    /**
     * 主键查询用户信息
     */
    @GetMapping("/getUserInfo")
    public Result<YtDyzUser> getUserInfo(@RequestParam("userId") String userId) {
        YtDyzUser user = qnUserMapper.selectPrimaryKey(userId);
        user.setLoginRecordList(qnloginRecordMapper.getLoginRecords(userId));
        user.setTodayAnswerCount(qnquestionMapper.getAnswerCount(userId,1));
        user.setHistoryAnswerCount(qnquestionMapper.getAnswerCount(userId,2));
        user.setAnswerRecordList(qnquestionMapper.getAnswerRecords(userId));
        return Result.resultObjOk(user);
    }

    /**
     * 查询用户信息
     */
    @PostMapping("/getUserList")
    public ResultTable<YtDyzUser> getUserList(@RequestBody AppUserParam param) {
        List<YtDyzUser> userList = qnUserMapper.getUserList(param.getUserIds());
        for (YtDyzUser user : userList) {
            user.setLoginRecordList(qnloginRecordMapper.getLoginRecords(user.getUserId()));
        }
        return ResultTable.resultTableOk(new PageInfo<>(userList));
    }

    @PostMapping("/getUserAll")
    public ResultTable<YtDyzUser> getUserAll(@RequestBody AppUserParam param) {
        List<YtDyzUser> userList = qnUserMapper.getUserList(param.getUserIds());
        return ResultTable.resultTableOk(new PageInfo<>(userList));
    }

    /**
     * 修改用户信息
     */
    @PostMapping("/updateUserInfo")
    public Result<?> updateUserInfo(@RequestBody YtDyzUser dyzUser) {
        qnUserMapper.updateUser(dyzUser);
        return Result.resultOk(RepMessage.MODIFY_SUCCESS);
    }

    /**
     * 查询用户的广告记录
     */
    @GetMapping("/adRecords")
    public ResultTable<YtDyzAdRecord> adRecords(@RequestParam(name = "userId",required = true) String userId,@RequestParam(name = "adsourceType",required = false)Integer adsourceType) {
        return ResultTable.resultTableOk(new PageInfo<YtDyzAdRecord>(qnadRecordMapper.getByUserId(userId,adsourceType)));
    }

    @PostMapping("/queryUserByTime")
    public List<YtDyzUser> queryUserByTime(@RequestBody AppUserQueryParam appUserQueryParam) {
        List<YtDyzUser> ytDyzUsers = qnUserMapper.queryAllByTime(appUserQueryParam.getStartTime(), appUserQueryParam.getEndTime(),appUserQueryParam.getAppIdList());
        return ytDyzUsers;
    }

    @PostMapping("/queryUserByTodayTime")
    public int[] queryUserByTodayTime(@RequestBody AppQueryUserTodayTimeParam appQueryUserTodayTimeParam) {
        // 获取当前日期
        LocalDate localDate = LocalDate.now();

        // 构建当天起始时间段
        LocalDateTime startOfDay = localDate.atStartOfDay();
        LocalDateTime endOfDay = startOfDay.plusDays(1).minusSeconds(1);

        Date startTime = Date.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant());
        Date endTime = Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant());
        // 查询用户注册数据
        List<HourCountView> hourCountViews = qnUserMapper.countUsersByHour(startTime, endTime,appQueryUserTodayTimeParam.getAppIdList());
        // 初始化每小时用户数量数组
        int[] hourlyCounts = new int[24];
        for (HourCountView hc : hourCountViews) {
            if (hc.getHour() >= 0 && hc.getHour() < 24) {
                hourlyCounts[hc.getHour()] = hc.getCount();
            }
        }
        return hourlyCounts;
    }

    @PostMapping("/queryLoginRecords")
    public List<String> queryLoginRecords(@RequestBody AppUserQueryParam appUserQueryParam) {
        return qnloginRecordMapper.queryLoginCount(appUserQueryParam);
    }

    @GetMapping("/queryByOpenid")
    public List<YtDyzUser> queryByOpenid(@RequestParam("openid") String openid){
        return qnUserMapper.queryByOpenid(openid);
    }
    @PostMapping("/queryTodayBanned")
    public List<YtDyzUser> queryTodayBanned(@RequestBody AppUserTodayBannedParam appUserTodayBannedParam){
        return qnUserMapper.queryTodayBanned(appUserTodayBannedParam.getStartTime(), appUserTodayBannedParam.getEndTime(), appUserTodayBannedParam.getUserIdList());
    }

}
