package com.bcxin.identify.business.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.bcxin.identify.business.dao.LYTrajectoryMapper;
import com.bcxin.identify.business.domain.LYTrajectory;
import com.bcxin.identify.business.domain.LYTrajectoryTerminal;
import com.bcxin.identify.business.domain.dto.MessageTargetDTO;
import com.bcxin.identify.util.HttpUtils;
import com.bcxin.identify.util.Result;
import com.bcxin.identify.util.codes.CommonConst;
import com.bcxin.identify.util.codes.TrajectoryConst;
import com.bcxin.identify.util.common.IdWorker;
import com.bcxin.identify.util.common.JwtUtil;
import com.bcxin.identify.util.common.StringUtil;
import com.bcxin.identify.util.lieying.LYResult;
import com.bcxin.identify.util.sys.ConfigUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;


@Service
@Transactional
@Slf4j
public class LYTrajectoryService {
	
	@Autowired
	private LYTrajectoryMapper lYTrajectoryMapper;

	public Result createKeyAndService(Map<String,String> params) {
		String key = params.get("key");
		String province = params.get("province");
		List<LYTrajectory> list = lYTrajectoryMapper.selectList(new EntityWrapper<LYTrajectory>().addFilter("tKey={0}", key));
		if(list.size()>15){
			return Result.fail("key的service生成已达到上限");
		}
		Integer seq = lYTrajectoryMapper.getMaxSeqByProvince(province);
		seq = seq==null?0:seq;
		Map map;
		String ret;
		LYResult lyR;
		LYTrajectory lYTrajectory;
		list = Lists.newArrayList();
		for(int i=0;i<15;i++){
			seq = seq+1;
			map = Maps.newHashMap();
			lYTrajectory = new LYTrajectory();
			map.put("key",key);
			map.put("name",province+key.substring(key.length()-10,key.length())+(i+1));
			ret = HttpUtil.post(TrajectoryConst.GATEWAY_URL + TrajectoryConst.ADD_SERVICE, map);
			System.out.println("ADD_SERVICE:"+ret);
			lyR = JSONObject.parseObject(ret, LYResult.class);
			if(lyR.getErrcode()==10000){
				Map m = JSONObject.parseObject(JSONObject.toJSONString(lyR.getData()), Map.class);
				lYTrajectory.setLyTrajectoryId(IdWorker.getId());
				lYTrajectory.setTKey(key);
				lYTrajectory.setProvince(province);
				lYTrajectory.setSeq(seq);
				lYTrajectory.setServiceId(String.valueOf(m.get("sid")));
				lYTrajectory.setName(String.valueOf(map.get("name")));
				list.add(lYTrajectory);
			}
		}
		if(list.size()>0){
			lYTrajectoryMapper.insertBatchTrajectory(list);
		}
		return Result.success(Result.SUCCESS_MSG);
	}

	/**
	 * <b> 根据省编码查询可用的key/sid </b>
	 * @author ZXF
	 * @create 2021/07/22 0022 15:18
	 * @version
	 * @注意事项 </b>
	 */
	public Result getKeyByProvince(Map<String,String> params) {
		String province = params.get("province");
		return Result.success(Result.SUCCESS_MSG,lYTrajectoryMapper.getKeyByProvince(province));
	}

	/**
	 * <b> 根据userId查询可用的key/sid </b>
	 * @author ZXF
	 * @create 2021/07/22 0022 15:18
	 * @version
	 * @注意事项 </b>
	 */
	public Result getTerminalByUserId(Map<String,String> params) {
		String userid = params.get("userid");
		return Result.success(Result.SUCCESS_MSG,lYTrajectoryMapper.getTerminalByUserId(userid));
	}

	/**
	 * <b> 根据sid、userid、tid新增设备关系记录 </b>
	 * @author ZXF
	 * @create 2021/07/22 0022 15:18
	 * @version
	 * @注意事项 </b>
	 */
	public Result createTerminal(Map<String,String> params) {
		String sid = params.get("sid");
		String userid = params.get("userid");
		String tid = params.get("tid");
		int count = lYTrajectoryMapper.terminalCount(userid, tid);
		if(count>0){
			return Result.fail("设备已存在");
		}
		List<LYTrajectory> list = lYTrajectoryMapper.selectList(new EntityWrapper<LYTrajectory>().addFilter("serviceId={0}", sid));
		if(list.size()==0){
			return Result.fail("sid无效");
		}
		LYTrajectoryTerminal terminal = new LYTrajectoryTerminal();
		terminal.setLyTrajectoryTerminalId(IdWorker.getId());
		terminal.setLyTrajectoryId(list.get(0).getLyTrajectoryId());
		terminal.setTid(tid);
		terminal.setUserid(userid);
		terminal.setCreateOn(new Date());
		lYTrajectoryMapper.insertTerminal(terminal);
		return Result.success("设备记录添加成功");
	}

