package com.huatek.frame.base.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.huatek.frame.base.dto.UserDTO;
import com.huatek.frame.base.entity.Group;
import com.huatek.frame.base.entity.User;
import com.huatek.frame.base.entity.UserRole;
import com.huatek.frame.base.mapper.GroupDao;
import com.huatek.frame.base.mapper.UserDao;
import com.huatek.frame.base.mapper.UserMapper;
import com.huatek.frame.base.mapper.UserRoleDao;
import com.huatek.frame.base.service.UserService;
import com.huatek.frame.base.util.Constants;
import com.huatek.frame.base.util.PhoneUtils;
import com.huatek.frame.base.vo.UserVO;
import com.huatek.torch.frame.tools.ConstantUtil;
import com.huatek.torch.frame.tools.ResultUtil;
import com.huatek.torch.sql.beans.WherePrams;
import com.huatek.torch.sql.where.W;
import com.huatek.torch.util.date.TimeUtil;
import com.huatek.torch.util.md5.Md5;
import com.huatek.torch.util.tools.HuatekTools;
import com.huatek.torch.util.uuid.Uuid;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统_用户 ServiceImpl
 *
 * @author key_dong
 * @date 2018-7-11 14:03:46
 */
@Component
@Service(interfaceClass = UserService.class)
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {
	@Value("${base.user.remote.aadd}")
	private String remoteUserAdd;

	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private UserDao userDao;
	
	@Autowired
	private UserRoleDao userRoleDao;
	
	@Autowired
	private GroupDao groupDao;
	
	@Autowired
	private RestTemplate restTemplate;
	@Override
//	@Cacheable(value="common",keyGenerator ="keyGenerator")
	public Map<String, Object> findUserPage(UserDTO dto) {
		PageHelper.startPage(dto.getPage(), dto.getLimit());
		dto.setDeleted(Constants.DEFAULT_NO);
		Page<UserVO> users = userMapper.selectUserPage(dto);
		return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, users.getTotal(), "", users.getResult());
	}

	@Override
//	@CachePut(value="common",key="'User_'+#entity.getId()")
	public Map<String, Object> addUser(User entity) { 
//		Map<String,Object> map = new HashMap<String,Object>();

		// 电话
		if(!PhoneUtils.isFixedTel(entity.getUserPhone())){
			return ResultUtil.put(ConstantUtil.REQUEST_FAIL, "USER.TEL.ERROR", "");
		}

		// 手机号码
		if(!PhoneUtils.isValidChinesePhone(entity.getUserMobile())){
			return ResultUtil.put(ConstantUtil.REQUEST_FAIL, "USER.PHONE.ERROR", "");
		}

		// 邮箱
		if(!PhoneUtils.isEmail(entity.getUserEmail())){
			return ResultUtil.put(ConstantUtil.REQUEST_FAIL, "USER.MAILBOX.ERROR", "");
		}

		List<User> lists = userDao.list(new WherePrams().where("user_code", entity.getUserCode()).and("deleted", "0"));
		if (!ObjectUtils.isEmpty(lists)) {
			return ResultUtil.put(ConstantUtil.REQUEST_FAIL, "USER.USERCODE.REPETITION", "");
		}	

		lists = userDao.list(new WherePrams().where("user_name", entity.getUserName()).and("deleted", "0"));
		if (!ObjectUtils.isEmpty(lists)) {
			return ResultUtil.put(ConstantUtil.REQUEST_FAIL, "USER.USERNAME.REPETITION", "");
		}	

		lists = userDao.list(new WherePrams().where("user_mobile", entity.getUserMobile()).and("deleted", "0"));
		if (!ObjectUtils.isEmpty(lists)) {
			return ResultUtil.put(ConstantUtil.REQUEST_FAIL, "USER.USERMOBILE.REPETITION", "");
		}	

		lists = userDao.list(new WherePrams().where("user_email", entity.getUserEmail()).and("deleted", "0"));
		if (!ObjectUtils.isEmpty(lists)) {
			return ResultUtil.put(ConstantUtil.REQUEST_FAIL, "USER.USEREMAIL.REPETITION", "");
		}

		entity.setId(Uuid.getUUID());
		entity.setCreateTime(TimeUtil.getLocalDateTime());
		entity.setLanguageType(Constants.CHINA_CN);
		entity.setDeleted(Constants.DEFAULT_NO);
		String salt = Uuid.getUUID();
		entity.setPasswordSalt(salt);
		String passWord = Md5.getMD5Code(salt+Constants.DEFAULT_PASSWORD);
		entity.setPassword(passWord);
		userDao.addLocal(entity);
//		return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "USER.INSERT.SUCCESS", "");

		Map<String, Object> map = new HashMap<>();
		// TODO 调用声级振动接口
		map.put("userName", entity.getUserName());
		map.put("email", entity.getUserEmail());
		map.put("phone", entity.getUserMobile());
		map.put("password", Constants.DEFAULT_PASSWORD);

		boolean flag = addUserRemote(map);
		if(flag) {
			userDao.addLocal(entity);
			return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "", "");
		} else {
			return ResultUtil.put(ConstantUtil.REQUEST_FAIL, "", "");
		}
	}

	@Override
