package com.cku.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.cku.sms.ZtSmsUtil;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cku.core.ExecResultModel;
import com.cku.dao.CkuCaiPanMapper;
import com.cku.dao.CkuImageMapper;
import com.cku.dao.CkuMatchCostMapper;
import com.cku.dao.CkuMatchProjectMapper;
import com.cku.dao.EventRelatedMapper;
import com.cku.model.CkuCaiPan;
import com.cku.model.CkuMatchCost;
import com.cku.model.CkuMatchProject;
import com.cku.model.CkuMatchSponsor;
import com.cku.model.EventRelatedModel;
import com.sys.util.ImgUtil;

/**
 * 
 * <p>
 * Title:EventRelatedServiceImpl
 * </p>
 * <p>
 * Description: 赛事相关服务层
 * </p>
 * <p>
 * Company:
 * </p>
 * 
 * @author zhuoHeng
 * @date 2016年3月15日 下午6:04:56
 */
@Service("eventRelatedService")
public class EventRelatedServiceImpl {
	@Autowired
	public EventRelatedMapper eventRelatedMapper;

	@Autowired
	public CkuMatchProjectMapper ckuMatchProjectMapper;

	@Autowired
	public CkuCaiPanMapper ckuCaiPanMapper;

	@Autowired
	public CkuMatchCostMapper ckuMatchCostMapper;

	@Autowired
	public PublicService publicService;

	@Autowired
	public CkuImageMapper ckuImageMapper;

	private static Logger logger = LoggerFactory.getLogger(EventRelatedServiceImpl.class);


	/**
	 * 
	 * @Description：根据页码、展示条数获取主赛事列表
	 * @author: zhuoHeng
	 * @version: 2016年3月15日 下午6:07:51
	 */
	public String getEventList(Integer page, Integer limit) {

		ExecResultModel<EventRelatedModel> resultModel = new ExecResultModel<EventRelatedModel>();
		Integer pageNew = (page - 1) * limit;
		List<EventRelatedModel> eventList = eventRelatedMapper.getEventList(pageNew, limit);
		List<EventRelatedModel> countList = eventRelatedMapper.getEventCount();
		resultModel.setItems(eventList);
		if (eventList.size() > 0) {
			Date now = new Date();
			String showNum = "";
			// 对字符串截取，取出其中的城市名称
			for (int i = 0; i < eventList.size(); i++) {
				String[] strs = eventList.get(i).getShow_num().split("-");
				// 报名截止时间
				eventList.get(i).setClosingEntries(false);
				if (eventList.get(i).getShow_num() != null && eventList.get(i).getShow_num().length() > 7) {
					showNum = eventList.get(i).getShow_num().substring(0, 7);
				} else {
					showNum = eventList.get(i).getShow_num();
				}
//				@SuppressWarnings("unchecked")
//				Map<String, Integer> map = publicService.enrollStatus(showNum);
				// 犬只报名情况
//				Integer topDog = 0;
//				if (eventList.get(i) != null) {
//					topDog = new Integer(eventList.get(i).getTop_dog());
//				}
//				boolean enrollStatus = map.get("enrollNumber") >= topDog;
//				if (enrollStatus) {
//					System.out.println("达到报名上限");
//				}
//				eventList.get(i).setEnrollStatus(enrollStatus);
				eventList.get(i).setShow_num(strs.length > 1 ? strs[1] : "");
				//改为在主赛事地点中取数据
				if(StringUtils.isNotBlank(eventList.get(i).getShow_location())) {
					eventList.get(i).setShow_num(eventList.get(i).getShow_location().split("-")[0]);
				}
				// 赛事负责人 自办比赛是北京办公室负责人 合办是各个办公室负责人
				if("1".equals(eventList.get(i).getOrgnizeType())) {//0：合办旧模式；1：自办;2:合办新模式
					eventList.get(i).setDirector( eventRelatedMapper.getShowOfficeManager("1"));//id是1为北京办公室
				}else {
					if(StringUtils.isNotBlank( eventList.get(i).getOfficeId())) {
						eventList.get(i).setDirector( eventRelatedMapper.getShowOfficeManager( eventList.get(i).getOrganizer()));//id是1为北京办公室
					}
				}

			}
			resultModel.setRc(0);
			resultModel.setMsg("");
			resultModel.setTotal((long) countList.size());
		} else {
			resultModel.setRc(0);
			resultModel.setMsg("没有更多数据了");
			resultModel.setTotal((long) 0);
		}
		return resultModel.getToJson();
	}

