package com.iamberry.app.service;


import static com.iamberry.app.config.ImberryConfig.BASE_URL;

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.dao.DuplicateKeyException;
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.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) {
		String areacode = StringUtils.substringBefore(phone, ","); 
		phone = StringUtils.substringAfter(phone, ",");
		User user = new User(phone, MD5.md5(password), new Date(), Constants.USER_ACTIVE);
		
		user.setDisplay_name("Iamberry");
		user.setStatus_(Constants.USER_ACTIVE);
		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("未知");
			}
		}
		user.setCountry_code(areacode);
		user.setCreated_on(new Date());
		user.setIs_perfect_user(1);//标示用户有没有绑定手机号 1未绑定 2绑定
		userMapper.insertUser(user);

		String token = getEncToken(user.getId());
		userMapper.updateUserToken(token, 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.selectUserByExtOpenId(openId);
		if (user == null) {
			return null;
		}
		
		String areacode = StringUtils.substringBefore(phone, ",");
		phone = StringUtils.substringAfter(phone, ",");
		
		try {
			int status = userMapper.updateUserNameAndCountry(phone,areacode, user.getId());
			if (status > 0) {
				
				user.setUsername(phone);
				user.setPassword(null);
			} else {
				return null;
			}
			return user;
		} catch (DuplicateKeyException e) { // 报错，触发数据库唯一约束错误，系统捕获，而后对获取数据重头再来
			user.setPassword("EXTIES");
			logger.info("userinfo:" + user.toString());
			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
	 * @return
	 */
	public Object login(String phone, String password) {
		User user = userMapper.selectUserByUsername(phone);
		if (user == null) {
			return -1;
		}
		user = userMapper.validateUser(phone, MD5.md5(password));
		if (user == null) {
			return -2;
		}
		if (Constants.USER_INACTIVE.equals(user.getStatus_())) {
			return -3;
		}
		String token = getEncToken(user.getId());
		userMapper.updateUserToken(token, user.getId());

		user.setToken(token);
		user.setPassword(null);
		return tuyaConnect(user);
	}

	/**
	 * 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.selectUserByExtOpenId(openId);
		if (user == null) {
			user = new User(openId, MD5.md5(String.valueOf(System.currentTimeMillis())), new Date(), Constants.USER_ACTIVE);
			user.setExt_open_id(openId);
			user.setExt_type(extType);
			user.setBaby_dob(Utility.formatStringToDate("yyyy-MM-dd", "1970-1-1"));
			user.setIs_perfect_user(1);//是否完善用户信息 1.未完善。2.已完善
			user.setCountry_code("86");
			user.setDisplay_name(extName.replaceAll("[\\ud800\\udc00-\\udbff\\udfff\\ud800-\\udfff]", "*"));

			RemoteIpInfoDTO dto = getLocation(ip);
			if (dto != null) {
				user.setLocation(dto.getCity());
			}
			//user.setCountry_code(areacode);
			user.setDisplay_picture(extPicture);
			userMapper.insertUser(user);
		}

		String token = getEncToken(user.getId());
		userMapper.updateUserToken(token, user.getId());

		user.setToken(token);
		user.setPassword(null);
		return user;
	}

	/**
	 * updateUserInfo
	 *
	 * @param user
	 * @param token
	 * @return
	 */
	public User updateUserInfo(User user, String token) {
		User userInfo = validateUserToken(token);
		if (userInfo == null) {
			return null;
		}
		user.setId(userInfo.getId());
		userMapper.updateUser(user);
		user = userMapper.selectUserById(user.getId());

		user.setPassword(null);
		return user;
	}

	/**
	 * updateDisplayPicture
	 *
	 * @author Moon Cheng
	 * @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 "";
		}
		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;
		}
		userMapper.updateUserName(phone, userInfo.getId());
		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
	 * @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);
		userInfo.setCountry_code(user.getCountry_code());
		userInfo.setIs_perfect_user(user.getIs_perfect_user());
		try {
			userInfo.setEncryptUsername(AES.encrypt(user.getUsername()));
		} catch (Exception e) {
			e.printStackTrace();
		}
		userInfo.setUserCode("iamberry123");
		// Tuya connection
		TuyaConnector.TuyaSyncConnect(user.getCountry_code()+","+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);
	}

}
