package com.ssj.service.conch.common.service.impl;

import com.alibaba.fastjson.JSON;
import com.ssj.bean.conch.conch.domain.ConchDerver;
import com.ssj.bean.sys.fx.domain.Merchant;
import com.ssj.bean.sys.give.GiveRecord;
import com.ssj.bean.weixin.libmy.domain.LibVip;
import com.ssj.bean.weixin.sales.domain.LibVipService;
import com.ssj.bean.weixin.user.domain.User;
import com.ssj.conch.push.util.PushConstants;
import com.ssj.framework.basic.utils.DateHelper;
import com.ssj.framework.core.security.manager.TokenManager;
import com.ssj.framework.core.util.PasswordUtil;
import com.ssj.framework.core.util.ResponseEntity;
import com.ssj.framework.core.util.StringUtil;
import com.ssj.framework.idworker.IdWorker;
import com.ssj.framework.weixin.util.DateUtil;
import com.ssj.service.conch.common.service.ConchCommonService;
import com.ssj.service.conch.conch.service.ConchDerverService;
import com.ssj.service.sys.easemob.service.EasemobService;
import com.ssj.service.sys.fx.service.DeviceService;
import com.ssj.service.sys.give.GiveRecordService;
import com.ssj.service.sys.push.service.SconXingeService;
import com.ssj.service.weixin.library.service.ILibVipService;
import com.ssj.service.weixin.sales.service.LibVipServiceService;
import com.ssj.service.weixin.user.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.HashMap;
import java.util.Map;

@Service
@Transactional
public class ConchCommonServiceImpl implements ConchCommonService{
	
	protected Logger	logger   = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
    private TokenManager tokenManager;
	@Autowired
	private ILibVipService vipService;
	@Autowired
	private UserService userService;
	@Autowired
	private LibVipServiceService  libVipServiceService;
	@Autowired
	private ConchDerverService conchDerverService;
	 @Autowired
	private SconXingeService sconXingeService;
	@Autowired
	private EasemobService easemobService;



	@Autowired
	private GiveRecordService giveRecordService;

	@Autowired
	private DeviceService deviceService;



	/**
	 * 此方法暂时注释，赠送改为用兑换码兑换
	 * @param vipId
	 */
	@Override
	public void giveBindConchZybService(String vipId) {
		//绑定赠送作业吧服务2个月
		/*String sendZybFlag = PropertiesUtil.getValue("sendZybFlag");
		if ("1".equals(sendZybFlag)) {
			//赠送记录
			GiveRecord record = giveRecordService.findByVipId(vipId);
			if (record == null) {
				record = new GiveRecord();
				record.setVipId(vipId);
				record.setQuantity(2);
				record.setSpecies("S003");
				record.setType("C004");
				record.setCreateTime(new Date());
				giveRecordService.save(record);
				libVipServiceService.saveLibVipServiceV2("S003", "C004", vipId, new Date(), 2, "zyb");
			}
		}*/
	}

	@Override
	public void giveBindConchZybServiceV1(String vipId, int days) {
		//赠送记录
		GiveRecord record = giveRecordService.findByVipId(vipId);
		if (record == null) {
			record = new GiveRecord();
			record.setVipId(vipId);
			record.setQuantity(days);
			record.setSpecies("S003");
			record.setType("C022");
			record.setCreateTime(new Date());
			giveRecordService.save(record);
			libVipServiceService.saveLibVipServiceV4("S003", "C022", vipId, new Date(), null, days, record.getId());
		}
	}