	/**
	 * 
	 * @Description：根据主赛事场地查询子赛事列表
	 * @author: zhuoHeng
	 * @version: 2016年3月16日 上午11:00:42
	 */
	public String getSpecificEvent(String showLocation, String ids) {

		ExecResultModel<EventRelatedModel> resultModel = new ExecResultModel<EventRelatedModel>();
		if (!"".equals(ids) && ids != null) {
			String[] showsIds = ids.split(",");
			StringBuffer showId = new StringBuffer();
			for (int i = 0; i < showsIds.length; i++) {
				showId.append("'" + showsIds[i] + "',");
			}
			ids = showId.substring(0, showId.length() - 1);
		}
		List<EventRelatedModel> eventList = eventRelatedMapper.getSpecificEvent(showLocation, ids);
		if (eventList.size() > 0) {
			//修改showName返回的字符串中包含英文引号，前端解析错误，改成中文引号
			for (EventRelatedModel eventRelatedModel : eventList) {
				logger.info("--------------- : -------------");
				String showName = eventRelatedModel.getShow_name();
				if (StringUtils.isNotBlank(showName)) {
					if (showName.contains("\"")) {
						String showNameNew = showName.replaceAll("\"", "“");
						eventRelatedModel.setShow_name(showNameNew);
						logger.info("--------------- : 名字 {} -------------", showNameNew);
					} else if (showName.contains("&quot;")) {
						String showNameNew = showName.replaceAll("&quot;", "“");
						eventRelatedModel.setShow_name(showNameNew);
						logger.info("--------------- : 名字 {} -------------", showNameNew);
					}
				}
			}
			logger.info("--------------- : {} -------------", JSON.toJSONString(eventList));
			resultModel.setItems(eventList);
			resultModel.setRc(0);
			resultModel.setMsg("");
			resultModel.setTotal((long) eventList.size());
		} else {
			resultModel.setItems(new ArrayList<EventRelatedModel>());
			resultModel.setMsg("无对应数据");
			resultModel.setTotal((long) 0);
			;
		}

		return resultModel.getToJson();
	}

	/**
	 * 
	 * @Description：根据赛事id获取赛事主要项目
	 * @author: zhuoHeng
	 * @version: 2016年3月16日 上午11:31:34
	 */
	public String getEventProject(Integer id) {
		ExecResultModel<CkuMatchProject> resultModel = new ExecResultModel<CkuMatchProject>();
		List<CkuMatchProject> eventIntroduce = ckuMatchProjectMapper.getEventProject(id);
		if (eventIntroduce.size() > 0) {
			resultModel.setItems(eventIntroduce);
			resultModel.setRc(0);
			resultModel.setMsg("");
			resultModel.setTotal((long) eventIntroduce.size());
		} else {
			resultModel.setItems(new ArrayList<CkuMatchProject>());
			resultModel.setMsg("无对应数据");
			resultModel.setTotal((long) 0);
		}

		return resultModel.getToJson();
	}