//	@Cacheable(value="common",key="'User_'+#id")
	public Map<String, Object> findUser(String id) {
		UserVO vo = new UserVO();
		if (!HuatekTools.isEmpty(id)) {
			User entity = userDao.get(id);
			BeanUtils.copyProperties(entity, vo);
		}  
		WherePrams where = new WherePrams();
		where.where("deleted", Constants.DEFAULT_NO); 
		List<Group> datas = groupDao.list(where);
		vo.setDatas(datas);
		return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "", vo);  
	}

	@Override
//	@CacheEvict(value="common",key="'User_'+#entity.getId()")
	public Map<String, Object> modifyUser(User entity) {

		// 电话
		if(!PhoneUtils.isFixedTel(entity.getUserPhone())){
			return ResultUtil.put(ConstantUtil.REQUEST_FAIL, "USER.TEL.ERROR", "");
		}

		// 手机号码
		if(!PhoneUtils.isValidChinesePhone(entity.getUserMobile())){
			return ResultUtil.put(ConstantUtil.REQUEST_FAIL, "USER.PHONE.ERROR", "");
		}

		// 邮箱
		if(!PhoneUtils.isEmail(entity.getUserEmail())){
			return ResultUtil.put(ConstantUtil.REQUEST_FAIL, "USER.MAILBOX.ERROR", "");
		}
		
		List<User> lists = userDao.list(new WherePrams().where("user_code", entity.getUserCode()).and("id", W.NE, entity.getId()));
		if (!ObjectUtils.isEmpty(lists)) {
			return ResultUtil.put(ConstantUtil.JWT_CODE_FAIL, "USER.USERCODE.REPETITION", "");
		}	
		  lists = userDao.list(new WherePrams().where("user_name", entity.getUserName()).and("id", W.NE, entity.getId()));
		if (!ObjectUtils.isEmpty(lists)) {
			return ResultUtil.put(ConstantUtil.JWT_CODE_FAIL, "USER.USERNAME.REPETITION", "");
		}	
		 lists = userDao.list(new WherePrams().where("user_mobile", entity.getUserMobile()).and("id", W.NE, entity.getId()));
		if (!ObjectUtils.isEmpty(lists)) {
			return ResultUtil.put(ConstantUtil.JWT_CODE_FAIL, "USER.USERMOBILE.REPETITION", "");
		}	
		 lists = userDao.list(new WherePrams().where("user_email", entity.getUserEmail()).and("id", W.NE, entity.getId()));
		if (!ObjectUtils.isEmpty(lists)) {
			return ResultUtil.put(ConstantUtil.JWT_CODE_FAIL, "USER.USEREMAIL.REPETITION", "");
		}
		
		String id = entity.getId();
		String groupId = entity.getGroupId();		
		User user = userDao.get(id);
		String gId = user.getGroupId();
		if(gId==null && groupId!=null)
		{
			entity.setUpdateTime(TimeUtil.getLocalDateTime());
			userDao.updateLocal(entity);
			return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "", "");
		}
		
		if(!gId.equals(groupId)){
			WherePrams where=new WherePrams();
			where.where("uid", id);
			userRoleDao.del(where);				
		}		
		entity.setUpdateTime(TimeUtil.getLocalDateTime());
		userDao.updateLocal(entity);
		return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "", "");
	}

	@Override
