package com.fs.live.controller;

import com.fs.common.annotation.Log;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.R;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.constant.HttpStatus;
import com.fs.common.enums.BusinessType;
import com.fs.common.utils.SecurityUtils;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.live.domain.LiveData;
import com.fs.live.param.*;
import com.fs.live.service.ILiveDataService;
import com.fs.live.vo.LiveDataCompanyVO;
import com.fs.live.vo.LiveUserFirstVo;
import com.fs.live.vo.LiveUserDetailExportVO;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/liveData/liveData")
public class LiveDataController extends BaseController {

    @Autowired
    private ILiveDataService liveDataService;

    /**
     * 直播数据页面卡片数据
     */
    @GetMapping("/dashboardData")
    public R dashboardData(@RequestParam Long liveId, HttpServletRequest request) {
        return liveDataService.dashboardData(liveId);
    }

    /**
     * 直播数据页面 分页查询邀请榜单
     */
    @GetMapping("/dashboardInviteList")
    public TableDataInfo inviteList(@RequestParam Long liveId, HttpServletRequest request) {
        startPage();
        List<LiveUserFirstVo> list = liveDataService.inviteList(liveId);
        return getDataTable(list);
    }

    /**
     * 查询新直播数据列表
     */
    @PreAuthorize("@ss.hasPermi('liveData:liveData:list')")
    @PostMapping("/listLiveData")
    public R listLiveData(@RequestBody LiveDataParam param, HttpServletRequest request)
    {
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        return liveDataService.listLiveData(param);
    }

    /**
     * 查询直播数据列表
     * */
    @PreAuthorize("@ss.hasPermi('liveData:liveData:query')")
    @GetMapping("/list")
    public List<LiveData> list(LiveData liveData) {
        return liveDataService.selectLiveDataList(liveData);
    }

    /**
     * 查询直播数据详情
     * */
    @PreAuthorize("@ss.hasPermi('liveData:liveData:query')")
    @GetMapping("/get/{liveId}")
    public R getLiveData(@PathVariable Long liveId) {
        return R.ok().put("liveData", liveDataService.selectLiveDataByLiveId(liveId));
    }

    /**
     * 点赞
     * */
    @PreAuthorize("@ss.hasPermi('liveData:liveData:edit')")
    @GetMapping("/like/{liveId}")
    public R like(@PathVariable Long liveId) {
        return R.ok(liveDataService.updateLikeByLiveId(liveId, SecurityUtils.getLoginUser().getUser().getUserId()));
    }

    /**
     * 收藏
     * */
    @PreAuthorize("@ss.hasPermi('liveData:liveData:edit')")
    @GetMapping("/collect/{liveId}")
    public R collect(@PathVariable Long liveId) {
        return R.ok(liveDataService.collect(liveId, SecurityUtils.getLoginUser().getUser().getUserId()));
    }

    /**
     * 关注
     * */
    @PreAuthorize("@ss.hasPermi('liveData:liveData:edit')")
    @GetMapping("/follow/{liveId}")
    public R follow(@PathVariable Long liveId) {
        return R.ok(liveDataService.follow(liveId, SecurityUtils.getLoginUser().getUser().getUserId()));
    }

    /**
     * 获取直播内数据
     * */
    @PreAuthorize("@ss.hasPermi('liveData:liveData:query')")
    @GetMapping("/getLiveViewData")
    public R getLiveViewData(Long liveId) {
        Map<String,Object> liveViewData =liveDataService.getLiveViewData(liveId);
        return R.ok(liveViewData);
    }

    /**
     * 查询直播间详情数据（SQL方式）
     * @param liveId 直播间ID
     * @return 详情数据
     */
    @PreAuthorize("@ss.hasPermi('liveData:liveData:query')")
    @GetMapping("/getLiveDataDetailBySql")
    public R getLiveDataDetailBySql(@RequestParam Long liveId) {
        return liveDataService.getLiveDataDetailBySql(liveId);
    }

    /**
     * 查询直播间用户详情列表（SQL方式）
     * @param liveId 直播间ID
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @return 用户详情列表
     */
    @PreAuthorize("@ss.hasPermi('liveData:liveData:query')")
    @GetMapping("/getLiveUserDetailListBySql")
    public R getLiveUserDetailListBySql(@RequestParam Long liveId,
                                        @RequestParam(defaultValue = "1") Integer pageNum,
                                        @RequestParam(defaultValue = "100") Integer pageSize) {
        // 限制最大每页查询条数为1000
        if (pageSize > 1000) {
            pageSize = 1000;
        }

        PageHelper.startPage(pageNum, pageSize);
        return liveDataService.getLiveUserDetailListBySql(liveId,null,null);
    }

    /**
     * 查询直播间详情数据（查询数据服务器处理方式）
     * @param liveId 直播间ID
     * @return 详情数据
     */
    @PreAuthorize("@ss.hasPermi('liveData:liveData:query')")
    @GetMapping("/getLiveDataDetailByServer")
    public R getLiveDataDetailByServer(@RequestParam Long liveId) {
        return liveDataService.getLiveDataDetailByServer(liveId);
    }

    /**
     * 查询直播间用户详情列表（查询数据服务器处理方式）
     * @param liveId 直播间ID
     * @return 用户详情列表
     */
    @PreAuthorize("@ss.hasPermi('liveData:liveData:query')")
    @GetMapping("/getLiveUserDetailListByServer")
    public R getLiveUserDetailListByServer(@RequestParam Long liveId) {
        return liveDataService.getLiveUserDetailListByServer(liveId);
    }

