/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.renren.modules.app.service.impl;

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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.exception.RRException;
import io.renren.common.validator.Assert;
import io.renren.modules.app.dao.UserDao;
import io.renren.modules.app.entity.UserEntity;
import io.renren.modules.app.form.LoginForm;
import io.renren.modules.app.service.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

	@Override
	public UserEntity queryByUsername(String username) {
		return baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("username", username));
	}

	@Override
	public long login(LoginForm form) {
		UserEntity user = queryByUsername(form.getUsername());
		Assert.isNull(user, "账号或密码错误");
		//密码错误
		// if(!user.getPassword().equals(DigestUtils.sha256Hex(form.getPassword()))){
		if(!user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())){
			throw new RRException("账号或密码错误1");
		}

		return user.getUserId();
	}

	@Override
	@Transactional
    public void saveUser(UserEntity user){
        user.setCreateTime(new Date());
        //sha256加密
		String salt = RandomStringUtils.randomAlphanumeric(20);
		user.setPassword(new Sha256Hash(user.getPassword(), salt).toHex());
		user.setSalt(salt);
		this.save(user); 
	}

	@Override
	public List<Map<String, Object>> queryOrderList(Long memberId) {
		return baseMapper.queryOrderList(memberId);
	}

	@Override
	public Map<String, Object> queryOrderInfoByAttendersId(Long attendersId) {
		return baseMapper.queryOrderInfoByAttendersId(attendersId);
	}
}
