package com.fs.app.controller;

import com.alibaba.fastjson.JSONObject;
import com.fs.app.annotation.Login;
import com.fs.app.facade.LiveFacadeService;
import com.fs.app.vo.LiveInfoVo;
import com.fs.common.vo.LiveVo;
import com.fs.app.websocket.bean.SendMsgVo;
import com.fs.common.annotation.RepeatSubmit;
import com.fs.common.core.domain.BaseEntity;
import com.fs.common.core.domain.R;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.ServletUtils;
import com.fs.common.utils.bean.BeanUtils;
import com.fs.live.domain.Live;
import com.fs.live.domain.LiveMsg;
import com.fs.live.domain.LiveVideo;
import com.fs.live.service.ILiveGoodsService;
import com.fs.live.service.ILiveMsgService;
import com.fs.live.service.ILiveService;
import com.fs.live.service.ILiveVideoService;
import com.fs.live.vo.LiveCartVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.fs.common.core.page.PageRequest;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;

import static com.fs.live.service.impl.LiveServiceImpl.to16Hex;
import static com.github.pagehelper.page.PageMethod.startPage;


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

	private static final Logger log = LoggerFactory.getLogger(LiveController.class);
	private final ILiveService liveService;
	private final ILiveMsgService liveMsgService;



	@Autowired
	private ILiveGoodsService liveGoodsService;

	@Autowired
	private ILiveVideoService videoService;
	@Autowired
	private LiveFacadeService liveFacadeService;




	@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("直播未开放");
		Long storeId = liveGoodsService.getStoreIdByLiveId(live.getLiveId());
		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).put("storeId", storeId);*/
		return liveFacadeService.liveDetail(id);
	}

	@Login
	@ApiOperation("直播间列表")
	@GetMapping("/liveList")
	@ApiResponse(code = 200, message = "", response = LiveInfoVo.class)
	public R liveList(PageRequest pageRequest) {
/*		PageHelper.startPage(Integer.parseInt(ServletUtils.getParameter("pageNum")) ,Integer.parseInt(ServletUtils.getParameter("pageSize")) );
		try {
			List<Live> list = liveService.liveList();
			PageInfo<Live> result = new PageInfo<>(list);
			return R.ok().put("data", result);
		} catch (Exception e) {
			return R.error("操作异常");
		}*/
		return liveFacadeService.liveList(pageRequest);
	}

	@Login
	@ApiOperation("直播间列表")
	@GetMapping("/liveList/{companyId}")
	@ApiResponse(code = 200, message = "", response = LiveInfoVo.class)
	public R liveCompanyList(PageRequest pageRequest,@PathVariable Long companyId) {
		PageHelper.startPage(Integer.parseInt(ServletUtils.getParameter("pageNum")) ,Integer.parseInt(ServletUtils.getParameter("pageSize")) );
		try {
			List<Live> list = liveService.liveCompanyList(companyId);
			PageInfo<Live> result = new PageInfo<>(list);
			return R.ok().put("data", result);
		} catch (Exception e) {
			return R.error("操作异常");
		}
//		return liveFacadeService.liveList(pageRequest);
	}


	@Login
	@ApiOperation("聊天记录（最新30条）")
	@GetMapping("/msgList")
	@ApiResponse(code = 200, message = "", response = LiveInfoVo.class)
	public R msgList(Long id) {
		List<LiveMsg> list = liveMsgService.listRecentMsg(id);
		list.sort(Comparator.comparing(BaseEntity::getCreateTime));
		return R.ok().put("data", list);
	}

	@PostMapping("/create")
	@RepeatSubmit
	public R createRoom(@RequestBody Map<String, Object> payload) {
		if (!payload.containsKey("liveId")) {
			return R.error("直播间id缺失");
		}
		Long liveId = Long.valueOf(payload.get("liveId").toString());
		return liveService.createLiveRoom(liveId);
	}


	@PostMapping("/checkLive")
	public R checkLiving(@RequestBody Map<String, String> payload) {
		// 销售端判断是否拥有直播权限
		return liveService.checkLiving(payload);
	}

	@GetMapping("/{liveId}")
	public R getRoom(@PathVariable String liveId) {
		return liveService.getLiveRoom(liveId);
	}


