package com.platform.modules.foreign.controller;/**
 * Created by TROY on 2019/2/20.
 */

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.platform.common.annotation.SysLog;
import com.platform.common.utils.PageUtils;
import com.platform.common.utils.R;
import com.platform.common.utils.RedisUtils;
import com.platform.modules.foreign.entity.CommentForeignEntity;
import com.platform.modules.foreign.entity.ReporterInterviewProcess;
import com.platform.modules.foreign.entity.SceneForeignEntity;
import com.platform.modules.foreign.service.LiveForeignService;
import com.platform.modules.live.service.LiveSceneService;
import com.platform.modules.live.service.LiveTaskAllocationService;

import net.sf.json.JSONObject;

/**
 * @author TROY
 * @version V1.0
 * @ClassName: LiveForeignController
 * @Description: 对外提供现场相关数据服务
 * @date 2019/2/20 16:35
 */
@RestController
@RequestMapping("/foreign/live")
public class LiveForeignController {

	@Autowired
	private LiveForeignService liveForeignService;
	@Autowired
	private LiveSceneService liveSceneService;
	@Autowired
	private RedisUtils redisUtils;
	@Autowired
	private LiveTaskAllocationService taskAllocationService;

	@GetMapping("/scene/list")
	@ResponseBody
	public R sceneList(Integer cid, Integer source, String title, Integer page, Integer size) {
		if (null == page || null == size){
			return R.error("缺少必要参数");
		}
		PageUtils pu = liveForeignService.getSceneList(cid, source, title, page, size);
		return R.ok().put("data", pu);
	}

	@GetMapping("/scene/get/{id}")
	@ResponseBody
	public R sceneInfo(@PathVariable("id") String id) {
		if (StringUtils.isBlank(id)) {
			return R.error("缺少必要参数");
		}

		// 20200317_Mxy 对地址中id做截取操作
		String subId;

		if (id.contains("&")){
			subId = StringUtils.substringBefore(id, "&");
		}else {
			subId = id;
		}

		if (StringUtils.isBlank(subId)){
			return R.error("参数错误");
		}

		SceneForeignEntity data;
		try {
			data = liveForeignService.getSceneDetail(Integer.valueOf(subId));
		} catch (NullPointerException e) {
			e.printStackTrace();
			return R.error("信息不存在");
		}
		return R.ok().put("data", data);
	}

	@GetMapping("/report/list")
	@ResponseBody
	public R reportList(Integer sceneId, Integer page, Integer size, Boolean reverse) {
		if (null == sceneId || null == page || null == size) {
			return R.error("缺少必要参数");
		}
		PageUtils pu = liveForeignService.getReportList(sceneId, page, size, reverse);
		return R.ok().put("data", pu);
	}

	@GetMapping("/comment/list")
	@ResponseBody
	public R commentList(Integer sceneId, Integer page, Integer size) {
		if (null == sceneId) {
			return R.error("缺少必要参数");
		}
		List<CommentForeignEntity> list = liveForeignService.getCommentList(sceneId, page, size);
		return R.ok().put("data", list);
	}

	@GetMapping("/caster/streamsUrl")
	@ResponseBody
	public R commentList(Integer sceneId) {
		if (null == sceneId) {
			return R.error("缺少必要参数");
		}
		return liveSceneService.getCasterStreamsUrl(sceneId);
	}