	/**
	 * 
	 * @Description：根据赛事裁判id获取裁判信息
	 * @author: zhuoHeng
	 * @version: 2016年3月16日 下午1:13:03
	 */
	public String getRefereeMessage(String ids) {
		String flag = "";
		ExecResultModel<CkuCaiPan> resultModel = new ExecResultModel<CkuCaiPan>();
		if (ids == null || "".equals(ids)) {
			resultModel.setRc(0);
			resultModel.setItems(new ArrayList<CkuCaiPan>());
			resultModel.setMsg("");
			resultModel.setTotal((long) 0);
			return resultModel.getToJson();
		}
		StringBuffer sb = new StringBuffer();
		sb.append("'");
		sb.append(ids.replace(",", "','"));
		sb.append("'");
		List<CkuCaiPan> eventIntroduce = ckuCaiPanMapper.getRefereeMessage(sb.toString());
		if (eventIntroduce.size() > 0) {
			for (int i = 0; i < eventIntroduce.size(); i++) {
				flag = eventIntroduce.get(i).getCkuPosition();
				eventIntroduce.get(i).setCkuContent(null);
				// 注释掉裁判头衔
				/*
				 * if(flag!=null&&!"".equals(flag)){ if(flag.contains(";")){ String[] strs =
				 * eventIntroduce.get(i).getCkuPosition().split(";");
				 * //eventIntroduce.get(i).setCkuPosition(strs[0]); } }
				 */
				// 使用新字段进行裁判头衔进行展示
				eventIntroduce.get(i).setCkuPosition(eventIntroduce.get(i).getCabJobtitleShort());
				CkuCaiPan ckuCaiPan = eventIntroduce.get(i);
				ckuCaiPan.setCkuTitle(StringEscapeUtils.unescapeHtml(ckuCaiPan.getCkuTitle()));
				ckuCaiPan.setImageMinUrl(ImgUtil.getImgUrl(ckuCaiPan.getImageMinUrl()));
				ckuCaiPan.setImageMaxUrl(ImgUtil.getImgUrl(ckuCaiPan.getImageMaxUrl()));
			}
			resultModel.setItems(eventIntroduce);
			resultModel.setRc(0);
			resultModel.setMsg("");
			resultModel.setTotal((long) eventIntroduce.size());
		} else {
			resultModel.setItems(new ArrayList<CkuCaiPan>());
			resultModel.setMsg("无对应数据");
			resultModel.setTotal((long) 0);
		}
		return resultModel.getToJson();
	}

	/**
	 * 
	 * @Description：获取赛事费用详情
	 * @author: zhuoHeng
	 * @version: 2016年3月16日 下午3:47:49
	 */
	public String getMatchCost(Integer id) {
		ExecResultModel<CkuMatchCost> resultModel = new ExecResultModel<CkuMatchCost>();
		try {
			List<CkuMatchCost> eventIntroduce = ckuMatchCostMapper.getMatchCost(id);
			if (eventIntroduce.size() > 0) {
				resultModel.setItems(eventIntroduce);
				resultModel.setRc(0);
				resultModel.setMsg("");
				resultModel.setTotal((long) 200);
			} else {
				resultModel.setItems(new ArrayList<CkuMatchCost>());
				resultModel.setMsg("无对应数据");
				resultModel.setTotal((long) 0);
			}
		} catch (Exception e) {

		} finally {

		}

		return resultModel.getToJson();
	}

	/**
	 * 
	 * @Description：根据赛主事场地查询主赛事信息
	 * @author: zhuoHeng
	 * @version: 2016年3月19日 上午10:27:10
	 */
	public String getTrunkEventInfo(String showLocation) {
		ExecResultModel<EventRelatedModel> resultModel = new ExecResultModel<EventRelatedModel>();
		List<EventRelatedModel> eventList = eventRelatedMapper.getTrunkEventInfo(showLocation);
		resultModel.setItems(eventList);
		int size = eventList.size();
		if (size > 0) {
			// 截取赛事编号（查询主赛事犬只报名情况使用）
			String showNum = eventList.get(0).getShow_num().substring(0, 7);
			Map<String, Integer> map = publicService.enrollStatus(showNum);
			if (map.get("enrollNumber") > 180) {
				System.out.println("达到报名上限");
			}
			//
			Date now = new Date();
			// 报名截止时间
			Date date = eventList.get(0).getExpiry_time();
			boolean flag = now.before(date);
			// 当前时间在截止时间前，不禁止报名
			if (!flag) {
				System.out.println("已过报名截止日期");
			}
			// 对字符串截取，取出其中的城市名称
			for (int i = 0; i < eventList.size(); i++) {
				String[] strs = eventList.get(i).getShow_num().split("-");
				eventList.get(i).setShow_num(strs[1]);
			}
			resultModel.setRc(0);
			resultModel.setMsg("");
			resultModel.setTotal((long) eventList.size());
		} else {
			resultModel.setMsg("无对应数据");
		}
		return resultModel.getToJson();
	}