//	// 直播开播回调
//	@PostMapping("/startLiving")
//	public R checkLiving(HttpServletRequest request, @RequestBody  Map<String, String> params) {
//		log.info("请求参数：{}", params);
//		SendMsgVo sendMsgVo = new SendMsgVo();
//		sendMsgVo.setMsg("开始直播");
//		sendMsgVo.setCmd("live_start");
//		webSocketServer.broadcastMessage(Long.valueOf(params.get("stream_id")), JSONObject.toJSONString(R.ok().put("data",sendMsgVo)));
//		return R.ok();
////		{app=200149.push.tlivecloud.com, appid=1319721001, appname=live, channel_id=667, errcode=0,
////		errmsg=, event_time=1753840982, event_type=1,
////		height=1080, idc_id=38, node=113.249.151.16,
////		sequence=702115889072680959, set_id=2, stream_id=667,
////		stream_param=txSecret=6E89AECCA08DBEE82E7F5870BCED7132&txTime=688ACD21, user_ip=125.80.218.101, width=1920}
//	}
//
//	// 直播结束回调
//	@PostMapping("/endLiving")
//	public R endLiving(HttpServletRequest request, @RequestBody  Map<String, String> params) {
//		log.info("请求参数：{}", params);
//		SendMsgVo sendMsgVo = new SendMsgVo();
//		sendMsgVo.setMsg("结束直播");
//		sendMsgVo.setCmd("live_end");
//		webSocketServer.broadcastMessage(Long.valueOf(params.get("stream_id")), JSONObject.toJSONString(R.ok().put("data",sendMsgVo)));
//		Live live = new Live();
//		live.setLiveId(Long.valueOf(params.get("stream_id")));
//		live.setStatus(3);
//		live.setFinishTime(LocalDateTime.now());
//		liveService.updateLive(live);
//		return R.ok();
////		{app=200149.push.tlivecloud.com, appid=1319721001, appname=live, channel_id=673,
////				errcode=1, errmsg=The push client actively stopped the push, event_time=1755571239,
////				event_type=0, height=1080, idc_id=38, node=113.250.23.118, push_duration=1051237,
////				sequence=721865018844564968, set_id=2, stream_id=673,
////				stream_param=txSecret=A3EF362C9484D3D091C2E9B08C2C08CB&txTime=68A53145,
////				user_ip=113.248.98.28, width=1920}
//
//	}
//
//	// 直播录制文件回调 腾讯云 cos桶 fs
//	@PostMapping("/liveReplayFile")
//	public R liveReplayFile(HttpServletRequest request, @RequestBody  Map<String, String> params) {
//		log.info("请求参数：{}", params);
//		Long liveId = Long.valueOf(params.get("stream_id"));
//		LiveVideo liveVideo = new LiveVideo();
//		LiveVideo exist = videoService.selectLiveVideoByLiveId(liveId);
//		if (exist != null) {
//			liveVideo = exist;
//		}
//		Date nowDate = DateUtils.getNowDate();
//		liveVideo.setLiveId(liveId);
//		liveVideo.setVideoUrl(params.get("video_url"));
//		liveVideo.setVideoType(2);
//		liveVideo.setDuration(Long.valueOf(params.get("duration")));
//		liveVideo.setCreateTime(nowDate);
//		liveVideo.setUpdateTime(nowDate);
//		videoService.saveOrUpdate(liveVideo);
//		return R.ok();
////		{app=200149.push.tlivecloud.com, appid=1319721001, appname=live,
////				callback_ext={"video_codec":"h264","session_id":"1755326625589574166","resolution":"1920x1080"},
////			channel_id=774, duration=137, end_time=1757387736, end_time_usec=476103, event_type=100, file_format=mp4,
////					file_id=1319721001_d69054948de44655b465aaf725cafc1c, file_size=45806289, media_start_time=80, record_bps=0,
////				record_file_id=1319721001_d69054948de44655b465aaf725cafc1c, record_temp_id=1595756, start_time=1757387600, start_time_usec=942579,
////				stream_id=774, stream_param=txSecret=CBF1E86FB1AD58B9CC25941F6B9DA854&txTime=68C0E304, task_id=1755326625589574166, video_id=1319721001_05396a7c47914b40aa9ffefcb0ea4626,
////				video_url=http://fs-1319721001.cos.ap-chongqing.myqcloud.com/origin/200149.push.tlivecloud.com/live/774/1755326625589574166-6a9899ea95be4e89be0eeb30cf458579/2025-09-09-11-13-20.mp4}
//
//	}
	@GetMapping("/currentActivities")
	@Transactional
	@Login
	public R currentActivities(Long liveId) {
/*		String userId = getUserId();
		return liveService.currentActivities(liveId,userId);*/
		return liveFacadeService.currentActivities(liveId,getUserId());
	}

	@PostMapping("/subNotifyLive")
	@Transactional
	@Login
	public R subNotifyLive(@RequestBody HashMap<String,Object> param) {
/*		String userId = getUserId();
		return liveService.currentActivities(liveId,userId);*/
		return liveService.subNotifyLive(param);
	}

	@GetMapping("/test")
	@Transactional
	public void test() {

	}


}
