package com.cirle.scientific.service.impl;

import com.cirle.scientific.dao.*;
import com.cirle.scientific.dto.QkjConferenceDTO;
import com.cirle.scientific.dto.QkjConferencePeopleDTO;
import com.cirle.scientific.po.*;
import com.cirle.scientific.pojo.Result;
import com.cirle.scientific.service.ArticleService;
import com.cirle.scientific.service.CommonService;
import com.cirle.scientific.service.MeetingService;
import com.cirle.scientific.service.RecommendService;
import com.cirle.scientific.utils.CopyUtil;
import com.cirle.scientific.utils.DateFormater;
import com.cirle.scientific.utils.OrderUtil;
import com.cirle.scientific.utils.StringUtil;
import com.cirle.scientific.utils.page.Page;
import com.cirle.scientific.utils.page.ResultPage;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.util.ListUtils;

import javax.validation.constraints.Null;
import java.util.*;
import java.util.stream.Collectors;

@Component
@Transactional
@Slf4j
public class MeetingServiceImpl implements MeetingService {

    @Autowired
    private QkjConferenceDao conferenceDao;

	@Autowired
	private QkjConferenceMenuDao conferenceMenuDao;

	@Autowired
	private QkjConferenceRecordDao conferenceRecordDao;

    @Autowired
	private CommonService commonService;

    @Autowired
	private RecommendService recommendService;

    @Autowired
	private QkjQuestionAnswerDao qkjQuestionAnswerDao;

	@Autowired
	private QkjQuestionDetailDao questionDetailDao;

    @Autowired
	private QkjConferencePeopelDao conferencePeopelDao;

    @Autowired
	private OrderDao orderDao;

	@Autowired
	private CollectionDao collectionDao;
	@Override
	public Result getListData(String memCard, Integer page, Integer size) {

		// 只有m端会调用，所以默认为true
		return getListData(memCard, page, size, true);
	}

	@Override
	public Result getListData(String memCard, Integer page, Integer size, boolean isPC) {
		Integer[] mOrPc= new Integer[2];
		if(isPC){ //手机
			mOrPc[0]=0;
			mOrPc[1]=2;
		}else{
			mOrPc[0]=1;
			mOrPc[1]=2;
		}
		List<QkjConferenceDTO> productList = getData(page, size, mOrPc);

		return Result.success(productList);
	}

