package com.ifish.serviceImpl;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.criterion.Order;
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.ifish.dao.CameraUserDao;
import com.ifish.dao.DeviceUserDao;
import com.ifish.dao.ShopsInfoDao;
import com.ifish.dao.ShopsUserInfoDao;
import com.ifish.dao.UserDao;
import com.ifish.dto.JsonResult;
import com.ifish.dto.PageingDto;
import com.ifish.dto.ShopsListDto;
import com.ifish.dto.ShopsUserDto;
import com.ifish.dto.ShopsUserInfoDto;
import com.ifish.entity.CameraUser;
import com.ifish.entity.ShopsInfo;
import com.ifish.entity.ShopsUserInfo;
import com.ifish.entity.ShopsUserInfoId;
import com.ifish.entity.User;
import com.ifish.enums.BooleanEnum;
import com.ifish.enums.MemberLevelEnum;
import com.ifish.enums.PushTypeEnum;
import com.ifish.enums.ResultEnum;
import com.ifish.enums.ShopsStatusEnum;
import com.ifish.enums.UserTypeEnum;
import com.ifish.exception.IfishException;
import com.ifish.hibernate.Pagination;
import com.ifish.mail.Mail;
import com.ifish.netease.NeteaseIM;
import com.ifish.service.AsyncTaskService;
import com.ifish.service.ShopsService;
import com.ifish.util.IfishFilePath;
import com.ifish.util.IfishUtil;
import com.ifish.util.ResultUtil;
import com.ifish.validator.PageParam;
import com.ifish.validator.ShopsUserInfoParam;

@Service
@Transactional
public class ShopsServiceImpl implements ShopsService{
	
	@Autowired
	private UserDao userDao;
	@Autowired
	private NeteaseIM neteaseIM;
	@Autowired
	private ShopsInfoDao shopsInfoDao;
	@Autowired
	private CameraUserDao cameraUserDao;
	@Autowired
	private DeviceUserDao deviceUserDao;
	@Autowired
	private ShopsUserInfoDao shopsUserInfoDao;
	@Autowired
	private AsyncTaskService asyncTaskService;

	@Override
	public Object getShopsInfoByPage(Integer userId,Integer firstResult, Integer pageSize) {
		if(userId!=null){
			if(firstResult==null){
				firstResult=0;
			}
			if(pageSize==null){
				pageSize=10;
			}
			User user = this.userDao.get(userId);
			Pagination<ShopsListDto> page = this.shopsInfoDao.findByDistance(user.getLongitude(), user.getLatitude(), firstResult, pageSize);
			Map<String, Object> returnMap = new HashMap<String, Object>();
			returnMap.put("result", ResultEnum.success.getKey());
			returnMap.put("total", page.getTotalCount());
			returnMap.put("data", page.getList());
			return returnMap;
		}
		return IfishUtil.toJson(ResultEnum.fail101.getKey(), "");
	}

	@Override
	public Object choiceShops(Integer shopsUserId, Integer userId) {
		//普通用户
		User user = this.userDao.get(userId);
		if(user==null){
			throw new IfishException(ResultEnum.error402);
		}
		//商家用户
		User shopsUser = this.userDao.get(shopsUserId);
		if(shopsUser==null){
			throw new IfishException(ResultEnum.error402);
		}
		//商家信息
		ShopsInfo shopsInfo = this.shopsInfoDao.findUniqueByProperty(Restrictions.eq("userId", shopsUserId));
		if(shopsInfo==null){
			throw new IfishException(ResultEnum.error402);
		}
		//是商家类型用户
		if(shopsUser.getUserType().equals(UserTypeEnum.userType1.getKey())){
			//选择商家
			user.setShopsUserId(shopsUserId);
			this.userDao.update(user);
			//摄像头默认开启看护
			List<CameraUser> CameraUserList = cameraUserDao.findByProperty(Restrictions.eq("cameraUserId.userId", userId));
			for (CameraUser cameraUser : CameraUserList) {
				cameraUser.setIsLook(BooleanEnum.YES.getKey());
				cameraUserDao.update(cameraUser);
			}
			//成为商家会员
			ShopsUserInfoId id = new ShopsUserInfoId(shopsInfo.getShopsId(), userId);
			ShopsUserInfo tmp = shopsUserInfoDao.get(id);
			if(tmp==null){
				//新增商家用户信息
				tmp = new ShopsUserInfo(id, MemberLevelEnum.level_1.getKey());
				tmp.setUserName(user.getNickName());
				tmp.setPhoneNumber(user.getPhoneNumber());
				shopsUserInfoDao.save(tmp);
				//发送云信息消息
				asyncTaskService.sendMsgToShopsUser(userId, shopsUserId, user.getNickName());
			}
			//发送云信消息
			neteaseIM.sendMsg(IfishFilePath.ifish_account, shopsUserId.toString(), "【"+PushTypeEnum.shops_push.getValue()+"】恭喜，["+user.getNickName()+"]已经将你锁定为他的看护商家，快去看看吧","");
			return IfishUtil.toJson(ResultEnum.success.getKey(), getShoppsInfo(shopsInfo, shopsUser));
		}
		return IfishUtil.toJson(ResultEnum.fail101.getKey(), "");
	}

