package com.iamberry.app.service;


import java.text.MessageFormat;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.iamberry.app.config.Constants;
import com.iamberry.app.config.ImberryConfig;
import com.iamberry.app.core.dto.RemoteIpInfoDTO;
import com.iamberry.app.core.dto.UserDTO;
import com.iamberry.app.core.entity.User;
import com.iamberry.app.face.UserService;
import com.iamberry.app.tool.util.AES;
import com.iamberry.app.tool.util.HttpUtility;
import com.iamberry.app.tool.util.MD5;
import com.iamberry.app.tool.util.TuyaConnector;
import com.iamberry.app.tool.util.WebJsonTokenUtil;
import com.iamberry.app.ulitity.Utility;
/**
 * UserService
 *
 * @author Moon Cheng
 * @date 2016年3月23日 上午11:33:29
 */
@Service
public class UserServiceImpl extends BaseService implements UserService {
	
	private Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

	/**
	 * register
	 *
	 * @author Moon Cheng
	 * @param phone 电话号码
	 * @param password 密码
	 * @param ip ip地址
	 * @return User Information
	 */
	@Transactional
	public User register(String phone, String password, String ip) {
		// 创建用户，填充数据
		User user = new User(phone, MD5.md5(password), new Date(), Constants.USER_SAVE_TEL);
		user.setUserTel(phone);															// 完善手机号码
		String defaultName = phone.substring(0, 3) + "****" + phone.substring(7, 11);	// 默认的昵称
		user.setDisplay_name(defaultName);
		user.setStatus_(Constants.USER_SAVE_TEL);										// 当前用户的状态为已完善手机号码,待完善宝宝信息
		user.setBaby_dob(Utility.formatStringToDate("yyyy-MM-dd", "1970-1-1")); 		// 设置宝宝生日
		RemoteIpInfoDTO dto = getLocation(ip);
		if (dto != null) {
			try {
				user.setLocation(dto.getCity());
			} catch (Exception e) {
				user.setLocation("深圳");
			}
		}
		
		// 在此，生成用户的保存区间，保证系统调用成功,通过手机号hash 定位当前区间
//		int interval = phone.hashCode() % 10;
		
		user.setCreated_on(new Date());													// 创建时间为当前时间
		userMapper.insertUser(user);
		
		if (user.getId() == null) {
			return null;
		}

		// 生成token
		String token = getEncToken(user.getId());
		user.setToken(token);
		user.setPassword(null);
		
		// 返回数据
		return user;
	}

	/**
	 * thirdPartBindingPhone
	 * @param phone
	 * @param openId
	 * @return
	 */
	public User thirdPartBindingPhone(String phone, String openId) {
		// 判断用户是否存在
		User user = userMapper.selectUserByUsername(openId);
		if (user == null) {
			return null;
		}
		// 用户已经完善手机号码，不需要完善
		if (!user.getStatus_().equals(Constants.USER_NOW_INIT)) {
			return null;
		}
		
		// 根据手机号码，完善信息
		User db = new User();
		db.setUserTel(phone);
		db.setStatus_(Constants.USER_SAVE_TEL);
		db.setId(user.getId());
		
		// 判断手机号码是否存在账户信息，如果有，需要copy
		User tempUser = userMapper.getOtherUserByTel(phone, user.getId().intValue());
		if (tempUser != null) {
			// 需要copy信息
			db.setBaby_dob(tempUser.getBaby_dob());
			db.setBaby_gender(tempUser.getBaby_gender());
			db.setBaby_nickname(tempUser.getBaby_nickname());
			db.setStatus_(Constants.USER_ACTIVE);
		}
		
		// 执行修改
		int status = userMapper.updateUser(db);
		if (status > 0) {
			user.setUsername(phone);
			user.setPassword(null);
		} else {
			return null;
		}
		
		user.setStatus_(db.getStatus_());
		return user;
	}

	/**
	 * findById
	 * @param id
	 * @return User
	 */
	public User findById(Long id) {
		User user = userMapper.selectUserById(id);
		user.setPassword(null);
		return user;
	}

