package com.jkcredit.invoice.hub.service.userBalance;

import com.jkcredit.invoice.hub.constant.ExceptionMessage;
import com.jkcredit.invoice.hub.mapper.UserBalanceMapper;
import com.jkcredit.invoice.hub.model.dto.userBalance.UserBalanceDto;
import com.jkcredit.invoice.hub.model.dto.userBalance.UserBalanceDtoApi;
import com.jkcredit.invoice.hub.model.po.userBalance.UserBalancePo;
import com.jkcredit.invoice.hub.service.base.BaseService;
import com.jkcredit.invoice.hub.spi.lang.exception.ServiceException;
import com.jkcredit.invoice.hub.util.BeanUtil;
import com.jkcredit.invoice.hub.util.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @description:
 * @author: xusonglin
 * @create: 2020/1/17 23:44
 * @version: V1.0
 **/
@Slf4j
@Service
public class UserBalanceServiceImpl extends BaseService implements UserBalanceService {
    @Resource
    UserBalanceMapper userBalanceMapper;

    @Override
    public UserBalanceDtoApi getUserBalanceApi(Long userId) {
        UserBalancePo userBalancePo = userBalanceMapper.selectById(userId);
        if (userBalancePo == null) {
            throw new ServiceException(ExceptionMessage.USER_NOT_EXIST);
        }
        return new UserBalanceDtoApi(CommonUtil.parseDouble(userBalancePo.getBalance()), CommonUtil.dateFormat(userBalancePo.getUpdateTime()));
    }

    @Override
    public void updateUserBalance(UserBalanceDto dto) {
        UserBalancePo po = new UserBalancePo();
        BeanUtil.copyProperties(po, dto);
        po.setUpdateTime(new Date());
        try {
            userBalanceMapper.updateById(po);
        } catch (Exception e) {
            log.error("更新余额表失败，失败原因：{}", e.getMessage());
            throw new ServiceException("更新余额表失败");
        }
    }

    //    @Override
    public UserBalanceDto getUserBalance(Long userId) {
        UserBalancePo userBalancePo = userBalanceMapper.selectById(userId);
        UserBalanceDto dto = new UserBalanceDto();
        BeanUtil.copyProperties(dto, userBalancePo);
        if (userBalancePo == null) {
            throw new ServiceException(ExceptionMessage.USER_NOT_EXIST);
        }
        return dto;
    }
}
