package com.yunzhi.marketing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunzhi.marketing.base.ResponseBean;
import com.yunzhi.marketing.center.taUser.mapper.TaUserMapper;
import com.yunzhi.marketing.common.CommConstant;
import com.yunzhi.marketing.common.StringUtils;
import com.yunzhi.marketing.drainage.entity.TaDrainage;
import com.yunzhi.marketing.drainage.mapper.TaDrainageMapper;
import com.yunzhi.marketing.mapper.HelpActivityMapper;
import com.yunzhi.marketing.mapper.TaBuildingDynamicMapper;
import com.yunzhi.marketing.mapper.TaNewsMapper;
import com.yunzhi.marketing.mapper.TaPersonMapper;
import com.yunzhi.marketing.mapper.TaPersonVisitRecordMapper;
import com.yunzhi.marketing.mapper.TaRecommendCustomerMapper;
import com.yunzhi.marketing.mapper.TaShareActivityMapper;
import com.yunzhi.marketing.entity.*;
import com.yunzhi.marketing.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * <p>
 *   服务实现类
 * </p>
 *
 * @author jobob
 * @since 2019-07-23
 */
@Service
public class TaPersonVisitRecordServiceImpl extends ServiceImpl<TaPersonVisitRecordMapper, TaPersonVisitRecord> implements ITaPersonVisitRecordService {
	
	@Autowired
	private TaRecommendCustomerMapper taRecommendCustomerMapper;
	
	@Autowired
	private TaPersonVisitRecordMapper personVisitRecordMapper;
	
	@Autowired
	private TaBuildingDynamicMapper taBuildingDynamicMapper;
	
	@Autowired
	private TaShareActivityMapper taShareActivityMapper;
	
	@Autowired
	private HelpActivityMapper helpActivityMapper;
	
	@Autowired
	private TaNewsMapper taNewsMapper;

	@Autowired
	private TaUserMapper taUserMapper;

	@Autowired
	private TaPersonMapper taPersonMapper;

	@Autowired
	private TaDrainageMapper taDrainageMapper;

	@Autowired
	private ITaEventPropertiesService taEventPropertiesService;

	@Autowired
	private ITaBuildingIntentionService buildingIntentionService;

	@Autowired
	private ITaBuildingService buildingService;

	@Autowired
	private ITaPersonIntentionRecordService personIntentionRecordService;

	@Autowired
	private ITaPersonFromRecordService iTaPersonFromRecordService;

	/**
	 * 分页获取客户访问记录
	 *
	 * @param pg
	 * @param customerId
	 * @return
	 */
	@Override
	public IPage<TaPersonVisitRecord> getPersonVisitRecordList(IPage<TaPersonVisitRecord> pg, String customerId) {
		TaRecommendCustomer taRecommendCustomer = taRecommendCustomerMapper.selectById(customerId);
		IPage<TaPersonVisitRecord> result = personVisitRecordMapper.getPersonVisitRecordList(pg,taRecommendCustomer.getPersonId());
		List<TaPersonVisitRecord> records = result.getRecords();
		records.forEach(e -> {
			//获取活动标题
			if ("activity".equals(e.getEventType()) && null != e.getTargetId()){
				TaBuildingDynamic taBuildingDynamic = taBuildingDynamicMapper.selectById(e.getTargetId());
				if (null != taBuildingDynamic){
					e.setActivityName(taBuildingDynamic.getTitle());
				}
				
			}
			//获取拼团标题
			if ("group".equals(e.getEventType()) && null != e.getTargetId()){
				TaShareActivity taShareActivity = taShareActivityMapper.selectById(e.getTargetId());
				if (null != taShareActivity){
					e.setActivityName(taShareActivity.getActivityName());
				}
			}
			//获取助力标题
			if ("help".equals(e.getEventType()) && null != e.getTargetId()){
				HelpActivity helpActivity = helpActivityMapper.selectById(e.getTargetId());
				if (null != helpActivity){
					e.setActivityName(helpActivity.getTitle());
				}
			}
			//获取咨询标题
			if ("news".equals(e.getEventType()) && null != e.getTargetId()){
				TaNews taNews = taNewsMapper.selectById(e.getTargetId());
				if (null != taNews){
					e.setActivityName(taNews.getNewsName());
				}
			}
			//获取H5活动标题
			if ("h5".equals(e.getEventType()) && null != e.getTargetId()){
				TaDrainage taDrainage = taDrainageMapper.selectById(e.getTargetId());
				if (null != taDrainage){
					e.setActivityName(taDrainage.getName());
				}
			}
		});
		result.setRecords(records);
		return result;
	}

