package com.docus.server.sys.service.impl;

import com.docus.core.util.Func;
import com.docus.infrastructure.redis.service.IdService;
import com.docus.server.common.config.UserProperties;
import com.docus.server.sys.common.pojo.dto.UserDTO;
import com.docus.server.sys.common.pojo.dto.UserModifyParam;
import com.docus.server.sys.common.pojo.entity.PowerUser;
import com.docus.server.sys.infrastructure.dao.IPowerUserDao;
import com.docus.server.sys.service.IPowerUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;

/**
 * 用户服务实现
 *
 * @author wyb
 */
@Service
public class PowerUserServiceImpl implements IPowerUserService {
    @Resource
    private IdService idService;
    @Resource
    private UserProperties userProperties;
    @Resource
    private IPowerUserDao userDao;

    @Transactional
    @Override
    public void batchInsertOrUpdatePowerUser(List<UserDTO> userDTOList) {
        userDTOList.forEach(this::insertOrUpdatePowerUser);
    }

    @Override
    public PowerUser findByUserName(String userName) {
        return userDao.findOneBy("userName", userName);
    }

    @Override
    public List<PowerUser> findByUserNameList(Collection<Object> userNames) {
        return userDao.findBy("userName", userNames);
    }

    @Transactional
    @Override
    public boolean insertOrUpdatePowerUser(UserDTO userDTO) {
        PowerUser powerUser = userDao.getUserByUserName(userDTO.getUserName());
        UserModifyParam userModifyParam = userDTO.transUserAddParam();
        if (Func.isEmpty(powerUser)) {
            long userId = idService.getDateSeq();
            userModifyParam.setUserId(userId);
            userModifyParam.setUserPwd(userProperties.getPassword());
            userDao.addUser(userModifyParam);
            return true;
        }
        userModifyParam.setUserId(powerUser.getUserId());
        userDao.updateUser(userModifyParam);
        return true;
    }

    @Transactional
    @Override
    public boolean delUserByUserName(String userName) {
        PowerUser powerUser = userDao.getUserByUserName(userName);
        if (Func.isEmpty(powerUser)) {
            return true;
        }
        userDao.delUserByUserName(userName);
        return true;
    }


}
