package com.lightinit.hsdataportal.impl;

import com.lightinit.hsdataportal.entity.User;
import com.lightinit.hsdataportal.entity.UserExample;
import com.lightinit.hsdataportal.mapper.UserMapper;
import com.lightinit.hsdataportal.model.ResultState;
import com.lightinit.hsdataportal.model.ResultStateCode;
import com.lightinit.hsdataportal.service.IUserService;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author: sunxiang
 * @Date: 2019/4/8 14:32
 * @Description:
 **/
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Override
    public String getForgetPasswordCode(String username) {
        UserExample userExample = new UserExample();
        userExample.createCriteria().andUsernameEqualTo(username);
        List<User> list = userMapper.selectByExample(userExample);
        if(list!=null && list.size()>0){
            return list.get(0).getPhone();
        }
        return null;
    }

    @Transactional
    @Override
    public ResultState forgetPassword(String username, String password) {
        ResultState<Object> state = new ResultState<>();
        UserExample userExample = new UserExample();
        userExample.createCriteria().andUsernameEqualTo(username);
        List<User> list = userMapper.selectByExample(userExample);
        if(list ==null || list.size()<1){
            state.setStateCode(ResultStateCode.INVALID_DATA);
            return state;
        }
        User user = new User();
        String password_cipherText = new Md5Hash(password, username + list.get(0).getSalt(), 3).toHex();
        user.setId( list.get(0).getId());
        user.setPassword(password_cipherText);
        int i=userMapper.updateByPrimaryKeySelective(user);
        if(i<1){
            state.setStateCode(ResultStateCode.INVALID_DATA);
            return state;
        }
        return state;
    }
}