	@Override
	public IPage<TaPersonVisitRecord> getDrainageVisitRecord(IPage<TaPersonVisitRecord> pg, Integer orgId, String activityName, String eventType, String shareName, String shareTel, String buildingId, String personType, List<TaPersonBuilding> taPersonBuildingList) {
		IPage<TaPersonVisitRecord> taPersonVisitRecordIPage = personVisitRecordMapper.getDrainageVisitRecord(pg, orgId, activityName, eventType, shareName, shareTel, buildingId, personType, taPersonBuildingList);
		List<TaPersonVisitRecord> taPersonVisitRecords = taPersonVisitRecordIPage.getRecords();
		for (TaPersonVisitRecord e : taPersonVisitRecords) {

			TaPerson personInfo = taPersonMapper.selectById(e.getPersonId());
			if (personInfo != null) {
				e.setUserName(personInfo.getNickname());
				e.setUserTel(personInfo.getPhone());
			}

			QueryWrapper<TaPerson> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("person_id", e.getSharePersonId());
			TaPerson userShareInfo = taPersonMapper.selectOne(queryWrapper);

			QueryWrapper<TaPerson> taPersonQueryWrapper = new QueryWrapper<>();
			taPersonQueryWrapper.eq("user_id", e.getSharePersonId());
			TaPerson taPersonUser = taPersonMapper.selectOne(taPersonQueryWrapper);

			e.setShareName((userShareInfo == null &&  taPersonUser == null) ? null : userShareInfo == null ? taPersonUser.getNickname() : userShareInfo.getNickname());
			e.setShareTel((userShareInfo == null &&  taPersonUser == null) ? null : userShareInfo == null ? taPersonUser.getPhone(): userShareInfo.getPhone());

			if (CommConstant.H5_SHARE.equals(e.getEventType())) {
				e.setActivityName(e.getDrainageName());
				continue;
			}
			if (CommConstant.BUILDING_SHARE.equals(e.getEventType())) {
				e.setActivityName(e.getBuildingName());
				continue;
			}
			if (CommConstant.NEWS_SHARE.equals(e.getEventType())) {
				e.setActivityName(e.getNewsName());
				continue;
			}
			if (CommConstant.HELP_SHARE.equals(e.getEventType())) {
				e.setActivityName(e.getHelpActivityName());
				continue;
			}
			if (CommConstant.GROUP_SHARE.equals(e.getEventType())) {
				e.setActivityName(e.getGroupActivityName());
				continue;
			}
		}
		taPersonVisitRecordIPage.setRecords(taPersonVisitRecords);
		return taPersonVisitRecordIPage;
	}

	@Override
	public IPage<TaConsultantInfo> getConsultantShareInfoList(IPage<TaConsultantInfo> pg, String personId) {
		IPage<TaConsultantInfo> result = personVisitRecordMapper.getConsultantShareInfoList(pg,personId);
		return result;
	}

	@Override
	public Integer countShareNumByEventType(Integer orgId, String targetId, Integer userId, String personId, String eventType) {
		return personVisitRecordMapper.countShareNumByEventType(orgId, targetId, userId, personId, eventType);
	}