	private List<QkjConferenceDTO> getData(Integer page, Integer size,Integer[] mOrPc) {
		List<QkjConference> conferenceList = conferenceDao.findList((page-1)*size, size,mOrPc);

		return conferenceList.stream().map(item ->{
			QkjConferenceDTO dto = CopyUtil.copy(item, QkjConferenceDTO.class);
			dto.setCoverImg(commonService.buildImgUrl(dto.getCoverImg()));
			dto.setTimeStr(item.getBigenTime()==null?"": DateFormater.formatDate(item.getBigenTime(),"yyyy年MM月dd日"));
			dto.setDetail("");
			dto.setPeopleCount(StringUtil.getTenThousandOfANumber(item.getPeopleCount()));
			if(item.getType() == 1){
				int peopleCount = 0;
				List<QkjConference> conferences = conferenceDao.findSonList(item.getId());
				for (QkjConference info : conferences){
					peopleCount+=info.getPeopleCount();
				}
				dto.setPeopleCount(StringUtil.getTenThousandOfANumber(peopleCount));
			}
			return dto;
		}).collect(Collectors.toList());
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
    public Result getDetailData(Long conferId, String memCard) {

		QkjConference conference = conferenceDao.findById(conferId).get();

		if(conference != null){
			QkjConferenceDTO dto = CopyUtil.copy(conference, QkjConferenceDTO.class);
			dto.setCoverImg(commonService.buildImgUrl(dto.getCoverImg()));
			if(conference.getType() == 1){
				//系列会议获取子会议
				List<QkjConference> conferenceList = conferenceDao.findSonList(conferId);
				List<QkjConferenceDTO> productList = conferenceList.stream().map(item ->{
					QkjConferenceDTO sonDto = CopyUtil.copy(item, QkjConferenceDTO.class);
					sonDto.setCoverImg(commonService.buildImgUrl(dto.getCoverImg()));
					sonDto.setTimeStr(DateFormater.formatDate(item.getBigenTime(),"yyyy年MM月dd日"));
					sonDto.setDetail("");
					return sonDto;
				}).collect(Collectors.toList());
				dto.setSonList(productList);
			}else{
				//普通会议获取菜单
				List<QkjConferenceMenu> menus = conferenceMenuDao.findByConferIdOrderBySqnAsc(conferId.intValue());
				for(QkjConferenceMenu menu : menus){
					menu.setMenuImg(commonService.buildImgUrl(menu.getMenuImg()));
				}
				dto.setMenus(menus);
			}

			// 获取会议详情页顶部广告位
			dto.setSysRecommendDTOs(recommendService.findByPostTypeAndObjId(4, conferId.intValue(), 1, 100));

			//判断会议是否已经订阅
			List<QkjConferenceRecord> records = conferenceRecordDao.findByConferIdAndMemCard(conferId, memCard, 1);
			if (!ListUtils.isEmpty(records)){
				dto.setIsSubscribe(1);
			}

			dto.setIsController(1);
			List<SalesCollectionMain> collectionMains = collectionDao.getCollectionInfo(memCard, conferId+"", 3);
			if(collectionMains!=null&&collectionMains.size()>0){//以收藏
				dto.setIsController(0);
			}

			return Result.success(dto);
		}else{
			log.info("找不到会议信息:conferId="+conferId);
			return Result.failed("找不到会议信息:conferId="+conferId);
		}
    }

	@Override
	public QkjConference getInfoById(Long conferId) {
		return conferenceDao.findById(conferId).get();
	}

	@Override
	public Result getPeopleList(Long conferId, String memCard) {

		List<QkjConferenceRecord> recordList = conferenceRecordDao.findByConferIdAndMemCard(conferId, memCard);

		List<QkjConferencePeopleDTO> isPayPeoples = new ArrayList<>();
		List<QkjConferencePeopleDTO> noPayPeoples = new ArrayList<>();
		QkjConferencePeopleDTO peopleAttributes = null;
		for(QkjConferenceRecord record : recordList){
			if(record.getPayStatus() == 1){
				isPayPeoples.add(makePeopleDto(record, conferId));
			}else{
				noPayPeoples.add(makePeopleDto(record, conferId));
			}
		}
		peopleAttributes = makePeopleDto(null, conferId);

		Map<String, Object> map = new HashMap<>();
		map.put("isPayPeoples", isPayPeoples);
		map.put("noPayPeoples", noPayPeoples);
		map.put("peopleAttributes", peopleAttributes);
		map.put("info", getDetailData(conferId, null).getData());
		return Result.success(map);
	}

	@Override
	public Result pursePeopleBm(String memCard, Long conferId, String peopleList) {
		try {
			ObjectMapper mapper = new ObjectMapper();
			JavaType javaType = mapper.getTypeFactory().constructParametricType(LinkedList.class, QkjConferencePeopleDTO.class);
			List<QkjConferencePeopleDTO> peoples = mapper.readValue(peopleList, javaType);
			List<String> isBmName = new ArrayList<>();
			for(QkjConferencePeopleDTO dto : peoples){
				QkjConferencePeopel peopel = conferencePeopelDao.findByMobile(dto.getMobile());
				if(peopel != null){
					QkjConferenceRecord record = conferenceRecordDao.findByConferIdAndMobile(conferId, peopel.getMobile());
					if(record != null){
						isBmName.add(peopel.getMobile());
					}
				}
			}
			Map<String, String> resMap = new HashMap<>();
			if(isBmName.size() > 0){
				resMap.put("code", "1");
				resMap.put("errorMsg", String.join(",",isBmName)+"已报名");
				Result.success(resMap);
			}else{
				resMap.put("code", "0");
				resMap.put("errorMsg", "验证成功，可以报名");
			}
			return Result.success(resMap);

		}catch (Exception e){
			e.printStackTrace();
			return Result.failed("数据解析失败！");
		}
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
	public Result peopleBm(String memCard, Long conferId, String peopleList, String ip) {
		try {
			ObjectMapper mapper = new ObjectMapper();
			JavaType javaType = mapper.getTypeFactory().constructParametricType(LinkedList.class, QkjConferencePeopleDTO.class);
			List<QkjConferencePeopleDTO> peoples = mapper.readValue(peopleList, javaType);
			List<String> isBmName = new ArrayList<>();

			//删除所有未支付订单相关数据
			List<QkjConferenceRecord> records = conferenceRecordDao.findByConferIdAndMemCard(conferId, memCard, 0);
			for(QkjConferenceRecord record : records){
				//删除对应的扩展字段
				qkjQuestionAnswerDao.deleteByMemberAndObjTypeAndOjbIdAndRecordId(memCard, 2, conferId.intValue(),record.getId().intValue());

				//删除订单
				SalesOrdersMain ordersMain = orderDao.getOrderInfo(record.getOrderId());
				if(ordersMain != null && ordersMain.getStatus() != 1){
					ordersMain.setStatus(2);
					orderDao.save(ordersMain);
				}

				//删除报名记录
				record.setStatus(1);
				conferenceRecordDao.save(record);
			}

			//获取会议信息
			QkjConference conference = conferenceDao.findById(conferId).get();

			//生成订单号
			String orderId = OrderUtil.getInstance().GenerateOrder();

			for(QkjConferencePeopleDTO dto : peoples){
				//添加或修改参会人信息
				QkjConferencePeopel peopel = conferencePeopelDao.findByMobile(dto.getMobile());
				if (peopel == null) {
					peopel = new QkjConferencePeopel();
				}
				peopel.setName(dto.getName());
				peopel.setMobile(dto.getMobile());
				peopel = conferencePeopelDao.save(peopel);

				//添加报名记录
				QkjConferenceRecord record = new QkjConferenceRecord();
				record.setMemCard(memCard);
				record.setOrderId(orderId);
				record.setConferId(conferId.intValue());
				record.setPeopleId(peopel.getId().intValue());
				record.setPayStatus(0);
				record.setStatus(0);
				record.setCreateTime(Calendar.getInstance());
				record = conferenceRecordDao.save(record);

				//添加参会人扩展字段信息
				for(QkjQuestionAnswer qa : dto.getQuestionAnswers()){
					qa.setMemCard(memCard);
					qa.setObjType(2);
					qa.setObjId(conferId.intValue());
					qa.setRecordId(record.getId().intValue());
					qkjQuestionAnswerDao.save(qa);
				}
			}
			return Result.success(orderId);
		}catch (Exception e){
			e.printStackTrace();
			return Result.failed("数据解析失败！");
		}
	}

	@Override
	public ResultPage getPageData(String memCard, Integer page, Integer size,boolean isPC) {
		Integer[] mOrPc= new Integer[2];//电脑
		if(isPC){ //手机
			mOrPc[0]=0;
			mOrPc[1]=2;
		}else{
			mOrPc[0]=1;
			mOrPc[1]=2;
		}
		Integer totalCount = conferenceDao.findTotalList(mOrPc);

		List<QkjConferenceDTO> data = getData(page, size,mOrPc);

		//传入当前页、一页显示条数及总条数，获取分页所需要的起始结束值
		Page<Object> pageBean = new Page<Object>(page, size, totalCount);


		return new ResultPage(data, true,"200", pageBean.getTotalCount(), pageBean.getTotalPage(), pageBean.getPageSize(), pageBean.getCurrentPage());
	}

	@Override
	public Result getQuestionList(Long conferId, String memCard) {

			QkjConferencePeopleDTO peopleAttributes =  makePeopleDto(null, conferId);
			Map<String, Object> map = new HashMap<>();
			map.put("peopleAttributes", peopleAttributes);
			map.put("info", getDetailData(conferId, null).getData());
			return Result.success(map);

	}


	private QkjConferencePeopleDTO makePeopleDto(QkjConferenceRecord record, Long conferId){
		QkjConferencePeopleDTO dto = new QkjConferencePeopleDTO();
		if(record != null){
			QkjConferencePeopel peopel = conferencePeopelDao.findById(record.getPeopleId().longValue()).get();
			dto.setName(peopel.getName());
			dto.setMobile(peopel.getMobile());
			List<QkjQuestionAnswer> questionAnswers = qkjQuestionAnswerDao.findConferPeopleAttribute(record.getMemCard(),record.getConferId(),record.getId().intValue());
			dto.setQuestionAnswers(questionAnswers);
		}else{
			List<QkjQuestionDetail> questionDetails = questionDetailDao.findByObjTypeAndObjId(2,conferId.intValue());
			List<QkjQuestionAnswer> questionAnswers = new ArrayList<>();
			for(QkjQuestionDetail detail : questionDetails){
				QkjQuestionAnswer qa = new QkjQuestionAnswer();
				qa.setObjType(detail.getObjType());
				qa.setObjId(detail.getObjId());
				qa.setQuId(detail.getQuId());
				qa.setQuTitle(detail.getQuTitle());
				qa.setQuType(detail.getQuType());
				questionAnswers.add(qa);
			}
			dto.setQuestionAnswers(questionAnswers);
		}
		return dto;
	}
}
