package com.uas.platform.b2b.service.impl;
import com.uas.sso.entity.UserView;
import com.uas.sso.util.AccountUtils;
import com.uas.platform.b2b.dao.*;
import com.uas.platform.b2b.model.*;
import com.uas.platform.b2b.service.UserService;
import com.uas.platform.b2b.support.*;
import com.uas.platform.core.model.Constant;
import com.uas.platform.core.model.PageInfo;
import com.uas.platform.core.model.Status;
import com.uas.platform.core.util.encry.Md5Utils;
import com.uas.search.b2b.model.SPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import java.util.*;

/**
 * @since 2016-9-26 21:18:35 账户中心统一管理；部分功能保留，但转移到v2目录
 * @see com.uas.platform.b2b.v2.service.impl.UserServiceImpl
 * 
 */
@Deprecated
@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserDao userDao;
	@Autowired
	private VendorDao vendorDao;
	@Autowired
	private DistributeDao distributeDao;

	static final String NUM_REGEXP= "^[0-9]*$";

	@Override
	public User save(User user) {
		user.setEnable(Constant.NO);
		user.setUserPwd(Md5Utils.encode(user.getUserPwd(), user.getUserUU()));
		user.setCurrentEnterprise();
		try {
			postToAccountCenter(user);
			return userDao.save(user);
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		}
	}

	@Override
	public User findUserByUserUU(Long uu) {
		List<User> users = userDao.findUserByUserUU(uu);
		if (users.size() == 0) {
			throw new UsernameNotFoundException("没有找到您的账号 " + uu);
		}
		return users.get(0);
	}

	@Override
	public User findUserByUserEmail(String email) {
		List<User> users = userDao.findUserByUserEmail(email);
		if (users.size() == 0) {
			throw new UsernameNotFoundException("没有找到您的账号 " + email);
		}
		return users.get(0);
	}

	@Override
	public User findUserByUserTel(String tel) {
		List<User> users = userDao.findUserByUserTel(tel);
		if (users.size() == 0) {
			throw new UsernameNotFoundException("没有找到您的账号 " + tel);
		} else {
			return users.get(0);
		}
	}

	@Override
	public List<User> findAll() {
		List<User> users = userDao.findByEnUU(SystemSession.getUser().getEnterprise().getUu());
		if(!CollectionUtils.isEmpty(users)) {
			for (User user : users) {
				Set<Role> roles = user.getRoles();
				Long enuu = SystemSession.getUser().getEnterprise().getUu();
				if(!CollectionUtils.isEmpty(roles)) {
					Iterator<Role> iterator = roles.iterator();
					while (iterator.hasNext()) {
						Role role = iterator.next();
						if(!role.getEnUU().equals(enuu)) {
							iterator.remove();
						}
					}
				}
			}
		}
		return users;
	}


	@Override
	public SPage<User> findByPageInfo(PageInfo pageInfo, String keyword) {
		Page<User> users = getUsersByPage(pageInfo, keyword);
		SPage<User> userInfos = new SPage<User>();
		if (!CollectionUtils.isEmpty(users.getContent())) {
			for (User user : users.getContent()) {
				Set<Role> roles = user.getRoles();
				Long enuu = SystemSession.getUser().getEnterprise().getUu();
				if (!CollectionUtils.isEmpty(roles)) {
					Iterator<Role> iterator = roles.iterator();
					while (iterator.hasNext()) {
						Role role = iterator.next();
						if (!role.getEnUU().equals(enuu)) {
							iterator.remove();
						}
					}
				}
			}
		}
		userInfos.setTotalPage(users.getTotalPages());
		userInfos.setSize(users.getSize());
		userInfos.setPage(users.getNumber());
		userInfos.setTotalElement(users.getTotalElements());
		userInfos.setContent(users.getContent());
		return userInfos;
	}

	private Page<User> getUsersByPage(final PageInfo pageInfo, String keyword) {
		Long enuu = SystemSession.getUser().getEnterprise().getUu();
		if(StringUtils.hasText(keyword)) {
		    if (keyword.matches(NUM_REGEXP)) {
                return userDao.findByEnUUAndKeyword(enuu, keyword.trim(), Long.valueOf(keyword.trim()), pageInfo);
            }
            return userDao.findByEnUUAndKeyword(enuu, keyword.trim(), pageInfo);
		} else {
			return userDao.findEnUUByAndPage(enuu, pageInfo);
		}
	}


	@Override
	public void postToAccountCenter(User user) throws Exception {
		UserView detail = new UserView();
		detail.setEmail(user.getUserEmail());
		detail.setIdCard(user.getUserIdcode());
		detail.setMobile(user.getUserTel());
		detail.setVipName(user.getUserName());
		detail.setSex(user.getUserSex());
		AccountUtils.saveUser(detail, null);
	}

	static final String defaultPassword = "111111";

	@Override
	public void removeUser(Long uu) {
		User user = userDao.findOne(uu);
		try {
			AccountUtils.removeUser(uu, SystemSession.getUser().getEnterprise().getUu());
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (user.getEnterprises().contains(SystemSession.getUser().getEnterprise())) {
			user.removeEnterprise(SystemSession.getUser().getEnterprise());
			if (user.getEnterprises().size() == 0) {
				user.setEnable((short) Status.DISABLED.value());
			}
			userDao.save(user);
			try {
				// 同步数据到账户中心
				AccountUtils.removeUser(user.getUserUU(), SystemSession.getUser().getEnterprise().getUu());
			} catch (Exception e) {
				// 尝试删除，存在关联的单据则不删
			}
		} else {
			throw new IllegalArgumentException();
		}
	}

	@Override
	public User findUserByEnUUAndUserUU(Long enUU, Long userUU) {
		List<User> users = userDao.findByEnUUAndUserUU(enUU, userUU);
		return CollectionUtils.isEmpty(users) ? null : users.get(0);
	}

	@Override
	public Boolean getDistribute(Long custUU) {
		List<Vendor> vendors = vendorDao.findByMyEnUUAndVendUU(custUU, SystemSession.getUser().getEnterprise().getUu());
		List<Distribute> distributes = distributeDao.findByUserUUAndVendorId(SystemSession.getUser().getUserUU(), vendors.get(0).getId());
		// 被分配了权限
		if (!CollectionUtils.isEmpty(distributes)) {
			return true;
		}
		return false;
	}

	@Override
	public List<Vendor> findChooseVendor(Long userUU) {
		List<Vendor> vendors = vendorDao.findByVendEnUU(SystemSession.getUser().getEnterprise().getUu());
		List<Vendor> vendors2 = new ArrayList<Vendor>();
		List<Distribute> distributes = distributeDao.findByUserUU(userUU);
		if (!CollectionUtils.isEmpty(distributes) && !CollectionUtils.isEmpty(vendors)) {
			for (Distribute d : distributes) {
				for (int i = 0; i < vendors.size(); i++) {
					if (d.getVendorId().equals(vendors.get(i).getId())) {
						vendors2.add(vendors.get(i));
					}
				}
			}
		}
		return vendors2;
	}

	@Override
	public SearchFilter distribute() {
		SearchFilter filter = null;
		Set<Role> roles = SystemSession.getUser().getRoles();
		boolean isSys = false;
		for (Role role : roles) {
			if (role.getIssys() == 1) {
				isSys = true;
				break;
			}
			if ("ROLE_SALEMANAGER".equals(role.getName())) {
				isSys = true;
				break;
			}
		}
		if (!SystemSession.getUser().isSys() && !isSys) {
			List<Vendor> vendors = findChooseVendor(SystemSession.getUser().getUserUU());
			List<Long> distributes = new ArrayList<Long>();
			filter = new SearchFilter();
			if (!CollectionUtils.isEmpty(vendors)) {
				for (Vendor v : vendors) {
					distributes.add(v.getMyEnUU());
				}
				filter.setDistribute(distributes);
			}
		}
		return filter;
	}

}