package com.ifish.serviceImpl;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.ifish.apiVersion.ApiVersion;
import com.ifish.dao.CameraDao;
import com.ifish.dao.CameraUserDao;
import com.ifish.dao.DeviceCameraDao;
import com.ifish.dao.DeviceDao;
import com.ifish.dao.DeviceUserDao;
import com.ifish.dao.GoldControlDao;
import com.ifish.dao.GoldGetRecordDao;
import com.ifish.dao.InformationDao;
import com.ifish.dao.PushListDao;
import com.ifish.dao.ShopsInfoDao;
import com.ifish.dao.UserAssetDao;
import com.ifish.dao.UserDao;
import com.ifish.dto.DeviceDto;
import com.ifish.dto.DeviceInfoDto;
import com.ifish.dto.GoldTaskDto;
import com.ifish.dto.GwellParamDto;
import com.ifish.dto.JsonResult;
import com.ifish.dto.NeteaseParamDto;
import com.ifish.dto.UserAssetDto;
import com.ifish.dto.UserInfoDto;
import com.ifish.dto.VenderDto;
import com.ifish.entity.Camera;
import com.ifish.entity.CameraUser;
import com.ifish.entity.Device;
import com.ifish.entity.DeviceCamera;
import com.ifish.entity.DeviceCameraId;
import com.ifish.entity.DeviceUser;
import com.ifish.entity.DeviceUserId;
import com.ifish.entity.GoldControl;
import com.ifish.entity.GoldGetRecord;
import com.ifish.entity.GoldTask;
import com.ifish.entity.GradeTask;
import com.ifish.entity.HardwareType;
import com.ifish.entity.PushList;
import com.ifish.entity.ShopsInfo;
import com.ifish.entity.User;
import com.ifish.entity.UserAsset;
import com.ifish.entity.VenderList;
import com.ifish.enums.AddTypeEnum;
import com.ifish.enums.BooleanEnum;
import com.ifish.enums.GoldGetTypeEnum;
import com.ifish.enums.GradeGetTypeEnum;
import com.ifish.enums.GwellEnum;
import com.ifish.enums.NeteaseEnum;
import com.ifish.enums.PushTypeEnum;
import com.ifish.enums.ResultEnum;
import com.ifish.enums.SendTypeEnum;
import com.ifish.enums.SmsSignEnum;
import com.ifish.enums.SmsTemplateEnum;
import com.ifish.enums.SubDirectoryEnum;
import com.ifish.enums.UserTypeEnum;
import com.ifish.exception.IfishException;
import com.ifish.gwell.GwellApi;
import com.ifish.jpush.SmsNumSend;
import com.ifish.netease.NeteaseIM;
import com.ifish.service.CacheService;
import com.ifish.service.GoldService;
import com.ifish.service.GradeService;
import com.ifish.service.UserService;
import com.ifish.util.IfishFilePath;
import com.ifish.util.IfishUtil;
import com.ifish.validator.LoginParam;
import com.ifish.validator.RegisterParam;

