package com.fs.app.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fs.app.annotation.Login;
import com.fs.app.vo.LiveInfoVo;
import com.fs.app.vo.LiveVo;
import com.fs.common.core.domain.BaseEntity;
import com.fs.common.core.domain.R;
import com.fs.common.utils.bean.BeanUtils;
import com.fs.live.domain.Live;
import com.fs.live.domain.LiveMsg;
import com.fs.live.service.ILiveMsgService;
import com.fs.live.service.ILiveService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Comparator;
import java.util.List;


@Api("直播信息接口")
@RestController
@AllArgsConstructor
@RequestMapping(value="/app/live")
public class LiveController extends AppBaseController {

	private final ILiveService liveService;
	private final ILiveMsgService liveMsgService;

	@ApiOperation("直播封面信息")
	@GetMapping("/liveInfo")
	@ApiResponse(code = 200, message = "", response = LiveInfoVo.class)
	public R liveInfo(Long id) {
		LocalDateTime now = LocalDateTime.now();
		Live live = liveService.selectLiveByLiveId(id);
		if(live == null) return R.error("未找到直播");
		if(live.getIsShow() == 2) return R.error("直播未开放");
		LiveInfoVo vo = new LiveInfoVo();
		BeanUtils.copyProperties(live, vo);
		vo.setId(live.getLiveId());
		return R.ok().put("data", vo);
	}

	@Login
	@ApiOperation("直播间")
	@GetMapping("/live")
	@ApiResponse(code = 200, message = "", response = LiveVo.class)
	public R live(Long id) {
		LocalDateTime now = LocalDateTime.now();
		Live live = liveService.selectLiveByLiveId(id);
		if(live == null) return R.error("未找到直播");
		if(live.getIsShow() == 2) return R.error("直播未开放");
		LiveVo liveVo = new LiveVo();
		BeanUtils.copyProperties(live, liveVo);
		liveVo.setNowDuration(200L);
		if(live.getStatus() == 2){
			long seconds = live.getStartTime().until(now, ChronoUnit.SECONDS);
			liveVo.setNowDuration(seconds);
		}
		if(liveVo.getNowDuration() != null){
			liveVo.setNowPri(BigDecimal.valueOf(liveVo.getDuration()).divide(BigDecimal.valueOf(liveVo.getNowDuration()), 20, RoundingMode.UP));
		}
		return R.ok().put("data", liveVo);
	}
	@Login
	@ApiOperation("聊天记录（最新30条）")
	@GetMapping("/msgList")
	@ApiResponse(code = 200, message = "", response = LiveInfoVo.class)
	public R msgList(Long id) {
		List<LiveMsg> list = liveMsgService.list(new QueryWrapper<LiveMsg>().eq("live_id", id).orderByDesc("create_time").last(" limit 30"));
		list.sort(Comparator.comparing(BaseEntity::getCreateTime));
		return R.ok().put("data", list);
	}

}
