package com.goafanti.user.service.impl;

import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.dao.OrganizationIdentityMapper;
import com.goafanti.common.dao.UserIdentityMapper;
import com.goafanti.common.dao.UserMapper;
import com.goafanti.common.enums.UserType;
import com.goafanti.common.model.OrganizationIdentity;
import com.goafanti.common.model.User;
import com.goafanti.common.model.UserIdentity;
import com.goafanti.common.utils.DateUtils;
import com.goafanti.core.mybatis.BaseMybatisDao;
import com.goafanti.core.mybatis.page.Pagination;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.user.bo.OrgListBo;
import com.goafanti.user.bo.OrgPartnerDetailBo;
import com.goafanti.user.bo.OrgUnitNames;
import com.goafanti.user.bo.StarAndExpertListBo;
import com.goafanti.user.bo.StarListBo;
import com.goafanti.user.bo.UserBasicInfo;
import com.goafanti.user.bo.UserDownLoadBo;
import com.goafanti.user.bo.UserNames;
import com.goafanti.user.bo.UserPartnerDetailBo;
import com.goafanti.user.service.UserService;

@Service
public class UserServiceImpl extends BaseMybatisDao<UserMapper> implements UserService {
	@Autowired
	private UserMapper						userMapper;
	@Autowired
	private OrganizationIdentityMapper		organizationIdentityMapper;
	@Autowired
	private UserIdentityMapper				userIdentityMapper;

	@Override
	@Transactional
	public User insertRegister(User user, String unitName, String userName) {
		userMapper.insert(user);
		if (null != user.getType() && UserType.ORGANIZATION.getCode().equals(user.getType())) {
			OrganizationIdentity organizationIdentity = new OrganizationIdentity();
			organizationIdentity.setUid(user.getId());
			organizationIdentity.setUnitName(StringUtils.isBlank(unitName) ? "" : unitName);
			organizationIdentity.setId(UUID.randomUUID().toString());
			organizationIdentity.setIdentityType(0);
			organizationIdentity.setAuditStatus(0);
			organizationIdentity.setProcess(0);
			organizationIdentity.setWrongCount(0);
			organizationIdentity.setListed(0);
			organizationIdentity.setListedType(0);
			organizationIdentityMapper.insert(organizationIdentity);
		}
		if (null != user.getType() && UserType.PERSONAL.getCode().equals(user.getType())) {
			UserIdentity ui = new UserIdentity();
			ui.setId(UUID.randomUUID().toString());
			ui.setUid(user.getId());
			ui.setAuditStatus(0);
			ui.setProcess(0);
			ui.setWrongCount(0);
			ui.setUsername(StringUtils.isBlank(userName) ? "" : userName);
			userIdentityMapper.insert(ui);
		}

		return user;
	}

	@Override
	public User selectByMobieAndType(String mobile, Integer type) {
		return userMapper.selectByMobieAndType(mobile, type);
	}

	@Override
	public User selectByPrimaryKey(String id) {
		return userMapper.selectByPrimaryKey(id);
	}

	@Override
	public int updateByPrimaryKeySelective(User u) {
		return userMapper.updateByPrimaryKeySelective(u);
	}

	@Override
	public User insert(User user) {
		userMapper.insert(user);
		return user;
	}

	

