package io.hmit.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.hmit.common.exception.ErrorCode;
import io.hmit.common.exception.HmitException;
import io.hmit.common.service.impl.BaseServiceImpl;
import io.hmit.common.utils.Result;
import io.hmit.common.utils.sm.SMUtil;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@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 getUserByUserId(Long userId) {
        return baseDao.getUserByUserId(userId);
    }

    @Override
    public UserEntity queryByIdnum(String idnum) {
        return baseDao.selectOne(new QueryWrapper<UserEntity>().eq("id_card_no", idnum));
    }

    @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;
    }

    /**
     * <h1>此方法对全部 手机号及身份证号 进行加密</h1>
     * 请勿执行此代码
     */
    @Override
    public Result<Object> encryptOneTime() {
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        List<UserEntity> userEntities = baseDao.selectList(wrapper);
        String testStr = userEntities.get(0).getMobile();
        Pattern pattern = Pattern.compile("[0-9]{1,}");
        Matcher matcher = pattern.matcher(testStr);
        if (!matcher.matches()) {
            return new Result<>().error("加密内容何必再加密");
        }
        for (UserEntity userEntity : userEntities) {
            userEntity.setIdCardNo(SMUtil.SM4Encrypt(userEntity.getIdCardNo()));
            userEntity.setMobile(SMUtil.SM4Encrypt(userEntity.getMobile()));
            baseDao.updateById(userEntity);
        }
        return new Result<>().ok(null);
    }

}
