package com.huiju.estateagents.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huiju.estateagents.base.ResponseBean;
import com.huiju.estateagents.common.CommConstant;
import com.huiju.estateagents.common.StringUtils;
import com.huiju.estateagents.entity.HelpActivity;
import com.huiju.estateagents.entity.HelpInitiateRecord;
import com.huiju.estateagents.entity.HelpRecord;
import com.huiju.estateagents.entity.TaPerson;
import com.huiju.estateagents.mapper.HelpActivityMapper;
import com.huiju.estateagents.mapper.HelpInitiateRecordMapper;
import com.huiju.estateagents.mapper.HelpRecordMapper;
import com.huiju.estateagents.mapper.TaPersonMapper;
import com.huiju.estateagents.service.IHelpRecordService;
import com.huiju.estateagents.service.IMiniAppService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 助力活动助力人员记录  服务实现类
 * </p>
 *
 * @author jobob
 * @since 2019-10-17
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class HelpRecordServiceImpl extends ServiceImpl<HelpRecordMapper, HelpRecord> implements IHelpRecordService {
	
	@Autowired
	private HelpActivityMapper helpActivityMapper;
	
	@Autowired
	private HelpInitiateRecordMapper helpInitiateRecordMapper;
	
	@Autowired
	private HelpRecordMapper helpRecordMapper;
	
	@Autowired
	private TaPersonMapper taPersonMapper;
	
	@Autowired
	private IMiniAppService miniAppService;
	
	/**
	 * 助力者助力
	 *
	 * @param helpRecord
	 * @param orgId
	 * @param person
	 * @return
	 */
	@Override
	public synchronized ResponseBean saveBooster(HelpRecord helpRecord, Integer orgId, TaPerson person) {
		//查看是否助力成功
		HelpInitiateRecord helpInitiateRecord = helpInitiateRecordMapper.selectById(helpRecord.getHelpRecordInitiateId());
		if (!StringUtils.isEmpty(helpInitiateRecord.getVerification())){
			return ResponseBean.error("该活动已成功", ResponseBean.ERROR_UNAVAILABLE);
		}

		HelpActivity helpActivity = helpActivityMapper.selectById(helpRecord.getHelpActivityId());
		//是否助力成功
		if (null != helpInitiateRecord.getEnlistNum() && helpInitiateRecord.getEnlistNum() >= helpActivity.getPersonNum()){
			return ResponseBean.error("该活动已成功", ResponseBean.ERROR_UNAVAILABLE);
		}
		if (helpActivity.getEndDate().isBefore(LocalDateTime.now())){
			return ResponseBean.error("活动已超时", ResponseBean.ERROR_UNAVAILABLE);
		}
		if(helpActivity.getActivityStatus().equals(CommConstant.ACTIVITY_STATUS_FINISH)){
			return ResponseBean.error("活动已结束", ResponseBean.ERROR_UNAVAILABLE);
		}
		if(helpActivity.getStatus().equals(CommConstant.STATUS_UNACCALIMED)){
			return ResponseBean.error("活动已失效", ResponseBean.ERROR_UNAVAILABLE);
		}
		
		//查看每个人的助力次数
		Integer helpNum = helpActivity.getHelpNum();
		
		QueryWrapper<HelpRecord> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("org_id",orgId);
		queryWrapper.eq("help_activity_id",helpRecord.getHelpActivityId());
		queryWrapper.eq("person_id",person.getPersonId());
		if (null != helpNum && helpNum > 0){
			//查看这个人是否助力过，和助力了几次
			List<HelpRecord> helpRecords = helpRecordMapper.selectList(queryWrapper);
			if (helpRecords.size() >= helpNum){
				return ResponseBean.error("助力次数达到上限", ResponseBean.ERROR_UNAVAILABLE);
			}
		}
		//查看是否助力过这个人
		queryWrapper.eq("help_record_initiate_id",helpRecord.getHelpRecordInitiateId());
		List<HelpRecord> helpRecordList = helpRecordMapper.selectList(queryWrapper);
		if (helpRecordList.size() > 0){
			return ResponseBean.error("您已经助力过了,无需重复助力", ResponseBean.ERROR_UNAVAILABLE);
		}
		//反更新在入库
		if (null == helpActivity.getEnlistNum()){
			helpActivity.setEnlistNum(0);
		}
		helpActivity.setEnlistNum(helpActivity.getEnlistNum()+1);
		helpActivityMapper.updateById(helpActivity);
		//插入数据
		helpRecord.setOrgId(orgId);
		helpRecord.setCreateDate(LocalDateTime.now());
		helpRecord.setPersonId(person.getPersonId());
		helpRecordMapper.insert(helpRecord);
		if (null == helpInitiateRecord.getEnlistNum()){
			helpInitiateRecord.setEnlistNum(0);
		}
		helpInitiateRecord.setEnlistNum(helpInitiateRecord.getEnlistNum()+1);
		if (helpInitiateRecord.getEnlistNum().equals(helpActivity.getPersonNum())){
			//发送微信模板消息所有人都发送
			try{
				sendWxMessage(helpInitiateRecord,orgId,helpActivity);
			}catch (Exception e){}
			
			//生成核销码
			helpInitiateRecord.setVerification(String.valueOf(helpInitiateRecord.getHelpRecordInitiateId()+System.currentTimeMillis()));
			helpInitiateRecord.setSucceedDate(LocalDateTime.now());
			helpInitiateRecord.setStatus(0);
		}
		
		helpInitiateRecordMapper.updateById(helpInitiateRecord);
		Map<String,Object> map = new HashMap<>();
		map.put("helpRecord",helpRecord);
		map.put("helpInitiateRecord",helpInitiateRecord);
		return ResponseBean.success(map);
	}

	/**
	 * 发送微信消息
	 * @param helpInitiateRecord
	 * @param orgId
	 * @param helpActivity
	 */
	private void sendWxMessage(HelpInitiateRecord helpInitiateRecord, Integer orgId, HelpActivity helpActivity) {
		String link = "/pages/activity/detail/assistance?id="+helpInitiateRecord.getHelpActivityId()+"&initiateId="+helpInitiateRecord.getHelpRecordInitiateId();
		//发送给发起者
		TaPerson taPerson = taPersonMapper.selectById(helpInitiateRecord.getPersonId());
		if (null != taPerson){
			miniAppService.sendHelpMessage(taPerson,link,"助力成功",helpActivity.getTitle(),LocalDateTime.now());
		}
		
		//批量发送给助力者
		QueryWrapper<HelpRecord> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("org_id",orgId);
		queryWrapper.eq("help_activity_id",helpInitiateRecord.getHelpActivityId());
		queryWrapper.eq("help_record_initiate_id",helpInitiateRecord.getHelpRecordInitiateId());
		List<HelpRecord> helpRecords = helpRecordMapper.selectList(queryWrapper);
		helpRecords.forEach(e -> {
			TaPerson toTaPerson = taPersonMapper.selectById(e.getPersonId());
			if (null != taPerson){
				miniAppService.sendHelpMessage(toTaPerson,link,"助力成功",helpActivity.getTitle(),LocalDateTime.now());
			}
		});
	}
	
}