	@Override
	public ResponseBean newRecord(TaPersonVisitRecord taPersonVisitRecord, TaPerson person) {
		Integer orgId = person.getOrgId();

		Integer eventProperties = taEventPropertiesService.isEventExist(taPersonVisitRecord.getTargetId(), taPersonVisitRecord.getEventType(), taPersonVisitRecord.getActivity(), orgId);
		if (eventProperties <= 0) {
			TaEventProperties taEventProperty = new TaEventProperties();
			taEventProperty.setBuildingId(taPersonVisitRecord.getTargetId());
			taEventProperty.setCreateDate(LocalDateTime.now());
			taEventProperty.setPropertyCode(taPersonVisitRecord.getPropertyName());
			taEventProperty.setPropertyName(taPersonVisitRecord.getPropertyName());
			taEventProperty.setStatus(CommConstant.STATUS_NORMAL);
			taEventProperty.setBuildingId(taPersonVisitRecord.getBuildingId());
			taEventProperty.setEventType(taPersonVisitRecord.getEventType());
			taEventProperty.setOrgId(orgId);
			if (!taEventPropertiesService.save(taEventProperty)) {
				return ResponseBean.error("新增失败", ResponseBean.ERROR_UNAVAILABLE);
			}
		}

		taPersonVisitRecord.setVisitTime(LocalDateTime.now());
		if (!StringUtils.isEmpty(taPersonVisitRecord.getBuildingId())) {
			QueryWrapper<TaBuildingIntention> intentionQueryWrapper = new QueryWrapper<>();
			intentionQueryWrapper.eq("building_id", taPersonVisitRecord.getBuildingId());
			intentionQueryWrapper.eq("org_id", taPersonVisitRecord.getOrgId());
			intentionQueryWrapper.eq("event_code", taPersonVisitRecord.getEvent());
			List<TaBuildingIntention> list = buildingIntentionService.list(intentionQueryWrapper);
			if (list.size() > 0) {
				TaBuildingIntention buildingIntention = list.get(0);
				TaPersonIntentionRecord intentionRecord = new TaPersonIntentionRecord();
				TaBuilding building = buildingService.getById(buildingIntention.getBuildingId());
				intentionRecord.setBuildingId(buildingIntention.getBuildingId());
				intentionRecord.setBuildingName(building.getBuildingName());
				intentionRecord.setCreateDate(LocalDateTime.now());
				intentionRecord.setEventCode(buildingIntention.getEventCode());
				intentionRecord.setEventId(buildingIntention.getEventId());
				intentionRecord.setEventName(buildingIntention.getEventName());
				intentionRecord.setIntention(buildingIntention.getIntention());
				intentionRecord.setOrgId(orgId);
				intentionRecord.setPersonId(person.getPersonId());
				intentionRecord.setPersonName(person.getNickname());
				intentionRecord.setStatus(CommConstant.STATUS_NORMAL);
				if (!personIntentionRecordService.save(intentionRecord)) {
					return ResponseBean.error("新增失败", ResponseBean.ERROR_UNAVAILABLE);
				}
			}
		}
		try {
			if (this.save(taPersonVisitRecord)) {
				//清洗埋點數據到新增用戶表--只有进入小程序的时候 start才记录
				if (taPersonVisitRecord.getEvent().equals(CommConstant.BIZ_EVENT_START)) {
					iTaPersonFromRecordService.addNewPersonRecordRecord(taPersonVisitRecord);
				}

				return ResponseBean.success(taPersonVisitRecord);
			} else {
				return ResponseBean.error("保存失败", ResponseBean.ERROR_UNAVAILABLE);
			}
		} catch (Exception e) {
//			logger.error("taPersonVisitRecordAdd -=- {}", e.toString());
			return ResponseBean.error("系统异常" + e.getMessage(), ResponseBean.ERROR_UNAVAILABLE);
		}
	}