	@PostMapping("/comment/create")
	@ResponseBody
	public R commentCreate (Integer sceneId, String utoken, String text, HttpServletRequest request) {

	    Integer appCommentIpCount = 1;
	    String setKey = "app_comment_counts";
		String ip = request.getRemoteAddr();
		Object value = redisUtils.hget(setKey, ip);
		if(value == null) {
            redisUtils.hset(setKey, ip, appCommentIpCount, 60);
        } else {
            Integer appCommentIpCountAlready = Integer.valueOf(value.toString());
            if(appCommentIpCountAlready >= 5)
                return R.error("当前用户评论过多，请稍后重试");
            appCommentIpCount += appCommentIpCountAlready;
            redisUtils.hset(setKey, ip, appCommentIpCount);
        }
		if (null == sceneId) {
			return R.error("缺少必要参数");
		}
		try {
			liveForeignService.saveComment(sceneId, utoken, text);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
			return R.error("第三方用户token无效");
		} catch (NullPointerException e) {
			e.printStackTrace();
			return R.error("缺少必要参数");
		} catch (Exception e ) {
			e.printStackTrace();
			return R.error("系统内部错误");
		}
		return R.ok();
	}
	@GetMapping("/channel/list")
	@ResponseBody
	public R channeltList() {
		return R.ok().put("data", liveForeignService.channeltList());
	}

	@PostMapping("/user/position")
	@ResponseBody
	public R position(String username, Float lat, Float lgt) {
		if (StringUtils.isBlank(username) || null == lat||null == lgt) {
			return R.error("缺少必要参数");
		}
		if (!Arrays.asList("Web_trtc_01", "Web_trtc_02", "Web_trtc_03", "Web_trtc_04").contains(username)) {
			return R.error("用户不存在");
		}
		JSONObject jn = new JSONObject();
		DecimalFormat df = new DecimalFormat("#.000");
		jn.put("lat", df.format(lat));
		jn.put("lgt", df.format(lgt));
		String key = "foreign:user:postion";
		redisUtils.hset(key, username, jn.toString());
		return R.ok("位置已更新");
	}

	@GetMapping("/user/position")
	@ResponseBody
	public R getPosition(String username) {
		if (StringUtils.isBlank(username)) {
			return R.error("缺少必要参数");
		}
		if (!Arrays.asList("Web_trtc_01", "Web_trtc_02", "Web_trtc_03", "Web_trtc_04").contains(username)) {
			return R.error("用户不存在");
		}
		String key = "foreign:user:postion";
		if (!redisUtils.hexists(key, username)) {
			JSONObject jn = new JSONObject();
			jn.put("lat", "117.025");
			jn.put("lgt", "36.683");
			return R.ok("位置未更新").put("data", jn);
		}
		Object res = redisUtils.hget(key, username);
		return R.ok("位置已更新").put("data", JSONObject.fromObject(res));
	}

	@GetMapping("/user/position/list")
	@ResponseBody
	public R posList() {
		String key = "foreign:user:postion";
		Map<String, Object> users = redisUtils.hentries(key);
		if (null==users || users.size()==0) {
			return R.ok("暂无用户位置信息").put("data", new ArrayList());
		}
		return R.ok("success").put("data", JSONObject.fromObject(users));
	}

	@GetMapping("/reporter/list")
	public R reportersList() {

		List<ReporterInterviewProcess> reporterInterviewProcesses = liveForeignService.findAllReporters();

		return R.ok().put("data", reporterInterviewProcesses);
	}
	
	@SysLog("任务分配")
	@PostMapping("/task/allocation")
	public R taskAllocation(Integer[] reporterIds,Integer userId, MultipartFile mediaFile, Integer durationTime) {

		if(null == reporterIds || reporterIds.length == 0 || null == userId || null == mediaFile || null == durationTime){
			return R.error("必填参数不能为空");
		}
		taskAllocationService.taskAllocation(reporterIds, userId, mediaFile, durationTime);

		return R.ok("success");
	}
	
	@GetMapping("/weixin/getJsApiTicket")
	@ResponseBody
	public R getWeixinJsApiTicket (String url) {
		if(StringUtils.isBlank(url)){
			return R.error("必填参数不能为空");
		}
		try {
			url=URLDecoder.decode(url, "UTF-8").replace("&amp;", "&");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return R.error("验证信息获取失败");
		}
		JSONObject object = liveForeignService.getWeixinJsApiTicket(url);
		
		if(object==null || object.isEmpty()){
			return R.error("验证信息获取失败");
		}
		return R.ok("success").put("data", object);
	}
}
