package org.springblade.modules.app.manager;

import com.wn.common.validator.Validator;
import org.springblade.modules.app.common.dto.AppUserIdDTO;
import org.springblade.modules.app.common.dto.UserDTO;
import org.springblade.modules.app.common.query.AppUserIdQuery;
import org.springblade.modules.app.constant.ErrorCode;
import org.springblade.modules.app.service.IAppUserIdService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * @author huyinuo
 */
@Slf4j
@Component
@RefreshScope
public class AppUserIdManager {

    @Autowired
    private IAppUserIdService appUserIdService;

    public Boolean addAppUserId(String clientId, UserDTO userDTO) {
        Validator.notNull(clientId, ErrorCode.INPUT_PARAMETERS_NULL);
        Validator.notNull(userDTO.getId(), ErrorCode.INPUT_PARAMETERS_NULL);
        log.info("新增app用户标识，用户id为：{}，cid为：{}", userDTO.getId(), clientId);
        AppUserIdQuery appUserIdQuery = new AppUserIdQuery();
        appUserIdQuery.setUserId(userDTO.getId());
        appUserIdQuery.setClientId(clientId);
        List<AppUserIdDTO> appUserIdDTOList = appUserIdService.listAppUserIdByUserId(appUserIdQuery);

        // 当传入的用户cid不存在时，新增app用户标识信息，否则更新已有数据的修改时间
        if (CollectionUtils.isEmpty(appUserIdDTOList)) {
            AppUserIdDTO appUserIdDTO = new AppUserIdDTO();
            appUserIdDTO.setUserId(userDTO.getId());
            appUserIdDTO.setClientId(clientId);
            appUserIdDTO.setModifiedTime(new Date());
            appUserIdService.addAppUserId(appUserIdDTO);
        }else {
            AppUserIdDTO appUserIdDTO = appUserIdService.getAppUserIdDTO(appUserIdQuery);
            appUserIdDTO.setModifiedTime(new Date());
            appUserIdService.updateAppUserId(appUserIdDTO);
        }
        return true;
    }
}
