package com.cloudcross.ssp.service.impl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cloudcross.ssp.model.Advertiser;
import com.cloudcross.ssp.model.Finance;
import com.cloudcross.ssp.service.IAdvertiserService;
import com.cloudcross.ssp.service.IFinanceService;
import com.cloudcross.ssp.base.dao.GenericIBatisDao;
import com.cloudcross.ssp.common.utils.Pager;

@Service
public class FinanceService implements IFinanceService{
	
	@Autowired
	private GenericIBatisDao ibatisDao;
	@Autowired
	private IAdvertiserService advertiserService;
	
	
	@Override
	public Finance findById(Long id) {
		// TODO Auto-generated method stub
		return ibatisDao.get("financeSqlMapper.findById", id);
	}

	@Override
	public int countByParams(Map<String, Object> paramMap) {
		// TODO Auto-generated method stub
		return ibatisDao.get("financeSqlMapper.countByParams", paramMap);
	}

	@Override
	public List<Finance> findByParams(Map<String, Object> paramMap, Pager pager) {
		// TODO Auto-generated method stub
		paramMap.put("pager", pager);
		return ibatisDao.getList("financeSqlMapper.findByParams", paramMap);
	}

	@Override
	public boolean add(Finance finance) {
		// TODO Auto-generated method stub
		ibatisDao.save("financeSqlMapper.addFinance",finance);
		return true;
	}

	
	//此时实际上为向数据表中添加记录
	@Override
	public boolean edit(Finance finance) {
		// TODO Auto-generated method stub
		ibatisDao.save("financeSqlMapper.editFinance", finance);
		return true;
	}

	@Override
	public boolean updateStatus(List<Long> idList, int status) {
		// TODO Auto-generated method stub
		return false;
	}
	
	@Override
	public Finance findByBalance(Map<String, Object> paramMap){
		return ibatisDao.get("financeSqlMapper.findByBalance",paramMap);
	}

	@Override
	public boolean saveAllocation(Map<String, Object> paramMap) {
		ibatisDao.save("advBalanceSqlMapper.insertAgentAllocation", paramMap);
		ibatisDao.save("advBalanceSqlMapper.insertAdvertiserAllocation", paramMap);
		//同时更新广告主表里的余额
		Double allocate = Double.parseDouble((String)paramMap.get("allocate"));
		Advertiser advertiser = advertiserService.findById(Long.parseLong((String)paramMap.get("advertiserId")));
		Double balance = advertiser.getBalance() + allocate;
		paramMap.put("advertiserBalance", balance);
		ibatisDao.save("advertiserSqlMapper.updateBalance", paramMap);
		return true;
	}

	@Override
	public List<Finance> findByParams(Map<String, Object> paramMap) {
		return ibatisDao.getList("financeSqlMapper.findByParams1", paramMap);
	}

}
