package com.transaction_.dao.impl;

import com.transaction_.dao.AccountDao;
import com.transaction_.entity.AccountEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class AccountDaoImpl implements AccountDao {
    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public int saveAccount(AccountEntity accountEntity) {
        String addsql = "insert into account(user_name,balance) values(?,?)";
        Object[] args = {accountEntity.getUserName(),accountEntity.getBalance()};
        return jdbcTemplate.update(addsql,args);
        //返回值update代表添加了几行
    }

    /**
     * 账户转入或转出
     * @param accountEntity
     * @param type   in 转入 out 转出
     * @return
     */
    @Override
    public int incomeAccount(AccountEntity accountEntity,String type) {
        String updateSql = "update account set balance=balance"
                + (type == "in" ? "+" :"-")
                + " ? where id =?";
        Object[] args = {accountEntity.getBalance(),accountEntity.getId()};
        return jdbcTemplate.update(updateSql,args);
    }

}