	@Override
	public void giveBindConchZybServiceV2(String vipId, int days, int useType) {
		Date beginTime = new Date();
		switch (useType) {
			case 1:
				this.removeGiveService(vipId);
				break;
			case 2:
				this.removeGiveService(vipId);
				//试用小塾，每个孩子只送一次服务
				GiveRecord record = giveRecordService.findByVipId(vipId);
				if (record == null) {
					record = new GiveRecord();
					record.setVipId(vipId);
					record.setQuantity(days);
					record.setSpecies("S003");
					record.setType("C022");
					record.setCreateTime(new Date());
					giveRecordService.save(record);
					libVipServiceService.saveLibVipServiceV4("S003", "C022", vipId, new Date(), null, days, record.getId());
				}
				break;
			case 3:
				//永久小塾，赠送100年服务
				LibVipService libVipService = libVipServiceService.findTopByVipIdAndSpeciesOrderByEndTimeDesc(vipId, "S003");
				if (libVipService != null) {
					String endTimeString = "2119-01-01";
					String endTimeCompare = DateUtil.format_yyyyMMdd(libVipService.getEndTime());
					//服务只赠送一次
					if (endTimeString.compareTo(endTimeCompare) < 0) {
						return;
					}
					if (DateHelper.compareTwoDate(beginTime, libVipService.getEndTime())) {
						beginTime = libVipService.getEndTime();
					}
				}
				//结束时间
				Date endTime = DateHelper.getYearDate(beginTime, 100);
				if (libVipService == null) {
					libVipService = new LibVipService();
					libVipService.setSpecies("S003");
					libVipService.setType("C006");
					libVipService.setStartTime(new Date());
					libVipService.setVipId(vipId);
					libVipService.setCreateTime(new Date());
				}
				libVipService.setEndTime(endTime);
				libVipService.setStat(1);
				libVipService.setIsJia(0);
				libVipService.setOrderDetailsId("zyb");
				libVipServiceService.save(libVipService);
				break;
			default:
				break;
		}
	}

	@Override
	public void giveBindConchZybServiceV3(String vipId, ConchDerver conchDerver) {
		int useType = conchDerver.getUseType();
		Date now = new Date();
		switch (useType) {
			case 2:
				//试用小塾，每个孩子只送一次服务,赠送半个月
				//试用服务改为赠送1个月 --修订于2019-11-8 by Mount
				GiveRecord record = giveRecordService.findByVipId(vipId);
				if (record == null) {
					//作业批改服务（作业吧服务）
					String species = "S003";
					//月卡
					String type = "C004";
					//数量
					int number = 1;
					record = new GiveRecord();
					record.setVipId(vipId);
					record.setSpecies(species);
					record.setType(type);
					record.setQuantity(number);
					record.setGiveWay(1);
					record.setCreateTime(now);
					giveRecordService.save(record);
					libVipServiceService.saveLibVipServiceV4("S003", "C022", vipId, now, null, number, record.getId());

				}
				break;
			case 3:
				if(conchDerver.getIsGiveInvalid() == 0){
					//记录赠送记录
					GiveRecord newRecord = new GiveRecord();
					newRecord.setVipId(vipId);
					newRecord.setQuantity(2);
					newRecord.setSpecies("S003");
					newRecord.setType("C004");
					newRecord.setGiveWay(2);
					newRecord.setCreateTime(now);
					giveRecordService.save(newRecord);
					//阶段服务版⼩塾（绑定则赠送2个月服务，只会送一次，类似于优惠券）
					libVipServiceService.saveLibVipServiceV4("S003", "C004", vipId, now, null, 2, newRecord.getId());
					logger.info("小塾" + conchDerver.getDerver() + "变为正常的小塾");
					//使用完,记录已赠送过服务
					conchDerver.setIsGiveInvalid(1);
					conchDerverService.save(conchDerver);

				}
				break;
			default:
				break;
		}
	}