	/**
	 * 分页获取个人中心访客记录
	 *
	 * @param pg
	 * @param userId
	 * @param orgId
	 * @return
	 */
	@Override
	public IPage<TaPersonVisitRecord> getWxVisitRecordList(IPage<TaPersonVisitRecord> pg, Integer userId, Integer orgId) {
		//根据userId获取用户信息
		QueryWrapper<TaPerson> taPersonQueryWrapper = new QueryWrapper<>();
		taPersonQueryWrapper.eq("user_id",userId);
		taPersonQueryWrapper.eq("org_id",orgId);
		TaPerson taPerson = taPersonMapper.selectOne(taPersonQueryWrapper);
		//获取我的访问客户列表
		IPage<TaPersonVisitRecord> result = personVisitRecordMapper.getWxVisitRecordList(pg,userId,orgId, CommConstant.EVENT_H5,taPerson.getPersonId());
		List<TaPersonVisitRecord> records = result.getRecords();
		//判断是否我的客户状态
		records.forEach(e -> {
			QueryWrapper<TaRecommendCustomer> queryWrapper = new QueryWrapper();
			queryWrapper.eq("realty_consultant",e.getConsultantId());
			queryWrapper.eq("person_id",e.getPersonId());
			List<TaRecommendCustomer> taRecommendCustomer = taRecommendCustomerMapper.selectList(queryWrapper);
			if (taRecommendCustomer.size() > 0){
				//1是我的客户
				e.setMyCustomer(CommConstant.STATUS_NORMAL);
			}
		});
		return result;
	}


	/**
	 * 分页获取个人中心访客记录
	 *
	 * @param pg
	 * @param userId
	 * @param orgId
	 * @return
	 */
	@Override
	public IPage<TaPersonVisitRecord> getWxActivityVisitRecordList(IPage<TaPersonVisitRecord> pg, String personId, Integer orgId, String targetId, String eventType) {
		//根据userId获取用户信息
		QueryWrapper<TaPerson> taPersonQueryWrapper = new QueryWrapper<>();
		taPersonQueryWrapper.eq("person_id",personId);
		taPersonQueryWrapper.eq("org_id",orgId);
		TaPerson taPerson = taPersonMapper.selectOne(taPersonQueryWrapper);
		//获取我的访问客户列表
		IPage<TaPersonVisitRecord> result = personVisitRecordMapper.getWxActivityVisitRecordList(pg, taPerson.getUserId(), orgId, targetId, personId, (CommConstant.FAVOR_PROJECT.equals(eventType) ? "building" : CommConstant.FAVOR_ACTIVITY.equals(eventType) ? "dynamic" : eventType)  + "_share");
		List<TaPersonVisitRecord> records = result.getRecords();
		//判断是否我的客户状态
		records.forEach(e -> {
			QueryWrapper<TaRecommendCustomer> queryWrapper = new QueryWrapper();
			queryWrapper.eq("realty_consultant",e.getConsultantId());
			queryWrapper.eq("person_id",e.getPersonId());
			List<TaRecommendCustomer> taRecommendCustomers = taRecommendCustomerMapper.selectList(queryWrapper);
			if (taRecommendCustomers.size() > 0){
				//1是我的客户
				e.setMyCustomer(CommConstant.STATUS_NORMAL);
				//返回customer_id给微信端
				e.setCustomerId(taRecommendCustomers.get(0).getCustomerId());
			}
		});
		return result;
	}

	/**
	 * 获取这个人的活动数据列表
	 *
	 * @param userId
	 * @param personId
	 * @param orgId
	 * @return
	 */
	@Override
	public IPage<TaPersonVisitRecord> getWxVisitRecordActivityList(IPage<TaPersonVisitRecord> pg,Integer userId, String personId, Integer orgId) {
		return personVisitRecordMapper.getWxVisitRecordActivityList(pg,userId,personId,orgId,CommConstant.EVENT_H5);
	}

//    @Autowired
//    private TaPersonMapper taPersonMapper;
//    @Autowired
//    private TaPersonVisitRecordMapper taPersonVisitRecordMapper;
//
//    @Override
//    public IPage<TaPerson> selectCustomer(IPage<TaPerson> page){
//        return taPersonMapper.selectCustomer(page);
//    }
//
//    @Override
//    public TaPerson customerInfo(String personId,String consultentId){
//        TaPerson taPerson = taPersonMapper.selectById(personId);
//        taPerson.setVisitRecords(taPersonVisitRecordMapper.visitRecordByPersonId(personId));
//        return taPerson;
//    }



}