    /**
     * 导出直播间用户详情数据
     * @param liveId 直播间ID
     * @return Excel文件
     */
    @PreAuthorize("@ss.hasPermi('liveData:liveData:export')")
    @Log(title = "直播间用户详情", businessType = BusinessType.EXPORT)
    @GetMapping("/exportLiveUserDetail")
    public AjaxResult exportLiveUserDetail(@RequestParam Long liveId) {
        List<LiveUserDetailExportVO> list = liveDataService.exportLiveUserDetail(liveId,null,null);
        if (list == null || list.isEmpty()) {
            return AjaxResult.error("未找到用户详情数据");
        }

        ExcelUtil<LiveUserDetailExportVO> util = new ExcelUtil<>(LiveUserDetailExportVO.class);
        return util.exportExcel(list, "直播间用户详情数据");
    }

    /**
     * 直播数据统计-数据概览（12项指标）
     * @param liveIds 直播间ID列表，前端传入
     */
    @PreAuthorize("@ss.hasPermi('liveData:liveData:query')")
    @PostMapping("/getLiveStatisticsOverview")
    public R getLiveStatisticsOverview(@RequestBody List<Long> liveIds) {

        return R.ok().put("data",liveDataService.getLiveStatisticsOverview(liveIds != null ? liveIds : Collections.emptyList()));
    }

    /**
     * 直播趋势-进入人数折线图
     * 基于 live_user_first_entry 与 live.start_time 计算相对时间，开播前进入的归为"开播前"
     * @param liveIds 直播间ID列表
     */
    @PreAuthorize("@ss.hasPermi('liveData:liveData:query')")
    @PostMapping("/getLiveEntryTrend")
    public R getLiveEntryTrend(@RequestBody List<Long> liveIds) {
        return R.ok().put("data", liveDataService.getLiveEntryTrend(liveIds != null ? liveIds : Collections.emptyList()));
    }

    /**
     * 直播间学员列表（分页，基于 live_user_first_entry）
     * 筛选：直播名称（liveIds）、首次访问时间范围
     */
    @PreAuthorize("@ss.hasPermi('liveData:liveData:query')")
    @PostMapping("/listLiveRoomStudents")
    public R listLiveRoomStudents(@RequestBody LiveRoomStudentParam param) {
        return liveDataService.listLiveRoomStudents(param);
    }

    /**
     * 商品对比统计（商品名称、下单未支付人数、成交人数、成交金额）
     */
    @PreAuthorize("@ss.hasPermi('liveData:liveData:query')")
    @PostMapping("/listProductCompareStats")
    public R listProductCompareStats(@RequestBody ProductCompareParam param) {
        return liveDataService.listProductCompareStats(param);
    }

    /**
     * 邀课对比-分享人选项列表（基于 live_user_first_entry 中存在的销售）
     */
    @PreAuthorize("@ss.hasPermi('liveData:liveData:query')")
    @PostMapping("/listInviteSalesOptions")
    public R listInviteSalesOptions(@RequestBody List<Long> liveIds) {
        return R.ok().put("data", liveDataService.listInviteSalesOptions(liveIds != null ? liveIds : Collections.emptyList()));
    }

    /**
     * 邀课对比统计（归属公司、销售名称、邀请人数、已支付订单数、订单总金额）
     */
    @PreAuthorize("@ss.hasPermi('liveData:liveData:query')")
    @PostMapping("/listInviteCompareStats")
    public R listInviteCompareStats(@RequestBody InviteCompareParam param) {
        return liveDataService.listInviteCompareStats(param);
    }

    /**
     * 查询分公司直播数据统计列表
     */
    @PreAuthorize("@ss.hasPermi('liveData:liveData:list')")
    @PostMapping("/listLiveDataCompany")
    public TableDataInfo listLiveDataCompany(@RequestBody LiveDataCompanyParam param) {
        List<LiveDataCompanyVO> list = liveDataService.listLiveDataCompany(param);
        int total = list.size();
        int pageNum = param.getPageNum() == null || param.getPageNum() < 1 ? 1 : param.getPageNum();
        int pageSize = param.getPageSize() == null || param.getPageSize() < 1 ? total : param.getPageSize();
        int fromIndex = Math.min((pageNum - 1) * pageSize, total);
        int toIndex = Math.min(fromIndex + pageSize, total);
        List<LiveDataCompanyVO> pageList = fromIndex >= toIndex ? Collections.emptyList() : list.subList(fromIndex, toIndex);

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(pageList);
        rspData.setTotal(total);
        return rspData;
    }

    /**
     * 导出分公司直播数据统计
     */
    @PreAuthorize("@ss.hasPermi('liveData:liveData:export')")
    @Log(title = "分公司直播数据统计", businessType = BusinessType.EXPORT)
    @PostMapping("/exportLiveDataCompany")
    public AjaxResult exportLiveDataCompany(@RequestBody LiveDataCompanyParam param) {
        List<LiveDataCompanyVO> list = liveDataService.listLiveDataCompany(param);
        ExcelUtil<LiveDataCompanyVO> util = new ExcelUtil<>(LiveDataCompanyVO.class);
        return util.exportExcel(list, "分公司直播数据统计");
    }

}