	/**
	 * login
	 *
	 * @param phone
	 * @param password
	 * @param userAgent
	 * @return
	 */
	public Object login(String phone, String password) {
		User user = userMapper.selectUserByUsername(phone);
		if (user == null) {
			return -1;
		}
		if (!MD5.md5(password).equals(user.getPassword())) {
			return -2;
		}
		if (Constants.USER_SAVE_TEL.equals(user.getStatus_())) {
			// 待完善宝宝信息
			user.setIs_perfect_user(2);
		}
		// 生成token
		String token = getEncToken(user.getId());
		// 将手机号码 -----> username
		user.setUsername(user.getUserTel());
		user.setToken(token);
		user.setPassword(null);
		// 注册涂鸦
		UserDTO dto = tuyaConnect(user);
		if (Constants.USER_NOW_INIT.equals(user.getStatus_())) {
			// 需要完善手机号码
			dto.setIs_perfect_user(1);
		} else if (Constants.USER_SAVE_TEL.equals(user.getStatus_())) {
			// 需要完善宝宝信息
			dto.setIs_perfect_user(2);
		} else {
			// 注册完成
			dto.setIs_perfect_user(3);
		}
		return dto;
	}

	/**
	 * thirdPartLogin
	 *
	 * @param openId
	 * @param extType
	 * @param extName
	 * @param extPicture
	 * @return
	 */
	public User thirdPartLogin(String openId, String extType, String extName, String extPicture, String ip) {
		User user = userMapper.selectUserByUsername(openId);
		if (user == null) {
			// 不存在，则自动注册,如果是第三方登录的用户，默认为刚初始化，需要完善手机号码、宝宝信息，账户才能正常使用
			user = new User(openId, MD5.md5(Constants.TUYA_DEFAULT_PASS), new Date(), Constants.USER_NOW_INIT);
			user.setExt_open_id(openId);
			user.setExt_type(extType);
			user.setBaby_dob(Utility.formatStringToDate("yyyy-MM-dd", "1970-1-1"));
			user.setDisplay_name(extName.replaceAll("[\\ud800\\udc00-\\udbff\\udfff\\ud800-\\udfff]", "*"));
			user.setUserTel("");	// 手机号码默认为空

			RemoteIpInfoDTO dto = getLocation(ip);
			if (dto != null) {
				user.setLocation(dto.getCity());
			} else {
				user.setLocation("默认");
			}

			user.setDisplay_picture(extPicture);
			userMapper.insertUser(user);
		}
		// 获取token
		user.setToken(WebJsonTokenUtil.getToken(user.getId().intValue()));
		user.setPassword(null);
		if (!Constants.USER_NOW_INIT.equals(user.getStatus_())) {
			// 需要完善手机号码
			user.setUsername(user.getUserTel());
		}
		
		return user;
	}

	/**
	 * updateUserInfo
	 *
	 * @param user
	 * @param token
	 * @return
	 */
	public User updateUserInfo(User user, String token) {
		User userInfo = validateUserToken(token);
		if (userInfo == null) {
			return null;
		}
		/*if (!userInfo.getStatus_().equals(Constants.USER_SAVE_TEL)) {
			return null;
		}*/
		
		/**
		 * 修改宝宝信息，只需要修改三个字段，宝宝昵称、宝宝性别、宝宝生日，其中默认 修改状态
		 */
		if (user.getBaby_dob() != null) {
			user.setStatus_(Constants.USER_ACTIVE);
		}
		
		// 清楚token,防止修改
		user.setToken(null);
		// 修改
		user.setId(userInfo.getId());
		userMapper.updateUser(user);
		
		// 更新用户信息，并且返回
		userInfo.setPassword(null);
		userInfo.setBaby_dob(user.getBaby_dob());
		userInfo.setBaby_nickname(user.getBaby_nickname());
		userInfo.setBaby_gender(user.getBaby_gender());
		userInfo.setStatus_(Constants.USER_ACTIVE);
		userInfo.setToken(token);
		if(StringUtils.isNotEmpty(user.getDisplay_name())){
			userInfo.setDisplay_name(user.getDisplay_name());
		}
		return userInfo;
	}