/** 
 * @ClassName: UserServiceImpl 
 * @Description: TODO 
 * @author ggw
 *  
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

	@Autowired
	private UserDao userDao;
	@Autowired
	private DeviceDao deviceDao;
	@Autowired
	private CameraDao cameraDao;
	@Autowired
	private NeteaseIM neteaseIM;
	@Autowired
	private SmsNumSend smsNumSend;
	@Autowired
	private PushListDao pushListDao;
	@Autowired
	private ShopsInfoDao shopsInfoDao;
	@Autowired
	private UserAssetDao userAssetDao;
	@Autowired
	private DeviceUserDao deviceUserDao;
	@Autowired
	private CameraUserDao cameraUserDao;
	@Autowired
	private GoldControlDao goldControlDao;
	@Autowired
	private InformationDao informationDao;
	@Autowired
	private DeviceCameraDao deviceCameraDao;
	@Autowired
	private GoldGetRecordDao goldGetRecordDao;
	@Autowired
	private GoldService goldService;
	@Autowired
	private CacheService cacheService;
	@Autowired
	private GradeService gradeService;

	@Override
	public JsonResult<?> getVerificateCode(String phoneNumber, String sendType) {
		//验证参数
		if(StringUtils.isNotBlank(phoneNumber) && StringUtils.isNotBlank(sendType)){
			User user = userDao.findUniqueByProperty(Restrictions.eq("phoneNumber",phoneNumber));
			//已注册
			if(user!=null){
				//找回密码操作
				if(sendType.equals(SendTypeEnum.findpwd.getKey())){
					//发送短信
					return sendMessage(phoneNumber,SmsSignEnum.sign5.getValue(),SmsTemplateEnum.SMS_720021.getKey());
				}
				//注册操作
				else if(sendType.equals(SendTypeEnum.register.getKey())){
					//手机注册过，发送错误码
					return new JsonResult<String>(ResultEnum.warn201.getKey());
				}
			}
			//未注册
			else{
				//注册操作
				if(sendType.equals(SendTypeEnum.register.getKey())){
					//发送短信
					return sendMessage(phoneNumber,SmsSignEnum.sign4.getValue(),SmsTemplateEnum.SMS_720018.getKey());
				}
			}
		}
		return new JsonResult<String>(ResultEnum.fail101.getKey());
	}

	@Override
	public JsonResult<?> login(LoginParam loginParam) {
		//手机号
		String phoneNumber = loginParam.getPhoneNumber();
		//用户是否存在
		User user = userDao.findUniqueByProperty(Restrictions.eq("phoneNumber",phoneNumber));
		if(user!=null){
			//密码是否正确
			if(user.getUserPassword().equals(loginParam.getUserPassword())){
				//技威参数
				GwellParamDto gwellParam = getGwellInfo(user.getIsRegisterGwell(), phoneNumber);
				if(gwellParam!=null){
					user.setIsRegisterGwell(gwellParam.getIsRegisterGwell());
					user.setP2PVerifyCode1(gwellParam.getP2PVerifyCode1());
					user.setP2PVerifyCode2(gwellParam.getP2PVerifyCode2());
					user.setGwellUserID(gwellParam.getUserID());
				}
				//云信参数
				Integer userId = user.getUserId();
				NeteaseParamDto neteaseParam = GetNeteaseInfo(user.getIsRegisterNetease(), userId, user.getNickName(), user.getUserImg(), user.getNeteaseToken());
				if(neteaseParam!=null){
					user.setIsRegisterNetease(neteaseParam.getIsRegisterNetease());
					user.setNeteaseToken(neteaseParam.getNeteaseToken());
				}
				/**
				 * 更新登陆参数
				 */
				userDao.executeLoginUpdate(userId,loginParam.getLoginType());
				//设备信息
				DeviceInfoDto deviceInfo = getDeviceInfo(userId);
				/**
				 * 登录返回信息
				 */
				JSONObject jsonObject = new JSONObject();
				//用户信息
				jsonObject.put("user", getUserInfo(user));
				//版本号
				if(ApiVersion.version1_0.equals(loginParam.getVersion())){
					//用户资产
					jsonObject.put("userAsset", getUserAssetInfo(userId));
					//金币任务
					jsonObject.put("goldTasks", getGoldTaskList(userId));
				}
				//资讯信息
				jsonObject.put("information", cacheService.getInformation());
				//设备信息
				jsonObject.put("device", deviceInfo.getDeviceList());
				//摄像头信息
				jsonObject.put("camera", getCameraInfo(userId));
				//设备关联摄像头信息
				jsonObject.put("deviceCamera", getDeviceCamera(deviceInfo.getDeviceIds()));
				//商家信息(自己是商家)
				jsonObject.put("shopsInfo", getShopsInfo(userId,user.getUserImg()));
				//看护商家信息
				jsonObject.put("shopsInfo2", getShopsInfo(user.getShopsUserId(),null));
				return new JsonResult<JSONObject>(ResultEnum.success.getKey(), jsonObject);
			}
			else{
				//密码不正确
				return new JsonResult<String>(ResultEnum.warn204.getKey());
			}
		}
		else{
			//用户不存在
			return new JsonResult<String>(ResultEnum.warn202.getKey());
		}
	}
	
	/**
	 * 优化后登陆验证
	 */
	@Override
	public JsonResult<?> loginValidate(LoginParam loginParam){
		//手机号
		String phoneNumber = loginParam.getPhoneNumber();
		//用户信息
		User user = userDao.findUniqueByProperty(Restrictions.eq("phoneNumber",phoneNumber));
		//用户不存在
		if(user==null){
			throw new IfishException(ResultEnum.warn202);
		}
		//密码不正确
		if(!loginParam.getUserPassword().equals(user.getUserPassword())){
			throw new IfishException(ResultEnum.warn204);
		}
		//技威参数
		GwellParamDto gwellParam = getGwellInfo(user.getIsRegisterGwell(), phoneNumber);
		if(gwellParam!=null){
			user.setIsRegisterGwell(gwellParam.getIsRegisterGwell());
			user.setP2PVerifyCode1(gwellParam.getP2PVerifyCode1());
			user.setP2PVerifyCode2(gwellParam.getP2PVerifyCode2());
			user.setGwellUserID(gwellParam.getUserID());
		}
		//云信参数
		Integer userId = user.getUserId();
		NeteaseParamDto neteaseParam = GetNeteaseInfo(user.getIsRegisterNetease(), userId, user.getNickName(), user.getUserImg(), user.getNeteaseToken());
		if(neteaseParam!=null){
			user.setIsRegisterNetease(neteaseParam.getIsRegisterNetease());
			user.setNeteaseToken(neteaseParam.getNeteaseToken());
		}
		//更新登陆参数
		userDao.executeLoginUpdate(userId,loginParam.getLoginType());
		//用户基本信息
		UserInfoDto userInfoDto = getUserInfoDto(user);
		//用户资产信息
		UserAssetDto userAssetDto = getUserAssetInfo(userId);
		//返回json信息
		JSONObject json = new JSONObject();
		json.put("userInfo", userInfoDto);
		json.put("userAsset", userAssetDto);
		return new JsonResult<JSONObject>(ResultEnum.success.getKey(), json);
	}
	/**
	 * 更多用户数据信息
	 */
	@Override
	public JsonResult<?> moreUserData(Integer userId){
		User user = userDao.get(userId);
		//用户不存在
		if(user==null){
			throw new IfishException(ResultEnum.warn202);
		}
		/**
		 * 登录返回信息
		 */
		JSONObject jsonObject = new JSONObject();
		//设备信息
		DeviceInfoDto deviceInfo = getSimpleDeviceInfo(userId);
		//金币任务
		jsonObject.put("goldTasks", getGoldTaskList(userId));
		//资讯信息
		List<JSONObject> information = cacheService.getInformation();
		JSONObject infoJson = new JSONObject();
		if(information.size()>0){
			JSONObject json = information.get(0);
			Integer infoId = json.getInteger("infoId");
			String title = json.getString("title");
			//资讯只返回id和title
			infoJson.put("infoId", infoId);
			infoJson.put("title", title);
			jsonObject.put("information", infoJson);
		}
		else{
			jsonObject.put("information", infoJson);
		}
		//设备信息
		jsonObject.put("device",deviceInfo.getDeviceList());
		//摄像头信息
		jsonObject.put("camera", getCameraInfo(userId));
		//设备关联摄像头信息
		jsonObject.put("deviceCamera", getDeviceCamera(deviceInfo.getDeviceIds()));
		//商家信息(自己是商家)
		jsonObject.put("shopsInfo", getShopsInfo(userId,user.getUserImg()));
		//看护商家信息
		jsonObject.put("shopsInfo2", getShopsInfo(user.getShopsUserId(),null));
		return new JsonResult<JSONObject>(ResultEnum.success.getKey(), jsonObject);
	}
	
	/**
	 * 绑定设备
	 */
	@Override
	public JsonResult<?> bindDevice(Integer userId,String macAddress){
		//设备信息
		Device device = deviceDao.findUniqueByProperty(Restrictions.eq("macAddress", macAddress));
		if(device==null){
			throw new IfishException(ResultEnum.error402);
		}
		//用户信息
		User user = userDao.get(userId);
		if(user==null){
			throw new IfishException(ResultEnum.error402);
		}
		//首次激活
		if(device.getFirstActivate()==null){
			device.setFirstActivate(new Date());
		}
		//设备ID
		Integer deviceId = device.getDeviceId();
		//是否已关联设备
		DeviceUserId priId = new DeviceUserId(userId, deviceId);
		DeviceUser deviceUser = deviceUserDao.get(priId);
		if(deviceUser==null){
			//已关联设备的其他用户
			List<DeviceUser> deviceUserList = deviceUserDao.findByProperty(Restrictions.eq("priId.deviceId", deviceId));
			//解除关联关系并发送推送
			deleteDeviceAndPushMsg(deviceUserList, deviceId);
			//关联设备
			deviceUser = new DeviceUser(priId, BooleanEnum.YES.getKey(), "鱼缸"+(int)(Math.random()*9000+1000));
			deviceUserDao.save(deviceUser);
		}
		else{
			//不是主控制权
			if(!BooleanEnum.YES.getKey().equals(deviceUser.getIsMaster())){
				//已关联设备的其他用户
				List<DeviceUser> deviceUserList = deviceUserDao.findByProperty(Restrictions.eq("priId.deviceId", deviceId),Restrictions.ne("priId.userId", userId));
				//解除关联关系并发送推送
				deleteDeviceAndPushMsg(deviceUserList, deviceId);
				//设为主控并更新时间
				deviceUser.setIsMaster(BooleanEnum.YES.getKey());
				deviceUser.setUpdateTime(new Date());
			}
		}
		return new JsonResult<DeviceDto>(ResultEnum.success.getKey(), getDeviceDto(deviceUser, device));
	}
	
	/**
	 * 扫一扫分享设备
	 */
	@Override
	public JsonResult<?> shareDevice(Integer userId,Integer deviceId){
		//设备信息
		Device device = deviceDao.get(deviceId);
		if(device==null){
			throw new IfishException(ResultEnum.error402);
		}
		//用户信息
		User user = userDao.get(userId);
		if(user==null){
			throw new IfishException(ResultEnum.error402);
		}
		//是否已关联设备
		DeviceUserId priId = new DeviceUserId(userId, deviceId);
		DeviceUser deviceUser = deviceUserDao.get(priId);
		if(deviceUser==null){
			//关联设备
			deviceUser = new DeviceUser(priId, BooleanEnum.NO.getKey(), "鱼缸"+(int)(Math.random()*9000+1000));
			deviceUserDao.save(deviceUser);
		}
		return new JsonResult<DeviceDto>(ResultEnum.success.getKey(), getDeviceDto(deviceUser, device));
	}
	
	@Override
	public JsonResult<?> register(RegisterParam registerParam) {
		String phoneNumber = registerParam.getPhoneNumber();
		User user = userDao.findUniqueByProperty(Restrictions.eq("phoneNumber", phoneNumber));
		if(user!=null){
			return new JsonResult<String>(ResultEnum.warn201.getKey());
		}
		else{
			user = new User();
			user.setPhoneNumber(phoneNumber);
			user.setUserPassword(registerParam.getUserPassword());
			user.setPhoneType(registerParam.getPhoneType());
			user.setLoginType(registerParam.getPhoneType());
			user.setIsRegisterGwell(BooleanEnum.NO.getKey());
			user.setIsRegisterNetease(BooleanEnum.NO.getKey());
			user.setNeteaseToken("");
			user.setUserType(UserTypeEnum.userType0.getKey());
			user.setAddress(registerParam.getAddress());
			user.setLongitude(registerParam.getLongitude());
			user.setLatitude(registerParam.getLatitude());
			//随机给一个默认头像
			String userImg = "default/"+(new Random().nextInt(7)+1)+".png";
			user.setUserImg(userImg);
			//随机生成用户名
			String nickName = "鱼友"+IfishUtil.getCharAndNumr(5);
			user.setNickName(nickName);
			user.setCreateTime(new Date());
			userDao.save(user);
			//首次注册赠送10金币
			BigDecimal gold = new BigDecimal(10);
			UserAsset userAsset = new UserAsset(user.getUserId(),gold);
			userAssetDao.save(userAsset);
			//获取记录
			GoldGetRecord getRecord = new GoldGetRecord(user.getUserId(), GoldGetTypeEnum.registerGive.getKey(), gold, GoldGetTypeEnum.registerGive.getValue());
			goldGetRecordDao.save(getRecord);
			return new JsonResult<String>(ResultEnum.success.getKey());
		}
	}
	
	@Override
	public JsonResult<?> updateInfo(User user){
		//用户ID
		Integer userId = user.getUserId();
		if(userId!=null){
			//查找用户信息
			User curUser = userDao.get(userId);
			if(curUser!=null){
				//是否需要更新
				boolean bln = false;
				//昵称
				String nickName = user.getNickName();
				if(StringUtils.isNotBlank(nickName)){
					//敏感词过滤
					if(nickName.contains("爱鱼奇") || nickName.contains("官方")){
						return new JsonResult<String>(ResultEnum.warn213.getKey());
					}
					else{
						curUser.setNickName(nickName);
						bln=true;
					}
				}
				//性别
				String userSex = user.getUserSex();
				if(StringUtils.isNotBlank(userSex)){
					curUser.setUserSex(userSex);
					bln=true;
				}
				//签名
				String signature = user.getSignature();
				if(StringUtils.isNotBlank(signature)){
					curUser.setSignature(signature);
					bln=true;
				}
				//有参数变更
				if(bln){
					//更新用户信息
					curUser.setUpdateTime(new Date());
					userDao.update(curUser);
					//更新云信
					updateIMUserInfo(userId.toString(), curUser.getNickName(), curUser.getUserImg());
				}
				return new JsonResult<String>(ResultEnum.success.getKey());
			}
			else{
				return new JsonResult<String>(ResultEnum.warn211.getKey());
			}
		}
		else{
			return new JsonResult<String>(ResultEnum.fail101.getKey());
		}
	}
	
	@Override
	public JsonResult<?> uploadUserImg(Integer userId,MultipartFile fileUpload){
		//查找用户信息
		User user = userDao.get(userId);
		if(user!=null){
			if(fileUpload!=null && !fileUpload.isEmpty()){
				//上传的图片不能大于1M
				if(fileUpload.getSize()>1048576){
					return new JsonResult<String>(ResultEnum.warn206.getKey());
				}
				else{
					//验证图片格式
					String extEndName = IfishFilePath.checkImgName(fileUpload.getOriginalFilename());
					//验证图片格式
					if(extEndName!=null) {
						//图片名称
						String picName = userId+"_icon.png";
						try {
							File file = new File(IfishFilePath.path_img, picName);
							//不存在则创建
							if(!file.exists()){
								file.mkdirs();
							}
							//保存
							fileUpload.transferTo(file);
						} catch (Exception e) {
							throw new RuntimeException(e);
						}
						//更新数据库
						user.setUserImg(picName);
						user.setUpdateTime(new Date());
						user = userDao.update(user);
						//更新云信
						updateIMUserInfo(userId.toString(), user.getNickName(), user.getUserImg());
						//返回数据
						JSONObject json = new JSONObject();
						json.put("userImg", picName);
						return new JsonResult<JSONObject>(ResultEnum.success.getKey(),json);
					}
					else{
						return new JsonResult<String>(ResultEnum.warn205.getKey());
					}
				}
			}
			else{
				return new JsonResult<String>(ResultEnum.fail101.getKey());
			}
		}
		else{
			return new JsonResult<String>(ResultEnum.warn211.getKey());
		}
	}
	
	/**
	 * 发送手机短信
	 * @param phoneNumber
	 * @param smsSign
	 * @param smsTemplate
	 * @return
	 */
	public JsonResult<?> sendMessage(String phoneNumber,String smsSign,String smsTemplate) {
		//4位随机数
		Integer code = (int)(Math.random()*9000+1000);
		boolean bln = smsNumSend.sendSmsNum(phoneNumber, code.toString(),smsSign,smsTemplate);
		//发送验证码
		if(bln){
			return new JsonResult<String>(ResultEnum.success.getKey(),code.toString());
		}
		else{
			return new JsonResult<String>(ResultEnum.fail101.getKey());
		}
	}
	/**
	 * 注册云信
	 * @param userId
	 * @param nickName
	 * @param userImg
	 * @return
	 */
	public Map<String,String> registerIM(String userId,String nickName,String userImg){
		return neteaseIM.createAccid(userId, nickName, IfishFilePath.getPath(SubDirectoryEnum.headImage,userImg), "");
	}
	/**
	 * 更新云信信息
	 * @param userId
	 * @param nickName
	 * @param userImg
	 * @return
	 */
	public Map<String,String> updateIMUserInfo(String userId,String nickName,String userImg){
		return neteaseIM.updateUinfo(userId, nickName, IfishFilePath.getPath(SubDirectoryEnum.headImage,userImg),"");
	}
	/**
	 * 获取云信token
	 * @param userId
	 * @return
	 */
	public Map<String,String> refreshToken(String userId){
		return neteaseIM.refreshToken(userId);
	}
	/**
	 * 第一次注册云信发送一条系统消息
	 * @param to
	 */
	public void sendMsgByIM(String to){
		//发送云信消息
		User user = userDao.findUniqueByProperty(Restrictions.eq("phoneNumber", IfishFilePath.netease_phone));
		if(user!=null){
			String from = user.getUserId().toString();
			neteaseIM.sendMsg(from, to, "感谢您使用爱鱼奇，连接智能设备请查看下方说明书，内含操作视频：http://u.eqxiu.com/s/KmmVl87l \n摄像头售后：021-54131006\n睿芯插排售后：15757401229\n绚多插排售后：18857689069\n松诺插排售后：13392205468","");
		}
	}
	/**
	 * 封装设备信息
	 * @param userId
	 * @return
	 */
	@Deprecated
	public DeviceInfoDto getDeviceInfo(Integer userId){
		//设备list
		List<JSONObject> deviceList = new ArrayList<JSONObject>();
		//设备ID
		List<Integer> deviceIds = new ArrayList<Integer>();
		//获取用户拥有设备
		List<DeviceUser> deviceUserList = deviceUserDao.findByProperty(Restrictions.eq("priId.userId", userId));
		for(DeviceUser deviceUser:deviceUserList){
			//查询设备信息
			Integer deviceId = deviceUser.getPriId().getDeviceId();
			Device device = deviceDao.get(deviceId);
			//json
			JSONObject json = new JSONObject();
			//封装设备返回信息
			deviceIds.add(deviceId);
			deviceList.add(json);
			//json存储设备信息
			json.put("userId", userId);
			json.put("deviceId", deviceId);
			json.put("isMaster", deviceUser.getIsMaster());
			json.put("showName", deviceUser.getShowName());
			json.put("macAddress", device.getMacAddress());
			json.put("isBlacklist", device.getIsBlacklist());
			//控制方案
			String type = device.getHardwareType();
			//鱼缸厂code
			String brandCode = device.getBrandCode();
			if(type!=null){
				HardwareType hardwareType = cacheService.findHardwareTypeById(type);
				if(hardwareType!=null){
					//设备类型
					json.put("type", type);
					//有无工作模式
					json.put("isWorkModel", hardwareType.getIsWorkModel());
					//控制信息
					json.put("controlAmount", hardwareType.getControlAmount());
					json.put("timerAmount", hardwareType.getTimerAmount());
					//背光/柜灯
					json.put("isLightness", hardwareType.getIsLightness());
					json.put("isSarkLamp", hardwareType.getIsSarkLamp());
					//是否显示预警推送
					if(brandCode!=null && brandCode.equals("YUEM") && device.getCreateTime().before(IfishUtil.StrToDate("2016-04-26"))){
						json.put("isPushWendu", BooleanEnum.NO.getKey());
					}
					else{
						json.put("isPushWendu", BooleanEnum.YES.getKey());
					}
					//换水提醒
					json.put("todayRemind", device.getTodayRemind());
					json.put("waterRemind", device.getWaterRemind());
					json.put("remindDate", device.getRemindDate()!=null?IfishUtil.format1(device.getRemindDate()):"");
					json.put("remindCycle", device.getRemindCycle()!=null?device.getRemindCycle():"");
					//自定义图标信息
					String isCustomIcon = hardwareType.getIsCustomIcon();
					json.put("isCustomIcon", isCustomIcon);
					if(isCustomIcon.equals(BooleanEnum.YES.getKey())){
						json.put("customIconName", deviceUser.getCustomIconName());
						json.put("customShowName", deviceUser.getCustomShowName());
						json.put("isCustomIcon", hardwareType.getIsCustomIcon());
						json.put("iconLink", hardwareType.getIconLink());
						json.put("allIconName", hardwareType.getAllIconName());
						json.put("allShowName", hardwareType.getAllShowName());
						json.put("defaultIconName", hardwareType.getDefaultIconName());
						json.put("defaultShowName", hardwareType.getDefaultShowName());
					}
				}
			}
			//厂家
			VenderList venderList = cacheService.findVenderListById(brandCode);
			if(venderList!=null){
				json.put("venderList", venderList);
			}
			else{
				//默认爱鱼奇
				json.put("venderList", cacheService.findVenderListById("AYQ"));
			}
		}
		return new DeviceInfoDto(deviceIds, deviceList);
	}
	
	/**
	 * 删除设备关联关系并推送消息
	 * @param deviceUserList
	 * @param deviceId
	 */
	public void deleteDeviceAndPushMsg(List<DeviceUser> deviceUserList,Integer deviceId){
		//推送消息类型
		PushTypeEnum pushTypeEnum = PushTypeEnum.remove_device;
		String title = pushTypeEnum.getValue();
		String pushType = pushTypeEnum.getKey();
		String timestamp = IfishUtil.format(new Date());
		//解除设备和用户关联关系并发送推送
		for (DeviceUser deviceUser : deviceUserList) {
			deviceUserDao.delete(deviceUser);
			Integer userId = deviceUser.getPriId().getUserId();
			String showName = deviceUser.getShowName();
			String content = "你已于"+timestamp+"失去对“"+showName+"”设备的控制权";
			//推送云信消息
			Map<String, String> neteaseMap = neteaseIM.sendMsg(IfishFilePath.ifish_account, userId.toString(), "【"+title+"】"+content,null);
			String neteaseStatus = NeteaseEnum.status200.getKey().equals(neteaseMap.get("code"))?BooleanEnum.YES.getKey():BooleanEnum.NO.getKey();
			//保存推送记录
			PushList pushList = new PushList(userId, deviceId, showName, pushType ,neteaseStatus, title, content);
			pushListDao.save(pushList);
		}
		//删除设备和摄像头关联关系
		List<DeviceCamera> deviceCameraList = deviceCameraDao.findByProperty(Restrictions.eq("deviceCameraId.deviceId", deviceId));
		for (DeviceCamera deviceCamera : deviceCameraList) {
			deviceCameraDao.delete(deviceCamera);
		}
	}
	
	/**
	 * 设备DTO
	 * @param deviceUser
	 * @param device
	 * @return
	 */
	public DeviceDto getDeviceDto(DeviceUser deviceUser,Device device){
		String type = device.getHardwareType();
		//设备信息DTO
		DeviceDto dto = new DeviceDto(device.getDeviceId(), device.getMacAddress(), deviceUser.getShowName(), deviceUser.getIsMaster(), type, device.getIsBlacklist());
		//用户ID
		dto.setUserId(deviceUser.getPriId().getUserId());
		//硬件类型
		HardwareType hardwareType = cacheService.findHardwareTypeById(type);
		if(hardwareType!=null){
			//控制数和定时器数
			dto.setControlAmount(hardwareType.getControlAmount());
			dto.setTimerAmount(hardwareType.getTimerAmount());
			//有无工作模式
			dto.setIsWorkModel(hardwareType.getIsWorkModel());
			//背光/柜灯
			dto.setIsLightness(hardwareType.getIsLightness());
			dto.setIsSarkLamp(hardwareType.getIsSarkLamp());
		}
		//鱼缸厂
		String brandCode = device.getBrandCode();
		//是否显示预警推送,2016-04-26号之前越美水族的不显示温度预警开关
		if("YUEM".equals(brandCode) && device.getCreateTime().before(IfishUtil.StrToDate("2016-04-26"))){
			dto.setIsPushWendu(BooleanEnum.NO.getKey());
		}
		else{
			dto.setIsPushWendu(BooleanEnum.YES.getKey());
		}
		//换水提醒
		dto.setTodayRemind(device.getTodayRemind());
		dto.setWaterRemind(device.getWaterRemind());
		dto.setRemindDate(device.getRemindDate()!=null?IfishUtil.format1(device.getRemindDate()):"");
		dto.setRemindCycle(device.getRemindCycle()!=null?device.getRemindCycle().toString():"");
		//鱼缸厂信息
		VenderList venderList = cacheService.findVenderListById(brandCode);
		if(venderList==null){
			//默认爱鱼奇
			venderList = cacheService.findVenderListById("AYQ");
		}
		if(venderList!=null){
			//鱼缸厂信息DTO
			VenderDto venderDto = new VenderDto(venderList.getBrandName(), venderList.getBrandIntroduce(), venderList.getLogo());
			dto.setVenderDto(venderDto);
		}
		return dto;
	}
	
	/**
	 * 优化后设备信息
	 * @param userId
	 */
	public DeviceInfoDto getSimpleDeviceInfo(Integer userId){
		//设备信息DTO
		List<DeviceDto> deviceDtoList = new ArrayList<DeviceDto>();
		//设备ID
		List<Integer> deviceIds = new ArrayList<Integer>();
		//用户关联的设备信息
		List<DeviceUser> deviceUserList = deviceUserDao.findByProperty(Restrictions.eq("priId.userId", userId));
		for (DeviceUser deviceUser : deviceUserList) {
			//设备Id
			Integer deviceId = deviceUser.getPriId().getDeviceId();
			//设备信息
			Device device = deviceDao.get(deviceId);
			if(device!=null){
				deviceIds.add(deviceId);
				deviceDtoList.add(getDeviceDto(deviceUser, device));
			}
		}
		return new DeviceInfoDto(deviceIds, deviceDtoList);
	}
	
	/**
	 * 获取技威相关参数
	 * @param isRegisterGwell
	 * @param phoneNumber
	 * @return
	 */
	public GwellParamDto getGwellInfo(String isRegisterGwell,String phoneNumber){
		//未注册技威
		if(!BooleanEnum.YES.getKey().equals(isRegisterGwell)){
			//注册技威
			Map<String,String> registerMap = GwellApi.Register(phoneNumber);
			String registerResult = registerMap.get("result");
			if(registerResult!=null){
				//注册成功
				if(registerResult.equals(GwellEnum.success.getKey())){
					return new GwellParamDto(BooleanEnum.YES.getKey(),registerMap.get("P2PVerifyCode1"),registerMap.get("P2PVerifyCode2"),registerMap.get("UserID"));
				}
				//已经注册过
				else if(registerResult.equals(GwellEnum.repeat.getKey())){
					//重新登陆获取
					Map<String,String> loginMap = GwellApi.Login(phoneNumber);
					String loginResult = loginMap.get("result");
					//登陆成功
					if(GwellEnum.success.getKey().equals(loginResult)){
						return new GwellParamDto(BooleanEnum.YES.getKey(),loginMap.get("P2PVerifyCode1"),loginMap.get("P2PVerifyCode2"),loginMap.get("UserID"));
					}
					else{
						return new GwellParamDto(BooleanEnum.YES.getKey());
					}
				}
			}
		}
		return null;
	}
	
	/**
	 * 获取云信相关参数
	 * @param isRegisterNetease
	 * @param userId
	 * @param nickName
	 * @param userImg
	 * @param neteaseToken
	 * @return
	 */
	public NeteaseParamDto GetNeteaseInfo(String isRegisterNetease,Integer userId,String nickName,String userImg,String neteaseToken){
		//未注册云信
		if(!BooleanEnum.YES.getKey().equals(isRegisterNetease)){
			//注册云信
			Map<String, String> registerMap = registerIM(userId.toString(),nickName,userImg);
			if(registerMap!=null){
				String code = registerMap.get("code");
				if(code.equals(NeteaseEnum.status200.getKey())){
					//发送云信消息
					sendMsgByIM(userId.toString());
					return new NeteaseParamDto(BooleanEnum.YES.getKey(), registerMap.get("token"));
				}
				else if(code.equals(NeteaseEnum.status414.getKey())){
					//获取云信token
					Map<String, String> refreshMap = refreshToken(userId.toString());
					if(refreshMap!=null){
						String refreshCode = refreshMap.get("code");
						if(refreshCode.equals(NeteaseEnum.status200.getKey())){
							return new NeteaseParamDto(BooleanEnum.YES.getKey(), refreshMap.get("token"));
						}
					}
				}
			}
		}
		//已注册云信
		else if(BooleanEnum.YES.getKey().equals(isRegisterNetease)){
			//token为空
			if(!StringUtils.isNotBlank(neteaseToken)){
				//获取云信token
				Map<String, String> refreshMap = refreshToken(userId.toString());
				if(refreshMap!=null){
					String code = refreshMap.get("code");
					if(code.equals(NeteaseEnum.status200.getKey())){
						return new NeteaseParamDto(BooleanEnum.YES.getKey(), refreshMap.get("token"));
					}
				}
			}
		}
		return null;
	}
	
	/**
	 * 封装用户信息
	 * @param user
	 * @return
	 */
	public JSONObject getUserInfo(User user){
		JSONObject json = new JSONObject();
		json.put("userId", user.getUserId());
		json.put("phoneNumber", user.getPhoneNumber());
		json.put("nickName", user.getNickName());
		json.put("userSex", user.getUserSex());
		json.put("signature", user.getSignature());
		json.put("userImg", user.getUserImg());
		json.put("P2PVerifyCode1", user.getP2PVerifyCode1());
		json.put("P2PVerifyCode2", user.getP2PVerifyCode2());
		json.put("gwellUserID", user.getGwellUserID());
		json.put("neteaseToken", user.getNeteaseToken());
		json.put("userType", user.getUserType());
		json.put("shopsUserId", user.getShopsUserId());
		return json;
	}
	/**
	 * 封装用户信息
	 * @param user
	 * @return
	 */
	public UserInfoDto getUserInfoDto(User user){
		UserInfoDto dto = new UserInfoDto();
		dto.setUserId(user.getUserId());
		dto.setPhoneNumber(user.getPhoneNumber());
		dto.setNickName(user.getNickName());
		dto.setUserSex(user.getUserSex());
		dto.setSignature(user.getSignature());
		dto.setUserImg(user.getUserImg());
		dto.setP2PVerifyCode1(user.getP2PVerifyCode1());
		dto.setP2PVerifyCode2(user.getP2PVerifyCode2());
		dto.setGwellUserID(user.getGwellUserID());
		dto.setNeteaseToken(user.getNeteaseToken());
		dto.setUserType(user.getUserType());
		dto.setShopsUserId(user.getShopsUserId());
		return dto;
	}
	/**
	 * 用户资产和签到信息(经验值,金币等)
	 * @param userId
	 * @return
	 */
	public UserAssetDto getUserAssetInfo(Integer userId){
		UserAsset userAsset = userAssetDao.get(userId);
		if(userAsset==null){
			//之前注册用户赠送20金币
			BigDecimal gold = new BigDecimal(20);
			userAsset = new UserAsset(userId,gold);
			userAssetDao.save(userAsset);
			//获取记录
			GoldGetRecord getRecord = new GoldGetRecord(userId, GoldGetTypeEnum.registerGive.getKey(), gold, GoldGetTypeEnum.registerGive.getValue());
			goldGetRecordDao.save(getRecord);
		}
		//日期
		Calendar calendar = Calendar.getInstance();
		//今天
		Date date = calendar.getTime();
		String today = IfishUtil.format1(date);
		//昨天
		calendar.add(Calendar.DAY_OF_MONTH, -1);
		String yesterday = IfishUtil.format1(calendar.getTime());
		//最后一天登陆日期
		String lastLogin = userAsset.getLastLoginDate();
		//规则
		GradeTask gradeRule = cacheService.getGradeRule(GradeGetTypeEnum.everyDayLogin.getKey());
		//今天登陆过
		if(gradeRule==null || lastLogin.equals(today)){
			return goldService.getUserAssetInfo(userAsset, new BigDecimal(0), today, yesterday);
		}
		return gradeService.getGradeControl(userAsset, gradeRule ,true);
	}
	
	/**
	 * 封装摄像头信息
	 * @param userId
	 * @return
	 */
	public List<JSONObject> getCameraInfo(Integer userId){
		List<JSONObject> cameraList = new ArrayList<JSONObject>();
		//获取用户拥有摄像头
		List<CameraUser> cameraUserList = cameraUserDao.findByProperty(Restrictions.eq("cameraUserId.userId", userId));
		for(CameraUser cameraUser:cameraUserList){
			Camera camera = cameraDao.get(cameraUser.getCameraUserId().getCameraId());
			//封装摄像头返回信息
			JSONObject json = new JSONObject();
			json.put("cameraId", camera.getCameraId());
			//json.put("isMaster", cameraUser.getIsMaster());
			json.put("isLook", cameraUser.getIsLook());
			json.put("isLive", cameraUser.getIsLive());
			json.put("isActive", camera.getActiveCode()!=null&&camera.getActiveCode().length()>0?"1":"0");
			json.put("showName", cameraUser.getShowName());
			cameraList.add(json);
		}
		return cameraList;
	}
	
	/**
	 * 设备关联摄像头
	 * @param deviceIds
	 * @return
	 */
	public List<DeviceCameraId> getDeviceCamera(List<Integer> deviceIds){
		//设备关联摄像头信息
		List<DeviceCameraId> deviceCameraList = new ArrayList<DeviceCameraId>();
		//设备已关联摄像头
		if(deviceIds.size()>0){
			List<DeviceCamera> list = deviceCameraDao.findByProperty(Restrictions.in("deviceCameraId.deviceId", deviceIds));
			for(DeviceCamera deviceCamera:list){
				deviceCameraList.add(deviceCamera.getDeviceCameraId());
			}
		}
		return deviceCameraList;
	}
	
	/**
	 * 封装商家认证信息
	 * @param shopsInfo
	 * @param userImg
	 * @return
	 */
	public JSONObject getShopsInfo(Integer userId,String userImg){
		if(userId!=null){
			ShopsInfo shopsInfo = shopsInfoDao.findUniqueByProperty(Restrictions.eq("userId", userId));
			if(shopsInfo!=null){
				//封装商家认证信息
				JSONObject json = new JSONObject();
				json.put("shopsId", shopsInfo.getShopsId());
				json.put("userId", shopsInfo.getUserId());
				if(userImg!=null){
					json.put("userImg", userImg);
				}
				else{
					User user = userDao.get(userId);
					json.put("userImg", user.getUserImg());
				}
				json.put("userName", shopsInfo.getUserName());
				json.put("shopsName", shopsInfo.getShopsName());
				json.put("shopsPhone", shopsInfo.getShopsPhone());
				json.put("shopsProvince", shopsInfo.getShopsProvince());
				json.put("shopsCity", shopsInfo.getShopsCity());
				json.put("shopsArea", shopsInfo.getShopsArea());
				json.put("shopsAddress", shopsInfo.getShopsAddress());
				json.put("picture1", shopsInfo.getPicture1());
				json.put("picture2", shopsInfo.getPicture2());
				json.put("picture3", shopsInfo.getPicture3());
				json.put("picture4", shopsInfo.getPicture4());
				json.put("status", shopsInfo.getStatus());
				json.put("remark", shopsInfo.getRemark());
				json.put("reason", shopsInfo.getReason());
				json.put("weixinCode", shopsInfo.getWeixinCode());
				json.put("shopLink", shopsInfo.getShopLink());
				return json;
			}
		}
		return new JSONObject();
	}
	
	/**
	 * 金币任务信息
	 * @param userId
	 * @return
	 */
	public List<GoldTaskDto> getGoldTaskList(Integer userId){
		//任务信息
		List<GoldTaskDto> goldTaskList = new ArrayList<GoldTaskDto>();
		//今天日期
		String today = IfishUtil.format1(new Date());
		//已完成金币任务
		Map<String, String> finishMap = new HashMap<String, String>();
		List<GoldControl> goldControls = goldControlDao.findByProperty(Restrictions.eq("goldControlId.userId", userId));
		for (GoldControl goldControl : goldControls) {
			finishMap.put(goldControl.getGoldControlId().getRuleType(), goldControl.getControlParam());
		}
		//所有金币任务
		for (GoldTask goldRule : cacheService.getGoldRuleList()) {
			//类型
			String ruleType = goldRule.getRuleType();
			//加成类型
			String addType = goldRule.getAddType();
			//任务是否完成
			String controlDate = finishMap.get(ruleType);
			//规则信息DTO
			GoldTaskDto taskDto = new GoldTaskDto(ruleType, addType, goldRule.getAddValue().toString(), BooleanEnum.NO.getKey());
			goldTaskList.add(taskDto);
			if(controlDate!=null){
				if(addType.equals(AddTypeEnum.once.getKey()) || (addType.equals(AddTypeEnum.everyDay.getKey()) && controlDate.equals(today))){
					taskDto.setIsFinish(BooleanEnum.YES.getKey());
				}
			}
		}
		return goldTaskList;
	}
}