	/**
	 * <b> 查询轨迹信息 </b>
	 * @author ZXF
	 * @create 2021/07/22 0022 15:18
	 * @version
	 * @注意事项 </b>
	 */
	public Result trackTrsearch(Map<String,String> params) {
		String key = params.get("key");
		String sid = params.get("sid");
		String tid = params.get("tid");
		String trid  = params.get("trid");
		String day = params.get("day");
		Long e = DateUtil.parse(day+" 23:59:59").getTime();
		Long n = (new Date()).getTime();
		if(e>n){
			e = n;
		}
		Map map = Maps.newHashMap();
		map.put("key",key);
		map.put("sid",sid);
		map.put("tid",tid);
		map.put("trid",trid);
		map.put("starttime", DateUtil.parse(day+" 00:00:00").getTime());
		map.put("endtime", e);
		String ret = HttpUtil.get(TrajectoryConst.GATEWAY_URL + TrajectoryConst.TRACK_TRSEARCH, map);
		LYResult lyR = JSONObject.parseObject(ret, LYResult.class);
		if("10000".equals(String.valueOf(lyR.getErrcode()))){
			return Result.success(Result.SUCCESS_MSG,lyR.getData());
		}
		return Result.fail(lyR.getErrmsg());
	}

	/**
	 * <b> 设备量预警 </b>
	 * @author ZXF
	 * @create 2021/07/22 0022 15:18
	 * @version
	 * @注意事项 </b>
	 */
	public void fullWarning() {
		List<String> list = lYTrajectoryMapper.groupProvince();
		for(String str : list){
			new Thread(() -> {
				warn(str);
			}).start();
		}

	}

	private void warn(String province){
		Integer count = lYTrajectoryMapper.findKeyIsFull(province);
		if(count==null){
			return;
		}
		String emails = ConfigUtil.getValue(CommonConst.TRAJ_EMAIL_WARN);
		if(StringUtil.isEmpty(emails)){
			return;
		}
		String[] arr = emails.split(",");
		List<MessageTargetDTO> dtoList = Lists.newArrayList();
		MessageTargetDTO dto;
		for (String email : arr) {
			dto = new MessageTargetDTO();
			dto.setEmail(email);
			dtoList.add(dto);
		}
		if (CollectionUtil.isEmpty(dtoList)) {
			return;
		}
		String web_url = ConfigUtil.getValue(CommonConst.WEB_URL);
		String TITLE = "猎鹰轨迹设备数即将达到上限！";
		String CONTENT = "您好！公共服务系统检测到猎鹰轨迹已创建设备数即将达到上限：\\n" +
				"区域代码：{province}\\n" +
				"剩余设备数：{count}\\n" +
				"请前往猎鹰轨迹平台（https://lbs.amap.com）创建新的应用获取到key组装到下面的扩容地址中！\\n" +
				"轨迹设备数扩容地址："+web_url+"/identify/api/trajectory/create-key-and-service?province={province}&key=" ;
		if(count<=100){//剩余<=100
			CONTENT = CONTENT.replace("{province}",province).replace("{count}",String.valueOf(count));
			lYTrajectoryMapper.updateFull(province);//省类下的所有记录都设置为满的状态
			callMSS(dtoList,TITLE,CONTENT);
		}else if(count<=500){//剩余<=500
			callMSS(dtoList,TITLE,CONTENT);
		}else if(count<=1000){//剩余<=1000
			callMSS(dtoList,TITLE,CONTENT);
		}else if(count<=3000){//剩余<=3000
			callMSS(dtoList,TITLE,CONTENT);
		}else if(count<=5000){//剩余<=5000
			callMSS(dtoList,TITLE,CONTENT);
		}
	}

	/**
	 * 对接MSS，消息系统
	 *
	 * @param dtoList
	 */
	private void callMSS(List<MessageTargetDTO> dtoList, String title, String content) {
		Map<String, Object> p = Maps.newHashMap();
		p.put("serialNumber", generateRamdomNumber());
		p.put("callPlat", CommonConst.PLATFORM);
		p.put("when", "0");
		p.put("to", JSON.toJSONString(dtoList));
		p.put("title", title);
		p.put("content", content);
		p.put("smsCode", "");
		p.put("smsParam", "");
		p.put("attachments", "");
		p.put("way", "2");
		p.put("plats", CommonConst.PLATFORM);
		p.put("callback", "");
		p.put("extra", "");

		String token = JwtUtil.createJWT(p);// 加密生成token

		Map<String, Object> requestMap = Maps.newHashMap();
		requestMap.put("token", token);
		String url = ConfigUtil.getValue(CommonConst.MSS_URL);
		HttpUtils.doPost(url, requestMap);
	}

	/**
	 * 生成随机流水号
	 *
	 * @return
	 */
	private synchronized String generateRamdomNumber() {
		return System.currentTimeMillis() + RandomUtil.randomNumbers(6);
	}
}
