package io.hmit.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.hmit.common.constant.Constant;
import io.hmit.common.exception.ErrorCode;
import io.hmit.common.exception.HmitException;
import io.hmit.common.page.PageData;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

    @Autowired
    private TokenService tokenService;

    @Autowired
    private UserDao userDao;

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

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

    @Override
    public PageData<UserEntity> getOrganizationAllUsers(Map<String, Object> params, Long userId) {
        IPage<UserEntity> page = getPage(params, Constant.CREATE_DATE, false);
        List<Long> serviceIds = userDao.getAllOrganizationStaff(userId);
        List<UserEntity> list = new ArrayList<>();
        for (Long id : serviceIds) {
            UserEntity userEntity = userDao.selectById(id);
            list.add(userEntity);
        }
        page.setTotal(list.size());
        return getPageData(list, page.getTotal(), UserEntity.class);
    }

}