	/**
	 * updateDisplayPicture
	 *
	 * @author Moon Cheng
	 * @param base64
	 * @param token
	 * @return
	 */
	public String updateDisplayPicture(String imageURL, String token) {
		User userInfo = validateUserToken(token);
		if (userInfo == null) {
			return null;
		}

		/*if (userMapper.updateUserAvator(userInfo.getId(), base64) < 1) {
			userMapper.insertUserAvator(userInfo.getId(), base64);
		}*/
	

		// final String BASE_URL = "http://localhost/imberry-api";
		int status = userMapper.updateDisplayPicture(imageURL, userInfo.getId());
		if (status < 1) {
			return "ERROR";
		}
		return imageURL;
	}

	/**
	 * changePhone
	 *
	 * @author Moon Cheng
	 * @param phone
	 * @param token
	 * @return
	 */
	public User changePhone(String phone, String token) {
		User userInfo = validateUserToken(token);
		if (userInfo == null) {
			return null;
		}
		//  修改绑定的手机号码
		User user = new User();
		user.setId(userInfo.getId());
		user.setUserTel(phone);

		userMapper.updateUser(user);
		userInfo = userMapper.selectUserById(userInfo.getId());
		userInfo.setPassword(null);
		return userInfo;
	}

	/**
	 * resetPassWord
	 *
	 * @param oldPassword
	 * @param newPassword
	 * @param token
	 * @return
	 */
	public int changePassword(String oldPassword, String newPassword, String token) {
		int status = -1;
		User userInfo = validateUserToken(token);
		if (userInfo == null) {
			return -1;
		}

		User user = userMapper.validateUser(userInfo.getUsername(), MD5.md5(oldPassword));
		if (user == null) {
			return 0;
		}
		
		status = userMapper.changePassword(user.getId(), MD5.md5(newPassword));
		return status;
	}

	/**
	 * changePassWord
	 *
	 * @param username,
	 *            newPassword
	 * @param session
	 * @return int
	 */
	public int resetPassWord(String username, String newPassword) {
		int status = 0;
		User user = userMapper.selectUserByUsername(username);
		if (user == null) {
			return -3;
		}
		status = userMapper.changePassword(user.getId(), MD5.md5(newPassword));
		return status;
	}

	public UserDTO tuyaConnect(User user) {
		UserDTO userInfo = new UserDTO(user.getId(), user.getUsername(), user.getPassword(), user.getToken(), user.getDisplay_name(),
				user.getDisplay_picture(), user.getCreated_on(), user.getExt_open_id(), user.getExt_name(), user.getExt_type(),
				user.getLocation(), user.getBaby_nickname(), user.getBaby_dob(), user.getBaby_gender(), user.getStatus_());
		userInfo.setPassword(null);
		try {
			userInfo.setEncryptUsername(AES.encrypt(user.getUsername()));
		} catch (Exception e) {
			e.printStackTrace();
		}
		userInfo.setUserCode(Constants.TUYA_DEFAULT_PASS);
		// Tuya connection
		TuyaConnector.TuyaSyncConnect(userInfo.getEncryptUsername(), userInfo.getUserCode());
		return userInfo;
	}

	/**
	 * getStartPage
	 *
	 * @return String
	 */
	public String getStartPage() {
		return userMapper.selectConfig("start_page");
	}

	/**
	 * getLocation
	 *
	 * @param ip
	 * @return String
	 */
	public RemoteIpInfoDTO getLocation(String ip) {
		RemoteIpInfoDTO remoteIpInfoDTO = new RemoteIpInfoDTO();
		if (ip.indexOf(",") != -1) {
			ip = ip.split(",")[0];
		}
		logger.info("IP为:" + ip);
		try {
			String result = HttpUtility.httpsGet(MessageFormat.format(ImberryConfig.SINA_IP_URL, ip));
			remoteIpInfoDTO = mapper.readValue(result, RemoteIpInfoDTO.class);
		} catch (Exception e) {
		}
		return remoteIpInfoDTO;
	}

	/**
	 * getApkVersion
	 *
	 * @return
	 */
	public String getApkVersion(){
		return userMapper.selectConfig("apk_version");
	}

	@Override
	public String selectUserAvator(Long id) {
		// TODO Auto-generated method stub
		return userMapper.selectUserAvator(id);
	}

	@Override
	public User selectUserByUsername(String username) {
		// TODO Auto-generated method stub
		return userMapper.selectUserByUsername(username);
	}

	@Override
	public List<User> getAll(int start, int end) {
		return null;
	}

}
