package com.hai.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hai.dao.BsOrganizationMapper;
import com.hai.dao.SecUserMapper;
import com.hai.dao.SecUserMapperExt;
import com.hai.dao.SecUserRoleRelMapper;
import com.hai.entity.*;
import com.hai.model.SecUserModel;
import com.hai.model.UserTreeModel;
import com.hai.service.BsOrganizationService;
import com.hai.service.CommonService;
import com.hai.service.SecUserLabelService;
import com.hai.service.SecUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service("secUserService")
public class SecUserServiceImpl implements SecUserService {

	@Resource
	private SecUserMapper secUserMapper;

	@Resource
	private SecUserMapperExt secUserMapperExt;

	@Resource
	private BsOrganizationMapper bsOrganizationMapper;

	@Resource
	private SecUserRoleRelMapper secUserRoleRelMapper;

	@Resource
	private BsOrganizationService bsOrganizationService;

	@Resource
	private SecUserLabelService userLabelService;

	@Resource
	private CommonService commonService;

	@Override
	@Transactional
	public void addUser(SecUser user) {
		secUserMapper.insert(user);
		// 用户角色关系
		if(user.getRoleId() != null && user.getId() != null){
			SecUserRoleRelExample exp = new SecUserRoleRelExample();
			exp.createCriteria().andUserIdEqualTo(user.getId());
			List<SecUserRoleRel> rels = secUserRoleRelMapper.selectByExample(exp);
			if(rels != null && rels.size() != 0){
				for(SecUserRoleRel rel : rels){
					secUserRoleRelMapper.deleteByPrimaryKey(rel.getId());
				}
			}
			SecUserRoleRel rel = new SecUserRoleRel();
			rel.setRoleId(user.getRoleId());
			rel.setUserId(user.getId());
			secUserRoleRelMapper.insert(rel);
		}
		// 如果用户被设为部门管理员
		if (user.isManager()) {
			BsOrganization organization = bsOrganizationMapper.selectByPrimaryKey(user.getOrganizationId());
			organization.setManagerId(user.getId());
			organization.setManagerName(user.getUserName());
			organization.setManagerPhone(user.getTelephone());
			bsOrganizationMapper.updateByPrimaryKey(organization);
		}
		if (user.getLabelIdArray() != null) {
			for (Long labelId : user.getLabelIdArray()) {
				String labelName = commonService.getDictionaryCodeName("USER_LABEL", labelId.toString());
				if (labelName != null) {
					SecUserLabel label = new SecUserLabel();
					label.setUserId(user.getId());
					label.setLabelId(labelId);
					label.setLabelName(labelName);
					userLabelService.edit(label);
				}
			}
		}
	}

	@Override
	public void updateUser(SecUser secUser) {
		secUserMapper.updateByPrimaryKey(secUser);
	}

	@Override
	public SecUser findById(Long userId) {
		return secUserMapper.selectByPrimaryKey(userId);
	}

	@Override
	public SecUser userLogin(String loginName, String password) {
		return secUserMapperExt.login(loginName,password);
	}

	@Override
	public SecUser findByPhone(String phone) {
		if (StringUtils.isBlank(phone)){
			return null;
		}
		SecUserExample example = new SecUserExample();
		example.createCriteria().andTelephoneEqualTo(phone).andStatusEqualTo(1);
		List<SecUser> users = secUserMapper.selectByExample(example);
		if (users != null && users.size() != 0) {
			return users.get(0);
		}
		return null;
	}

	@Override
	public SecUser findByLoginName(String loginName) {
		SecUserExample example = new SecUserExample();
		example.createCriteria().andLoginNameEqualTo(loginName).andStatusEqualTo(1);
		List<SecUser> users = secUserMapper.selectByExample(example);
		if (users != null && users.size() != 0) {
			return users.get(0);
		}
		return null;
	}

	@Override
	public SecUser findByOpenId(String openId) {
		if (StringUtils.isBlank(openId)){
			return null;
		}
		SecUserExample example = new SecUserExample();
		example.createCriteria().andExt1EqualTo(openId).andStatusEqualTo(1);
		List<SecUser> users = secUserMapper.selectByExample(example);
		if (users != null && users.size() != 0) {
			return users.get(0);
		}
		return null;
	}

	@Override
	public SecUser selectAdminUser(Long companyId) {
		SecUserExample example = new SecUserExample();
		example.createCriteria().andCompanyIdEqualTo(companyId).andAdminFlagEqualTo(1);
		List<SecUser> userList = secUserMapper.selectByExample(example);
		if (userList != null && userList.size() == 1) {
			return userList.get(0);
		}else {
			return null;
		}
	}

	@Override
	public PageInfo<SecUserModel> findPage(Long companyId, Long organizationId, String userName, String phone, Integer pageNum, Integer pageSize) {
		PageHelper.startPage(pageNum,pageSize);
		return  new PageInfo<SecUserModel>(secUserMapper.findPage(companyId,organizationId,userName,phone));
	}