	@Override
	public ResponseEntity bindDerver(String vipId, String longitude, String latitude, String derver) {
		return this.bindDerver(vipId, longitude, latitude, derver, null);
	}
	@Override
	public ResponseEntity bindDerver(String vipId, String longitude, String latitude, String derver, String userId) {
		ResponseEntity responseEntity = new ResponseEntity();
		ConchDerver conchDerver = conchDerverService.findByDerver(derver);
		if (conchDerver != null) {
			//此小塾为试用的
			/*if (conchDerver.getUseType() == 2 && StringUtil.isNotBlank(userId)) {
				if (this.conchTryServiceOperate(responseEntity, userId, derver, conchDerver.getUseDays())) {
					return responseEntity;
				}
			}*/

			/*//试用小塾给对应的设置的试用服务时长（新业务）
			if (conchDerver.getUseType() == 2) {
				this.giveBindConchZybServiceV1(vipId, conchDerver.getUseDays());
			} else if (conchDerver.getUseType() == 3) {
				//永久的小塾，每绑定一次送10年
				//libVipServiceService.saveLibVipServiceV2("S003", "C004", vipId, new Date(), 120, "zyb");
			}*/
			//给对应服务
			//this.giveBindConchZybServiceV2(vipId, conchDerver.getUseDays(), conchDerver.getUseType());
			String derVipId = conchDerver.getVipId();
			if (StringUtils.isNotBlank(derVipId)) {
				if (derVipId.equals(vipId)) {
					responseEntity.failure("您已绑定过小塾相机,无需再绑定");
					return responseEntity;
				} else {
					responseEntity.failure("小塾相机已被其他用户绑定");
					return responseEntity;
				}
			} else {
				LibVip libVip = vipService.getById(vipId);
				libVip.setActivateTime(new Date());
				libVip.setDerver(derver);

				//推送贝壳消息，创建用户
				String derUserId = libVip.getChildUserId();
				if (StringUtils.isBlank(derUserId)) {
					User childUserInfo = new User();
					childUserInfo.setId(IdWorker.generateId());
					childUserInfo.setEasemobName(userService.createUniqueEasemobName());
					//创建小孩环信账号
					easemobService.createUserSingle(childUserInfo.getEasemobName(), null);
					User parentUserInfo = userService.getById(libVip.getUserId());
					//添加家长和小孩的好友关系
					easemobService.addFriendSingle(parentUserInfo.getEasemobName(), childUserInfo.getEasemobName());

					childUserInfo.setPassword("123456");
					//需要创建小塾的账号密码
					childUserInfo.setPwdSalt(PasswordUtil.generateSalt());
					childUserInfo.setPassword(PasswordUtil.initPassword(childUserInfo.getPassword(), childUserInfo.getPwdSalt()));
					childUserInfo.setCreateTime(new Date());
					userService.save(childUserInfo);
					libVip.setChildUserId(childUserInfo.getId());
				} else {
					User childUserInfo = userService.getById(derUserId);
					if (StringUtils.isBlank(childUserInfo.getEasemobName())) {
						childUserInfo.setEasemobName(userService.createUniqueEasemobName());
						userService.save(childUserInfo);
						//创建小孩环信账号
						easemobService.createUserSingle(childUserInfo.getEasemobName(), null);
						User parentUserInfo = userService.getById(libVip.getUserId());
						//添加家长和小孩的好友关系
						easemobService.addFriendSingle(parentUserInfo.getEasemobName(), childUserInfo.getEasemobName());
					}
				}
				//存入redis ,小程序扫描公众号会推送消息,公众号直接返回 不提示

				//tokenManager.setString("sharingschool" + derver, "1", 5);

				conchDerver.setUserId(libVip.getChildUserId());
				conchDerver.setVipId(vipId);
				conchDerver.setUpdatedDate(new Date());
				logger.info("恭喜您绑定小塾相机成功");

				int isService = conchDerver.getIsService();
				if (isService == 0) {

					conchDerver.setIsService(1);
					//无作业吧服务，或作业吧服务已过期，赠送作业吧服务2个月
					giveBindConchZybService(libVip.getId());
				}

				//是否串区
				Merchant merchant=deviceService.checkIsRage(conchDerver.getImei(),conchDerver.getLongitude(),conchDerver.getLatitude(),longitude,latitude);
				if(StringUtil.isBlank(libVip.getPosCode())&&merchant!=null){
					libVip.setPosCode(merchant.getPosCode());
				}

				vipService.save(libVip);
				conchDerverService.save(conchDerver);
				tokenManager.set("DERVER_"+derver, conchDerver,1);

				//推送绑定成功消息给小塾
				Map<String,Object> map = new HashMap<String,Object>();
				map.put("type", "BIND");
				map.put("time", new Date());
				map.put("data", "{}");
				String content = JSON.toJSONString(map);
				//信鸽推送
				sconXingeService.asynPushThreadTask(derver,null,1,content, PushConstants.PUSH_OTHER);

				this.giveBindConchZybServiceV3(vipId, conchDerver);
				responseEntity.success("小塾相机绑定成功");
				return responseEntity;
			}
		} else {
			responseEntity.failure("小塾相机不存在");
			return responseEntity;
		}
	}

	/**
	 * 移除已经赠送过的永久服务
	 * @param vipId
	 */
	private void removeGiveService(String vipId) {
		String endTimeString = "2119-01-01";
		LibVipService libVipService = libVipServiceService.findTopByVipIdAndSpeciesOrderByEndTimeDesc(vipId, "S003");
		if (libVipService != null) {
			Date endTime = libVipService.getEndTime();
			String endTimeCompare = DateUtil.format_yyyyMMdd(endTime);
			//证明有赠送过服务，需要移除
			if (endTimeString.compareTo(endTimeCompare) < 0) {
				//向前推100年
				endTime = DateHelper.getYearDate(endTime, -100);
				libVipService.setEndTime(endTime);
				libVipServiceService.save(libVipService);
			}
		}
	}
}
