package io.hmit.service.impl;

import io.hmit.common.exception.ErrorCode;
import io.hmit.common.exception.HmitException;
import io.hmit.common.service.impl.BaseServiceImpl;
import io.hmit.common.validator.AssertUtils;
import io.hmit.dao.UserDao;
import io.hmit.dto.LoginDTO;
import io.hmit.entity.TokenEntity;
import io.hmit.entity.UserEntity;
import io.hmit.service.TokenService;
import io.hmit.service.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl extends BaseServiceImpl<UserDao, UserEntity> implements UserService {

    @Autowired
    private TokenService tokenService;


    @Override
    public UserEntity getByMobile(String mobile) {
        return baseDao.getUserByMobile(mobile);
    }

    @Override
    public UserEntity getByParams(Map<String, Object> params) {
        return baseDao.getUserByParams(params);
    }

    @Override
    public UserEntity getByMobileAIdno(String mobile, String userIdno) {
        Map<String, Object> params = new HashMap<>();
        params.put("mobile",mobile);
        params.put("userIdno",userIdno);
        return baseDao.getUserByParams(params);
    }


    @Override
    public UserEntity getByIdno(String userIdno) {
        Map<String, Object> params = new HashMap<>();
        params.put("userIdno",userIdno);
        return baseDao.getUserByParams(params);
    }

    @Override
    public UserEntity getUserByUserId(Long userId) {
        return baseDao.getUserByUserId(userId);
    }

    @Override
    public Map<String, Object> login(LoginDTO dto) {

        UserEntity user = getByMobile(dto.getMobile());
        AssertUtils.isNull(user, ErrorCode.ACCOUNT_PASSWORD_ERROR);

        //密码错误
        if (!user.getPassword().equals(DigestUtils.sha256Hex(dto.getPassword()))) {
            throw new HmitException(ErrorCode.ACCOUNT_PASSWORD_ERROR);
        }

        //获取登录token
        TokenEntity tokenEntity = tokenService.createToken(user.getId());

        Map<String, Object> map = new HashMap<>(2);
        map.put("token", tokenEntity.getToken());
        map.put("expire", tokenEntity.getExpireDate().getTime() - System.currentTimeMillis());

        return map;
    }

}