//	@CacheEvict(value="common",key="User_Page_*")
	public Map<String, Object> deleteUser(String[] ids) {
		for (String id : ids) {
			User entity = new User();
			entity.setDeleted(Constants.DEFAULT_YES);
			entity.setId(id);
			userDao.updateLocal(entity);
		}
		return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "", "");
	}

	@Override
	public Map<String, Object> updateUserRole(String uid, String[] rids) {
		WherePrams where=new WherePrams();
		where.where("uid", uid);
		userRoleDao.del(where);	
		List<UserRole> collections=new ArrayList<>(2);
		for (String pid : rids) {	
			UserRole collection=new UserRole();	
			collection.setUid(uid);
			collection.setRoleId(pid);
			collections.add(collection);
		}
		userRoleDao.add(collections);
		return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "", "");
	}

	@Override
	public List<User> findUsers() {
		List<User> lists = userDao.list(new WherePrams().where("deleted",Constants.DEFAULT_NO));
		return lists;
	}

	@Override
	public List<UserRole> findUserRoles() {
		List<UserRole> userRoles = userRoleDao.list(new WherePrams());
		return userRoles;
	}

	@Override
	public Page<UserVO> getUserByRoleId(String roleId,int page,int limit) {
		Map<String, Object> map=new HashMap<>();
		map.put("deleted",Constants.DEFAULT_NO);
		map.put("roleId",roleId);
		 PageHelper.startPage(page, limit);
		 Page<UserVO>  vos = userMapper.getUserByRoleId(map);
		return vos;
	}

	@Override
	public Map<String, Object> addRemoteUser(User entity) {
		
		System.out.println("-----------------------addRemoteUser------------------------------");
		List<User> lists = userDao.list(new WherePrams().where("user_code", entity.getUserCode()));
		if (!ObjectUtils.isEmpty(lists)) {
			return ResultUtil.put(ConstantUtil.JWT_CODE_FAIL, "USER.USERCODE.REPETITION", "");
		}	
		  lists = userDao.list(new WherePrams().where("user_name", entity.getUserName()));
		if (!ObjectUtils.isEmpty(lists)) {
			return ResultUtil.put(ConstantUtil.JWT_CODE_FAIL, "USER.USERNAME.REPETITION", "");
		}	
		 lists = userDao.list(new WherePrams().where("user_mobile", entity.getUserMobile()));
		if (!ObjectUtils.isEmpty(lists)) {
			return ResultUtil.put(ConstantUtil.JWT_CODE_FAIL, "USER.USERMOBILE.REPETITION", "");
		}	
		 lists = userDao.list(new WherePrams().where("user_email", entity.getUserEmail()));
		if (!ObjectUtils.isEmpty(lists)) {
			return ResultUtil.put(ConstantUtil.JWT_CODE_FAIL, "USER.USEREMAIL.REPETITION", "");
		}
		
		System.out.println("/////////////////////////////////////////////////////");
		entity.setId(Uuid.getUUID());
		entity.setCreateTime(TimeUtil.getLocalDateTime());
		entity.setLanguageType(Constants.CHINA_CN);
		entity.setDeleted(Constants.DEFAULT_NO);
		String salt = Uuid.getUUID();
		entity.setPasswordSalt(salt);
		String passWord=Md5.getMD5Code(salt+Constants.DEFAULT_PASSWORD);
		entity.setPassword(passWord);
		System.out.println("-----------------------addRemoteUser   begin------------------------------");
		userDao.addLocal(entity);
		
		System.out.println("-----------------------addRemoteUser   end------------------------------");
		return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "", "");
	}
	
	public boolean addUserRemote(Map<String, Object> map) {
		try {
			HttpHeaders httpHeaders = new HttpHeaders();
			httpHeaders.setContentType(MediaType.parseMediaType(MediaType.APPLICATION_JSON_UTF8_VALUE));
//        Map<String, Object> param = new HashMap<String, Object>();
//        param.put("参数1", "值1");
//        param.put("参数2", "值2");
			HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(map, httpHeaders);

			restTemplate.postForEntity(remoteUserAdd, httpEntity,
					Object.class);
			
			
//			Object forObject = restTemplate.postForEntity("http://192.168.135.81:8081/remote/user/addUser", httpEntity,
//					Object.class);
			return true;
		} catch (RestClientException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}
}