	/**
	 * 
	 * @Description：根据主办方获取主办方详细信息
	 * @author: zhuoHeng
	 * @version: 2016年3月22日 下午6:12:04
	 */
	public String getSponsorInfo(String organizer) {
		ExecResultModel<CkuMatchSponsor> resultModel = new ExecResultModel<CkuMatchSponsor>();
		try {
			List<CkuMatchSponsor> eventIntroduce = eventRelatedMapper.getSponsorInfo(organizer);
			if (eventIntroduce.size() > 0) {
				resultModel.setItems(eventIntroduce);
				resultModel.setRc(0);
				resultModel.setMsg("");
				resultModel.setTotal((long) 200);
			} else {
				resultModel.setItems(new ArrayList<CkuMatchSponsor>());
				resultModel.setMsg("无对应数据");
				resultModel.setTotal((long) 0);
			}
		} catch (Exception e) {

		} finally {

		}

		return resultModel.getToJson();
	}

	/**
	 * 根据赛事id修改为是否推荐
	 * 
	 * @param isTop
	 * @Author chaixueteng
	 * @2016年5月4日下午2:34:14
	 */
	public void updateMatchToTop(Integer id, Integer isTop) {
		// 根据id查出赛事的赛事地点 全部更改为推荐赛事
		String showLocation = eventRelatedMapper.getMatchByAdress(id);
		eventRelatedMapper.updateMatchToTop(showLocation, isTop);
	}

	/**
	 * 得到推荐赛事的列表
	 * 
	 * @Author chaixueteng
	 * @2016年5月4日下午3:57:30
	 */
	public String getTopMatch() {
		ExecResultModel<EventRelatedModel> resultModel = new ExecResultModel<EventRelatedModel>();
		List<EventRelatedModel> eventList = eventRelatedMapper.getTopMatch(0, 100);
		//app赛事banner列表，如果有大图为空则不返回
		eventList = eventList.stream().filter(a->!Objects.isNull(a.getCkuImageList())
				&& a.getCkuImageList().size()>0 && !Objects.isNull(a.getCkuImageList().get(0))
				&&  StringUtils.isNotBlank(a.getCkuImageList().get(0).getImageMaxUrl()))
				.collect(Collectors.toList());
		resultModel.setItems(eventList);
		if (eventList.size() > 0) {
			Date now = new Date();
			String showNum = "";
			// 对字符串截取，取出其中的城市名称
			for (int i = 0; i < eventList.size(); i++) {
				String[] strs = eventList.get(i).getShow_num().split("-");
				// 报名截止时间
				Date date = eventList.get(i).getExpiry_time();
				boolean flag = date.before(now);
				eventList.get(i).setClosingEntries(flag);
				// System.out.println("是否过了报名截止日期"+flag);
				showNum = eventList.get(i).getShow_num().substring(0, 7);
				Map<String, Integer> map = publicService.enrollStatus(showNum);
				// 犬只报名情况
				Integer topDog = 0;
				if (eventList.get(i) != null && !eventList.isEmpty()) {
					topDog = new Integer(eventList.get(i).getTop_dog());
				}
				boolean enrollStatus = map.get("enrollNumber") >= topDog;
				if (enrollStatus) {
					System.out.println("达到报名上限");
				}
				eventList.get(i).setEnrollStatus(enrollStatus);
				eventList.get(i).setShow_num(strs[1]);
				// 得到推荐的赛事的地点
				String id = eventList.get(i).getId();
				String imageUrl = eventRelatedMapper.getMatchImage(id);
				eventList.get(i).setTopMessage(imageUrl);
			}
			resultModel.setRc(0);
			resultModel.setMsg("");
			resultModel.setTotal(new Long(eventList.size()));
		} else {
			resultModel.setItems(new ArrayList<EventRelatedModel>());
			resultModel.setRc(0);
			resultModel.setMsg("没有更多数据了");
		}
		return resultModel.getToJson();
	}
}
