package com.ym.mec.auth.service.impl;

import java.util.Date;
import java.util.List;

import com.ym.mec.auth.api.enums.YesOrNoEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ym.mec.auth.api.dto.SysUserInfo;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.auth.dal.dao.SysUserDao;
import com.ym.mec.auth.service.SysRoleMenuService;
import com.ym.mec.auth.service.SysUserRoleService;
import com.ym.mec.auth.service.SysUserService;
import com.ym.mec.common.dal.BaseDAO;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.common.service.impl.BaseServiceImpl;

@Service
public class SysUserServiceImpl extends BaseServiceImpl<Integer, SysUser> implements SysUserService {

	@Autowired
	private SysUserDao sysUserDao;

	@Autowired
	private SysUserRoleService sysUserRoleService;

	@Autowired
	private SysRoleMenuService sysRoleMenuService;

	@Override
	public BaseDAO<Integer, SysUser> getDAO() {
		return sysUserDao;
	}

	@Override
	public SysUser queryByUsername(String username) {
		return sysUserDao.queryByUsername(username);
	}

	@Override
	public SysUser queryByPhone(String phone) {
		return sysUserDao.queryByPhone(phone);
	}

	@Override
	public SysUserInfo queryUserInfoByUsername(String username) {
		SysUser sysUser = queryByUsername(username);
		return getSysUserInfo(sysUser);
	}

	@Override
	public SysUserInfo queryUserInfoByPhone(String phone) {
		SysUser sysUser = queryByPhone(phone);
		return getSysUserInfo(sysUser);
	}

	private SysUserInfo getSysUserInfo(SysUser sysUser) {
		if (sysUser == null) {
			return null;
		}
		SysUserInfo userInfo = new SysUserInfo();
		userInfo.setSysUser(sysUser);

		List<String> roleCodeList = sysUserRoleService.queryRoleCodeListByUserId(sysUser.getId());
		userInfo.setRoles(roleCodeList.toArray(new String[roleCodeList.size()]));

		List<Integer> roleIdList = sysUserRoleService.queryRoleIdListByUserId(sysUser.getId());
		List<String> permissionList = sysRoleMenuService.queryPermissionsByRoleIdList(roleIdList);

		userInfo.setPermissions(permissionList.toArray(new String[permissionList.size()]));

		return userInfo;
	}

	@Override
	public boolean deleteById(Integer id) {
		SysUser user = get(id);

		if (user == null) {
			throw new BizException("账户不存在");
		}

		user.setUpdateTime(new Date());
		user.setDelFlag(YesOrNoEnum.YES);

		update(user);

		return true;
	}

	@Override
	public void updatePassword(String mobile, String password) {
		sysUserDao.updatePassword(mobile,password);
	}

}