	@Override
	public Object removeLook(Integer userId) {
		if(userId!=null){
			User user = this.userDao.get(userId);
			if(user!=null){
				//解除看护关系
				user.setShopsUserId(null);
				this.userDao.update(user);
				List<CameraUser> cameraUserList = this.cameraUserDao.findByProperty(Restrictions.eq("isLook", BooleanEnum.YES.getKey()));
				for (CameraUser cameraUser : cameraUserList) {
					cameraUser.setIsLook(BooleanEnum.NO.getKey());
					this.cameraUserDao.update(cameraUser);
				}
				return IfishUtil.toJson(ResultEnum.success.getKey(), "");
			}
		}
		return IfishUtil.toJson(ResultEnum.fail101.getKey(), "");
	}

	@Override
	public Object saveShopsInfo(ShopsInfo shopsInfo,MultipartFile file1,MultipartFile file2,MultipartFile file3) {
		//用户ID
		Integer userId = shopsInfo.getUserId();
		User user = this.userDao.get(userId);
		if(user==null){
			return IfishUtil.returnJson(ResultEnum.warn211.getKey(), "");
		}
		//验证图片格式
		if(!file1.isEmpty() && !file2.isEmpty() && !file3.isEmpty()) {
			try {
				if(!file1.getOriginalFilename().equals("")){
					File picFile = new File(IfishFilePath.path_shops+"/"+userId, "1.png");
					//不存在则创建
					if(!picFile.exists()){
						picFile.mkdirs();
					}
					//保存
					file1.transferTo(picFile);
				}
				if(!file2.getOriginalFilename().equals("")){
					File picFile = new File(IfishFilePath.path_shops+"/"+userId, "2.png");
					//不存在则创建
					if(!picFile.exists()){
						picFile.mkdirs();
					}
					//保存
					file2.transferTo(picFile);
				}
				if(!file3.getOriginalFilename().equals("")){
					File picFile = new File(IfishFilePath.path_shops+"/"+userId, "3.png");
					//不存在则创建
					if(!picFile.exists()){
						picFile.mkdirs();
					}
					//保存
					file3.transferTo(picFile);
				}
				//保存商家信息
				shopsInfo.setPicture1("1.png");
				shopsInfo.setPicture2("2.png");
				shopsInfo.setPicture3("3.png");
				shopsInfo.setStatus(ShopsStatusEnum.status2.getKey());
				shopsInfo.setUpdateTime(new Date());
				shopsInfo.setCreateTime(new Date());
				this.shopsInfoDao.save(shopsInfo);
				//发送邮件
				Mail.send(user.getNickName()+"("+user.getPhoneNumber()+")提交审核了", "有提交新的审核!");
				return IfishUtil.returnJson(ResultEnum.success.getKey(), getShoppsInfo(shopsInfo, user));
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
		return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
	}

	@Override
	public Object updateShopsInfo(ShopsInfo shopsInfo, MultipartFile file1,MultipartFile file2, MultipartFile file3) {
		ShopsInfo tmpShopsInfo = this.shopsInfoDao.get(shopsInfo.getShopsId());
		if(tmpShopsInfo!=null){
			Integer userId = tmpShopsInfo.getUserId();
			try {
				if(file1!=null && !file1.isEmpty() && !file1.getOriginalFilename().equals("")){
					File picFile = new File(IfishFilePath.path_shops+"/"+userId, "1.png");
					//不存在则创建
					if(!picFile.exists()){
						picFile.mkdirs();
					}
					//保存
					file1.transferTo(picFile);
				}
				if(file2!=null && !file2.isEmpty() && !file2.getOriginalFilename().equals("")){
					File picFile = new File(IfishFilePath.path_shops+"/"+userId, "2.png");
					//不存在则创建
					if(!picFile.exists()){
						picFile.mkdirs();
					}
					//保存
					file2.transferTo(picFile);
				}
				if(file3!=null && !file3.isEmpty() && !file3.getOriginalFilename().equals("")){
					File picFile = new File(IfishFilePath.path_shops+"/"+userId, "3.png");
					//不存在则创建
					if(!picFile.exists()){
						picFile.mkdirs();
					}
					//保存
					file3.transferTo(picFile);
				}
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
			//保存商家信息
			tmpShopsInfo.setShopsName(shopsInfo.getShopsName());
			tmpShopsInfo.setUserName(shopsInfo.getUserName());
			tmpShopsInfo.setShopsPhone(shopsInfo.getShopsPhone());
			tmpShopsInfo.setShopsProvince(shopsInfo.getShopsProvince());
			tmpShopsInfo.setShopsCity(shopsInfo.getShopsCity());
			tmpShopsInfo.setShopsArea(shopsInfo.getShopsArea());
			tmpShopsInfo.setShopsAddress(shopsInfo.getShopsAddress());
			tmpShopsInfo.setStatus(ShopsStatusEnum.status2.getKey());
			tmpShopsInfo.setWeixinCode(shopsInfo.getWeixinCode());
			tmpShopsInfo.setShopLink(shopsInfo.getShopLink());
			tmpShopsInfo.setUpdateTime(new Date());
			this.shopsInfoDao.update(tmpShopsInfo);
			User user = this.userDao.get(tmpShopsInfo.getUserId());
			//发送邮件
			Mail.send(user.getNickName()+"("+user.getPhoneNumber()+")重新提交审核了", "重新提交了新的审核!");
			return IfishUtil.returnJson(ResultEnum.success.getKey(), getShoppsInfo(tmpShopsInfo, user));
		}
		return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
	}

	@Override
	public Object updateBaseShopsInfo(ShopsInfo shopsInfo,MultipartFile file4) {
		ShopsInfo tmpShopsInfo = this.shopsInfoDao.get(shopsInfo.getShopsId());
		if(tmpShopsInfo!=null){
			try{
				if(file4!=null && !file4.isEmpty() && !file4.getOriginalFilename().equals("")){
					File picFile = new File(IfishFilePath.path_shops+"/"+tmpShopsInfo.getUserId(), "4.png");
					//不存在则创建
					if(!picFile.exists()){
						picFile.mkdirs();
					}
					//保存
					file4.transferTo(picFile);
					tmpShopsInfo.setPicture4("4.png");
				}
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
			tmpShopsInfo.setShopsPhone(shopsInfo.getShopsPhone());
			tmpShopsInfo.setShopsProvince(shopsInfo.getShopsProvince());
			tmpShopsInfo.setShopsCity(shopsInfo.getShopsCity());
			tmpShopsInfo.setShopsArea(shopsInfo.getShopsArea());
			tmpShopsInfo.setShopsAddress(shopsInfo.getShopsAddress());
			tmpShopsInfo.setWeixinCode(shopsInfo.getWeixinCode());
			tmpShopsInfo.setShopLink(shopsInfo.getShopLink());
			tmpShopsInfo.setUpdateTime(new Date());
			this.shopsInfoDao.update(tmpShopsInfo);
			User user = this.userDao.get(tmpShopsInfo.getUserId());
			return IfishUtil.returnJson(ResultEnum.success.getKey(), getShoppsInfo(tmpShopsInfo, user));
		}
		return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
	}
	
	@Override
	public Object getShopsStatus(Integer shopsId){
		ShopsInfo shopsInfo = this.shopsInfoDao.get(shopsId);
		if(shopsInfo!=null){
			User user = this.userDao.get(shopsInfo.getUserId());
			return IfishUtil.returnJson(ResultEnum.success.getKey(), getShoppsInfo(shopsInfo, user));
		}
		return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
	}
	
	public Map<String, Object> getShoppsInfo(ShopsInfo shopsInfo,User user){
		Map<String, Object> shopsInfoMap = new HashMap<String, Object>();
		shopsInfoMap.put("shopsId", shopsInfo.getShopsId());
		shopsInfoMap.put("userId", shopsInfo.getUserId());
		shopsInfoMap.put("userImg", user.getUserImg());
		shopsInfoMap.put("userName", shopsInfo.getUserName());
		shopsInfoMap.put("shopsName", shopsInfo.getShopsName());
		shopsInfoMap.put("shopsPhone", shopsInfo.getShopsPhone());
		shopsInfoMap.put("shopsProvince", shopsInfo.getShopsProvince());
		shopsInfoMap.put("shopsCity", shopsInfo.getShopsCity());
		shopsInfoMap.put("shopsArea", shopsInfo.getShopsArea());
		shopsInfoMap.put("shopsAddress", shopsInfo.getShopsAddress());
		shopsInfoMap.put("picture1", shopsInfo.getPicture1());
		shopsInfoMap.put("picture2", shopsInfo.getPicture2());
		shopsInfoMap.put("picture3", shopsInfo.getPicture3());
		shopsInfoMap.put("picture4", shopsInfo.getPicture4());
		shopsInfoMap.put("status", shopsInfo.getStatus());
		shopsInfoMap.put("remark", shopsInfo.getRemark());
		shopsInfoMap.put("reason", shopsInfo.getReason());
		shopsInfoMap.put("weixinCode", shopsInfo.getWeixinCode());
		shopsInfoMap.put("shopLink", shopsInfo.getShopLink());
		return shopsInfoMap;
	}

	/**
	 * 获取商家会员信息
	 */
	@Override
	public JsonResult<?> getShopsUserInfoById(Integer userId, Integer shopsId) {
		ShopsUserInfoId id = new ShopsUserInfoId(shopsId, userId);
		ShopsUserInfo shopsUserInfo = shopsUserInfoDao.get(id);
		//商家用户信息
		if(shopsUserInfo==null){
			//用户信息
			User user = userDao.get(userId);
			if(user==null){
				throw new IfishException(ResultEnum.error402);
			}
			//临时商家用户信息
			shopsUserInfo = new ShopsUserInfo(id, MemberLevelEnum.level_1.getKey());
			shopsUserInfo.setPhoneNumber(user.getPhoneNumber());
			shopsUserInfo.setUserName(user.getNickName());
		}
		//水族箱个数
		int deviceNum = deviceUserDao.getDeviceNumById(userId);
		//摄像头个数
		int cameraNum = cameraUserDao.getCameraNumById(userId);
		//返回信息DTO
		ShopsUserInfoDto infoDto = new ShopsUserInfoDto(userId, shopsId, shopsUserInfo.getMemberLevel(), deviceNum, cameraNum);
		infoDto.setUserName(shopsUserInfo.getUserName());
		infoDto.setPhoneNumber(shopsUserInfo.getPhoneNumber());
		infoDto.setProvince(shopsUserInfo.getProvince());
		infoDto.setCity(shopsUserInfo.getCity());
		infoDto.setArea(shopsUserInfo.getArea());
		infoDto.setAddress(shopsUserInfo.getAddress());
		infoDto.setRemark(shopsUserInfo.getRemark());
		return ResultUtil.success(infoDto);
	}

	/**
	 * 更新商家会员信息
	 */
	@Override
	public JsonResult<?> updateShopsUserInfo(Integer userId,Integer shopsId,ShopsUserInfoParam param) {
		//商家用户信息
		ShopsUserInfoId id = new ShopsUserInfoId(shopsId, userId);
		ShopsUserInfo tmp = shopsUserInfoDao.get(id);
		if(tmp==null){
			//用户信息
			User user = userDao.get(userId);
			if(user==null){
				throw new IfishException(ResultEnum.error402);
			}
			//商家信息
			ShopsInfo shopsInfo = shopsInfoDao.get(shopsId);
			if(shopsInfo==null){
				throw new IfishException(ResultEnum.error402);
			}
			//新增商家会员信息
			tmp = new ShopsUserInfo(id, param.getMemberLevel());
			tmp.setUserName(param.getUserName());
			tmp.setPhoneNumber(param.getPhoneNumber());
			tmp.setProvince(param.getProvince());
			tmp.setCity(param.getCity());
			tmp.setArea(param.getArea());
			tmp.setAddress(param.getAddress());
			tmp.setRemark(param.getRemark());
			shopsUserInfoDao.save(tmp);
			//发送云信息消息
			asyncTaskService.sendMsgToShopsUser(userId, shopsInfo.getUserId(), user.getNickName());
		}
		else{
			//更新用户信息
			tmp.setMemberLevel(param.getMemberLevel());
			tmp.setUserName(param.getUserName());
			tmp.setPhoneNumber(param.getPhoneNumber());
			tmp.setProvince(param.getProvince());
			tmp.setCity(param.getCity());
			tmp.setArea(param.getArea());
			tmp.setAddress(param.getAddress());
			tmp.setRemark(param.getRemark());
			tmp.setUpdateTime(new Date());
			shopsUserInfoDao.update(tmp);
		}
		return ResultUtil.success();
	}

	/**
	 * 分页获取商家会员信息
	 */
	@Override
	public PageingDto<?> getShopsUserInfoByPage(Integer shopsId,PageParam pageParam) {
		//分页获取数据
		Integer firstResult = pageParam.getFirstResult();
		Pagination<ShopsUserInfo> page = shopsUserInfoDao.findByCriteria(firstResult, pageParam.getPageSize(), Order.desc("createTime"), Restrictions.eq("id.shopsId", shopsId));
		List<ShopsUserInfo> list = page.getList();
		firstResult+=list.size();
		//封装
		List<ShopsUserDto> dtoList = new ArrayList<ShopsUserDto>();
		for (ShopsUserInfo info : list) {
			Integer userId = info.getId().getUserId();
			//分页会员信息DTO
			ShopsUserDto dto = new ShopsUserDto(userId, info.getUserName());
			dtoList.add(dto);
			User user = userDao.get(userId);
			if(user!=null){
				dto.setNickName(user.getNickName());
				dto.setUserImg(user.getUserImg());
				dto.setLoginTime(IfishUtil.format1(user.getLoginTime()));
			}
		}
		return new PageingDto<ShopsUserDto>(ResultEnum.success.getKey(), firstResult, page.getTotalCount(), dtoList);
	}

	/**
	 * 成为商家用户
	 */
	@Override
	public JsonResult<?> becomeShopsUser(Integer userId, Integer shopsId) {
		//商家会员
		ShopsUserInfoId id = new ShopsUserInfoId(shopsId, userId);
		ShopsUserInfo shopsUser = shopsUserInfoDao.get(id);
		if(shopsUser==null){
			//用户信息
			User user = userDao.get(userId);
			if(user==null){
				throw new IfishException(ResultEnum.error402);
			}
			//商家信息
			ShopsInfo shopsInfo = shopsInfoDao.get(shopsId);
			if(shopsInfo==null){
				throw new IfishException(ResultEnum.error402);
			}
			//新增商家会员信息
			shopsUser = new ShopsUserInfo(id, MemberLevelEnum.level_1.getKey());
			shopsUser.setPhoneNumber(user.getPhoneNumber());
			shopsUser.setUserName(user.getNickName());
			shopsUserInfoDao.save(shopsUser);
			//发送云信息消息
			asyncTaskService.sendMsgToShopsUser(userId, shopsInfo.getUserId(), user.getNickName());
		}
		return ResultUtil.success();
	}
	
}