	@Override
	@Transactional
	public void modifyUser(SecUser user) {
		// 是否更换部门
		SecUser secUser = secUserMapper.selectByPrimaryKey(user.getId());
		if (secUser.getOrganizationId() != null && (!secUser.getOrganizationId().equals(user.getOrganizationId()) || user.getStatus() == 0)) {
			BsOrganization organization = bsOrganizationMapper.selectByPrimaryKey(secUser.getOrganizationId());
			// 更换前是部门管理员的，去除管理员
			// 删除用户的，去除管理员
			if (secUser.getId().equals(organization.getManagerId())) {
				organization.setManagerId(null);
				organization.setManagerName(null);
				organization.setManagerPhone(null);
				bsOrganizationMapper.updateByPrimaryKey(organization);
			}
		}

		secUserMapper.updateByPrimaryKeySelective(user);
		// 删除原来关系
		SecUserRoleRelExample exp = new SecUserRoleRelExample();
		exp.createCriteria().andUserIdEqualTo(user.getId());
		List<SecUserRoleRel> rels = secUserRoleRelMapper.selectByExample(exp);
		if(rels != null && rels.size() != 0){
			for(SecUserRoleRel rel : rels){
				secUserRoleRelMapper.deleteByPrimaryKey(rel.getId());
			}
		}
		if(user.getRoleId() != null && user.getId() != null && user.getStatus() != 0){
			SecUserRoleRel rel = new SecUserRoleRel();
			rel.setUserId(user.getId());
			rel.setRoleId(user.getRoleId());
			secUserRoleRelMapper.insert(rel);
		}
		// 删除用户原来标签
		List<SecUserLabel> labelList = userLabelService.getLabelByUser(secUser.getId());
		for (SecUserLabel label : labelList) {
			label.setStatus(0);
			userLabelService.edit(label);
		}

		if (user.getLabelIdArray() != null) {
			for (Long labelId : user.getLabelIdArray()) {
				String labelName = commonService.getDictionaryCodeName("USER_LABEL", labelId.toString());
				if (labelName != null) {
					SecUserLabel label = new SecUserLabel();
					label.setUserId(user.getId());
					label.setLabelId(labelId);
					label.setLabelName(labelName);
					userLabelService.edit(label);
				}
			}
		}
	}

	@Override
	public SecUser getMainAccount(Integer objectType, Long objectId) {
		SecUserExample example = new SecUserExample();
		example.createCriteria().andAdminFlagEqualTo(1).andObjectTypeEqualTo(objectType).andObjectIdEqualTo(objectId);

		List<SecUser> list = secUserMapper.selectByExample(example);
		if (list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public List<SecUser> findUserList(Long organizationId, String phone) {
		SecUserExample example = new SecUserExample();
		SecUserExample.Criteria criteria = example.createCriteria();

		if(organizationId != null){
			criteria.andOrganizationIdEqualTo(organizationId);
		}

		if (StringUtils.isNotBlank(phone)) {
			criteria.andTelephoneLike("%" + phone + "%");
		}
		criteria.andStatusEqualTo(1);
		example.setOrderByClause("create_time desc");
		return secUserMapper.selectByExample(example);
	}


	@Override
	public UserTreeModel findAttendUserTree(Long companyId, BsOrganization organization) {
		// 查询公司下全部子级部门
		List<BsOrganization> organizationList = bsOrganizationService.findAllSon(companyId);
		UserTreeModel userTreeModel = new UserTreeModel();
		userTreeModel.setTitle(organization.getName());
		userTreeModel.setKey("o" + organization.getId());
		userTreeModel.setType(false);
		//构建树
		buildAttendUserTree(userTreeModel,organizationList);
		return userTreeModel;
	}

	@Override
	public List<SecUser> getMerchantStoreUser(Long merchantStoreId) {
		SecUserExample example = new SecUserExample();
		example.createCriteria().andObjectTypeEqualTo(3).andObjectIdEqualTo(merchantStoreId).andStatusEqualTo(1);
		return secUserMapper.selectByExample(example);
	}

	//构建考勤员工树
	public void buildAttendUserTree(UserTreeModel parent, List<BsOrganization> organizations) {
		// 查询部门下员工
		List<SecUser> userList = findUserList(Long.valueOf(parent.getKey().substring(1)),null);
		for (SecUser secUser : userList) {
			UserTreeModel child = new UserTreeModel();
			child.setKey(secUser.getId().toString());
			child.setTitle(secUser.getUserName());
			child.setType(true);
			child.setPhone(secUser.getTelephone());
			parent.add(child);
		}
		organizations.forEach(organization -> {
			if (organization.getParentId().toString().equals(parent.getKey().substring(1))) {
				UserTreeModel child = new UserTreeModel();
				child.setKey("o" + organization.getId());
				child.setTitle(organization.getName());
				child.setType(false);
				parent.add(child);
				buildAttendUserTree(child, organizations);
			}
		});
	}
}
