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

import com.docus.core.util.Func;
import com.docus.infrastructure.redis.service.IdService;
import com.docus.server.collection.config.UserSyncConfig;
import com.docus.server.collection.dto.SzyUserDto;
import com.docus.server.collection.dto.UserDto;
import com.docus.server.collection.dto.UserModifyParam;
import com.docus.server.collection.infrastructure.dao.entity.PowerUser;
import com.docus.server.collection.infrastructure.dao.mapper.PowerUserMapper;
import com.docus.server.collection.service.IPowerUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 用户服务实现
 *
 * @author wyb
 */
@Service
public class PowerUserServiceImpl implements IPowerUserService {
    @Resource
    private PowerUserMapper powerUserMapper;
    @Resource
    private IdService idService;
    @Resource
    private UserSyncConfig syncConfig;

    @Override
    public boolean register(UserDto userDto) {
        PowerUser powerUser = powerUserMapper.getUserByUserName(userDto.getUserName());
        UserModifyParam userModifyParam = userDto.transUserAddParam();
        if (Func.isEmpty(powerUser)) {
            long userId = idService.getDateSeq();
            userModifyParam.setUserId(userId);
            userModifyParam.setUserPwd(syncConfig.getPassword());
            powerUserMapper.addUser(userModifyParam);
            return true;
        }
        userModifyParam.setUserId(powerUser.getUserId());
        powerUserMapper.updateUser(userModifyParam);
        return true;
    }

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

    @Override
    public void add(SzyUserDto dto) {
        PowerUser powerUser = powerUserMapper.getUserByUserName(dto.getUserName());
        UserModifyParam userModifyParam = new UserModifyParam();
        userModifyParam.setAuthorId(dto.getAuthorId());
        userModifyParam.setAuthorName(dto.getAuthorName());
        userModifyParam.setDeptId(dto.getDeptId());
        userModifyParam.setName(dto.getName());
        userModifyParam.setRoleId(dto.getRoleId());
        userModifyParam.setUserName(dto.getUserName());
        if (Func.isEmpty(powerUser)) {
            long userId = idService.getDateSeq();
            userModifyParam.setUserId(userId);
            userModifyParam.setUserPwd(syncConfig.getPassword());
            powerUserMapper.addUser(userModifyParam);
            return ;
        }
        userModifyParam.setUserId(powerUser.getUserId());
        powerUserMapper.updateUser(userModifyParam);
    }
}
