package com.iamberry.wechat.service.member;

import java.net.URLDecoder;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.iamberry.wechat.core.entity.Page;
import com.iamberry.wechat.core.entity.member.ApplyDto;
import com.iamberry.wechat.core.entity.member.CashLog;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.core.entity.member.Withdraw;
import com.iamberry.wechat.face.member.CashLogService;
import com.iamberry.wechat.face.member.MemberService;
import com.iamberry.wechat.face.member.WithdrawService;
//import com.iamberry.wechat.face.wechat.WxService;	
import com.iamberry.wechat.service.member.dao.WithdrawDao;
import com.iamberry.wechat.tools.DateTimeUtil;
import com.iamberry.wechat.tools.NameUtils;
import com.iamberry.wechat.tools.ResultInfo;
@Service
public class WithdrawServiceImpl implements WithdrawService {
	@Autowired
	private WithdrawDao withdrawDao;

	@Autowired
	private MemberService memberService;
	
	@Autowired
	private CashLogService cashLogService;
	
	public WithdrawDao getWithdrawDao() {
		return withdrawDao;
	}
	public void setWithdrawDao(WithdrawDao withdrawDao) {
		this.withdrawDao = withdrawDao;
	}
	@Override
	public Integer getCount() {
		// TODO Auto-generated method stub
		return withdrawDao.getCount();
	}


	@Override
	public void updateWithdraw(Withdraw withdraw) {
		// TODO Auto-generated method stub
		withdrawDao.updateWithdraw(withdraw);
	}

	@Override
	public boolean addApplyCashWithdraw(ApplyDto dto, Member member) throws Exception {
		// 添加申请记录
		Withdraw withdraw = new Withdraw();
		Date date = new Date();
		withdraw.setWithdrawalsLogsDate(date);
		withdraw.setWithdrawalsOpenid(member.getUserOpenid());
		withdraw.setWithdrawalsLogsIntegralNum(0);		//积分 预留
		
		withdraw.setWithdrawalsLogsAmount(dto.getIntegralNum() * 100);	//提现金额
		withdraw.setWithdrawalsUsername(dto.getUsername());
		withdraw.setWithdrawalsTel(dto.getTel());
		withdraw.setWithdrawalsStatus(2); // 处理中
		withdraw.setWithdrawalsCardNo(dto.getBankName());
		withdraw.setWithdrawalsBankName(dto.getBranch());
		int i = withdrawDao.insertApplyLogs(withdraw); // 添加申请记录
		if (i < 1) {
			throw new Exception("添加申请记录失败!");
		}
		
		// 修改用户可用金额、添加现金记录
		member.setUserIncome( - dto.getIntegralNum() * 100); // 可用金额-提现金额
		i = memberService.updateUserIncomeByOpenId(member);
		if (i < 1) {
			throw new Exception("修改用户可用金额失败!");
		}
		String cashIntroduction = dto.getUsername() + "提现" + dto.getIntegralNum();
		i = addCashLog(member.getUserOpenid(), dto.getIntegralNum() * 100, 2, cashIntroduction, 2,withdraw.getWithdrawalsLogsId().toString());// 提现支出
		if (i < 1) {
			throw new Exception("添加提现 现金记录失败!");
		}
		
		return true;
	}
	
	/**
	 * 添加一条 现金记录
	 * 2016年5月4日
	 * @param openid
	 * @param cashNum
	 * @param cashType
	 * @param cashIntroduction
	 * @param cashResType
	 * @return
	 */
	private int addCashLog(String openid,int cashNum,int cashType,String cashIntroduction,int cashResType,String cashLogsOrderid){
		CashLog cash = new CashLog();
		cash.setCashLogsOpenid(openid);
		cash.setCashLogsNum(cashNum);
		cash.setCashLogsType(cashType);
		cash.setCashLogsIntroduction(cashIntroduction);
		cash.setCashLogsResType(cashResType);
		cash.setCashLogsCreateDate(new Date());
		cash.setCashLogsOrderid(cashLogsOrderid);
		return cashLogService.addCashLog(cash);
	}
	
	@Override
	public List<Withdraw> selectLogsByOpenid(Page page) {
		// TODO Auto-generated method stub
		return withdrawDao.selectLogsByOpenid(page);
	}
	@Override
	public Integer selectLogsCountByOpenid(Page page) {
		// TODO Auto-generated method stub
		return withdrawDao.selectLogsCountByOpenid(page);
	}
	@Override
	public Withdraw selectWithdrawLogsById(Integer id) {
		// TODO Auto-generated method stub
		return withdrawDao.selectWithdrawLogsById(id);
	}
	