	@Override
	public UserDownLoadBo selectUserDownLoadBoByUserId(String id) {
		return userMapper.selectUserDownLoadBoByUserId(id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<OrgListBo> selectUserByAid(Integer number, String mobile, Integer auditStatus, String auditName,
			String email, String aid, String startCreateTime, String endCreateTime, Integer type, Integer pageNo,
			Integer pageSize) {
		Map<String, Object> params = new HashMap<>();

		if (StringUtils.isNotBlank(startCreateTime)) {
			try {
				params.put("startCreateTime", DateUtils.parseDate(startCreateTime, AFTConstants.YYYYMMDD));
			} catch (ParseException e) {
			}
		}

		if (StringUtils.isNotBlank(endCreateTime)) {
			try {
				params.put("endCreateTime",
						DateUtils.addDays(DateUtils.parseDate(endCreateTime, AFTConstants.YYYYMMDD), 1));
			} catch (ParseException e) {
			}
		}

		if (null != number) {
			params.put("number", number);
		}

		if (StringUtils.isNotBlank(mobile)) {
			params.put("mobile", mobile);
		}

		if (null != auditStatus) {
			params.put("auditStatus", auditStatus);
		}

		if (StringUtils.isNotBlank(auditName)) {
			params.put("auditName", auditName);
		}

		if (StringUtils.isNotBlank(email)) {
			params.put("email", email);
		}

		if (!TokenManager.hasRole(AFTConstants.SUPERADMIN)) {
			params.put("aid", aid);
		}

		if (pageNo == null || pageNo < 0) {
			pageNo = 1;
		}

		if (pageSize == null || pageSize < 0 || pageSize > 10) {
			pageSize = 10;
		}

		if (UserType.PERSONAL.getCode().equals(type)) {
			return (Pagination<OrgListBo>) findPage("findUserByAidWithParamsListByPage", "findUserByAidWithParamsCount",
					params, pageNo, pageSize);
		} else if (UserType.ORGANIZATION.getCode().equals(type)) {
			return (Pagination<OrgListBo>) findPage("findOrgByAidWithParamsListByPage", "findOrgByAidWithParamsCount",
					params, pageNo, pageSize);
		}
		return null;
	}

	@Override
	public List<OrgUnitNames> selectDemandUnitNames() {
		String aid = TokenManager.getAdminId();
		if (TokenManager.hasRole(AFTConstants.MANAGERADMIN)) {
			return organizationIdentityMapper.selectManagerUnitNames(aid);
		} else {
			if (TokenManager.hasRole(AFTConstants.SUPERADMIN)) {
				aid = null;
			}
			return organizationIdentityMapper.selectAllOrgIndentity(aid);
		}
	}

	@Override
	public List<UserNames> selectDemandUserNames() {
		String aid = TokenManager.getAdminId();
		if (TokenManager.hasRole(AFTConstants.MANAGERADMIN)) {
			return userIdentityMapper.selectManagerUserNames(aid);
		} else {
			if (TokenManager.hasRole(AFTConstants.SUPERADMIN)) {
				aid = null;
			}
			return userIdentityMapper.selectAllUserNames(aid);
		}
	}





	

	@Override
	public String findUserNameByNameAndMobile(String name, String mobile) {
		return userMapper.findUserByNameAndMobile(name, mobile);
	}

	@Override
	public String findOrgNameByNameAndMobile(String name, String mobile) {
		return userMapper.findOrgByNameAndMobile(name, mobile);
	}

	@Override
	public UserPartnerDetailBo findUserPartnerDetail(String uid) {
		return userMapper.findUserPartnerDetail(uid);
	}

	@Override
	public OrgPartnerDetailBo findOrgPartnerDetail(String uid) {
		return userMapper.findOrgPartnerDetail(uid);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<StarListBo> listStar(Integer number, String engagedField, String username,
			String professionalTitle, String workUnit, Integer pNo, Integer pSize) {
		Map<String, Object> params = new HashMap<>();

		if (null != number) {
			params.put("number", number);
		}

		if (StringUtils.isNotBlank(engagedField)) {
			params.put("engagedField", engagedField);
		}

		if (StringUtils.isNotBlank(username)) {
			params.put("username", username);
		}

		if (StringUtils.isNotBlank(professionalTitle)) {
			params.put("professionalTitle", professionalTitle);
		}

		if (StringUtils.isNotBlank(workUnit)) {
			params.put("workUnit", workUnit);
		}

		if (pNo == null || pNo < 0) {
			pNo = 1;
		}

		if (pSize == null || pSize < 0 || pSize > 10) {
			pSize = 10;
		}
		return (Pagination<StarListBo>) findPage("findStarListByPage", "findStarCount", params, pNo, pSize);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<StarAndExpertListBo> listStarAndExpert(Integer number, String engagedField, String username,
			String professionalTitle, String workUnit, Integer pNo, Integer pSize) {
		Map<String, Object> params = new HashMap<>();

		if (null != number) {
			params.put("number", number);
		}

		if (StringUtils.isNotBlank(engagedField)) {
			params.put("engagedField", engagedField);
		}

		if (StringUtils.isNotBlank(username)) {
			params.put("username", username);
		}

		if (StringUtils.isNotBlank(professionalTitle)) {
			params.put("professionalTitle", professionalTitle);
		}

		if (StringUtils.isNotBlank(workUnit)) {
			params.put("workUnit", workUnit);
		}

		if (pNo == null || pNo < 0) {
			pNo = 1;
		}

		if (pSize == null || pSize < 0 || pSize > 10) {
			pSize = 10;
		}
		return (Pagination<StarAndExpertListBo>) findPage("findStarAndExpertListByPage", "findStarAndExpertCount",
				params, pNo, pSize);
	}

	@Override
	@Cacheable(value = "UserNumberCache", key = "'UserNumberCache:UID:'+#userId")
	public String selectNumberByPrimaryKey(String userId) {
		return String.valueOf(userMapper.selectNumberByPrimaryKey(userId));
	}

	@Override
	public List<UserPartnerDetailBo> findUserPartner() {
		return userMapper.findUserPartner();
	}

	@Override
	public UserBasicInfo selectBaseInfo() {
		if(TokenManager.getToken() instanceof User)return userMapper.selectBaseInfo(TokenManager.getUserId());
		return null;
	}

	@Override
	public User selectByNumber(String easemobName) {
		
		return userMapper.selectByNumber(easemobName);
	}
	
	@Override
	public List<User> selectUserByRoleName(String roleName1,String roleName2){
		return userMapper.selectUserByRoleName(roleName1,roleName2);
	}
	
	
}