	public boolean handleWithdrawCashStatus(Integer status, Withdraw withdraw) throws Exception {
		Withdraw with = new Withdraw();
		with.setWithdrawalsLogsId(withdraw.getWithdrawalsLogsId());
		with.setWithdrawalsStatus(status);
		with.setWithdrawalsRemark(withdraw.getWithdrawalsRemark());
		Withdraw withdrawApply = withdrawDao.selectWithdrawLogsById(withdraw.getWithdrawalsLogsId());
		if (status == 1) { // 通过
			// 修改此次记录状态为通过
			int i = withdrawDao.updateWithdrawStatusById(with);
			if (i < 1) {
				throw new Exception("处理失败!");
			}
			//返现后给用户推送微信消息
			if(withdrawApply != null && StringUtils.isNotEmpty(withdrawApply.getWithdrawalsOpenid())){
				try {
					Member member = memberService.getMemberByUserOpenId(withdrawApply.getWithdrawalsOpenid());
					String temp = ResultInfo.INCOMEREMINDTEMP;
					double money = withdrawApply.getWithdrawalsLogsAmount().doubleValue() / 100.0;
					temp = temp.replaceFirst("firstValueIamberry", ResultInfo.INCOMEAGREEMESSAGE)
						.replaceFirst("accountValueIamberry", URLDecoder.decode(member.getUserNickname(), "UTF-8"))
						.replaceFirst("timeValueIamberry", DateTimeUtil.format(new Date(),NameUtils.getConfig("DATE_TIME_FORMAT")))
						.replaceFirst("typeValueIamberry", "申请提现：" + new Double(money).toString()+"元")
						.replaceFirst("remarkValueIamberry", ResultInfo.INTOSHOP);
//					wxService.incomeRemind(temp, withdrawApply.getWithdrawalsOpenid(), ResultInfo.INDEX_PAGE);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			// 完成
			return true;
		} else if (status == 3) { // 驳回
			// 修改此次记录为不通过
			int i = withdrawDao.updateWithdrawStatusById(with);
			if (i < 1) {
				throw new Exception("处理失败!");
			}

			// 修改用户可用金额 +
			Member member = new Member();
			member.setUserOpenid(withdraw.getWithdrawalsOpenid());
			member.setUserIncome(withdraw.getWithdrawalsLogsAmount() == null ? 0 : withdraw.getWithdrawalsLogsAmount().intValue()); // 可用金额-提现金额
			i = memberService.updateUserIncomeByOpenId(member);
			
			//删除现金记录
			Integer j = cashLogService.deleteCashLogs(withdraw.getWithdrawalsLogsId());
			if (j == null || j < 1) {
				throw new Exception("处理失败!");
			}
			
			//返现后给用户推送微信消息
			if(withdrawApply != null && StringUtils.isNotEmpty(withdrawApply.getWithdrawalsOpenid())){
				try {
					Member dataMember = memberService.getMemberByUserOpenId(withdrawApply.getWithdrawalsOpenid());
					String temp = ResultInfo.INCOMEREMINDTEMP;
					double money = withdrawApply.getWithdrawalsLogsAmount().doubleValue() / 100.0;
					temp = temp.replaceFirst("firstValueIamberry", ResultInfo.INCOMEREJECTMESSAGE)
						.replaceFirst("accountValueIamberry", URLDecoder.decode(dataMember.getUserNickname(), "UTF-8"))
						.replaceFirst("timeValueIamberry", DateTimeUtil.format(new Date(),NameUtils.getConfig("DATE_TIME_FORMAT")))
						.replaceFirst("typeValueIamberry", "申请提现：" + new Double(money).toString()+"元")
						.replaceFirst("remarkValueIamberry", ResultInfo.INTOSHOP);
//					wxService.incomeRemind(temp, withdrawApply.getWithdrawalsOpenid(), ResultInfo.INDEX_PAGE);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (i < 1) {
				throw new Exception("修改用户可用金额失败!");
			}
			// 完成
			return true;
		}
		return false;
	}
	
	@Override
	public int selectUseLogsCount(Withdraw withdraw) {
		// TODO Auto-generated method stub
		return withdrawDao.selectUseLogsCount(withdraw);
	}
	@Override
	public List<Withdraw> selectWithDraw(Page page) {
		// TODO Auto-generated method stub
		return withdrawDao.selectWithDraw(page);
	}
	@Override
	public List<Withdraw> selectWithDrawAllSumMoney(Page page) {
		// TODO Auto-generated method stub
		return withdrawDao.selectWithDrawAllSumMoney(page);
	}
	
	
	
	
	
	
	
}
