package com.ym.mec.biz.service.impl;

import com.ym.mec.auth.api.client.SysUserFeignService;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.biz.dal.dao.SysUserCashAccountDao;
import com.ym.mec.biz.dal.dao.SysUserCashAccountDetailDao;
import com.ym.mec.biz.dal.entity.SysUserCashAccount;
import com.ym.mec.biz.dal.entity.SysUserCashAccountDetail;
import com.ym.mec.biz.dal.enums.DealStatusEnum;
import com.ym.mec.biz.dal.enums.MessageTypeEnum;
import com.ym.mec.biz.dal.enums.PlatformCashAccountDetailTypeEnum;
import com.ym.mec.biz.dal.enums.PlatformCashAccountStatusEnum;
import com.ym.mec.biz.service.SysMessageService;
import com.ym.mec.biz.service.SysUserCashAccountService;
import com.ym.mec.common.dal.BaseDAO;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.common.service.impl.BaseServiceImpl;
import com.ym.mec.thirdparty.message.MessageSenderPluginContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class SysUserCashAccountServiceImpl extends BaseServiceImpl<Integer, SysUserCashAccount> implements SysUserCashAccountService {

	@Autowired
	private SysUserCashAccountDao sysUserCashAccountDao;
	@Autowired
	private SysUserFeignService sysUserFeignService;
	@Autowired
	private SysMessageService sysMessageService;

	@Autowired
	private SysUserCashAccountDetailDao sysUserCashAccountDetailDao;

	@Override
	public BaseDAO<Integer, SysUserCashAccount> getDAO() {
		return sysUserCashAccountDao;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public boolean updateBalance(Integer userId, BigDecimal decimal) {

		SysUserCashAccount cashAccount = sysUserCashAccountDao.getLocked(userId);
		if (cashAccount == null) {
			throw new BizException("用户[{}]现金账户不存在", userId);
		}

		if (cashAccount.getStatus() != PlatformCashAccountStatusEnum.NORMAL) {
			throw new BizException("账户不可用");
		}
		BigDecimal balance = cashAccount.getBalance().add(decimal);
		if (balance.doubleValue() < 0) {
			throw new BizException("现金账户[{}]余额不足，可用余额剩{}元", userId, cashAccount.getBalance().doubleValue());
		}

		cashAccount.setBalance(balance);
		cashAccount.setUpdateTime(new Date());

		sysUserCashAccountDao.update(cashAccount);

		return true;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public boolean updateBalance(Integer userId, BigDecimal decimal, PlatformCashAccountDetailTypeEnum type, String memo) {
		SysUserCashAccount cashAccount = sysUserCashAccountDao.getLocked(userId);
		if (cashAccount == null) {
			throw new BizException("用户[{}]现金账户不存在", userId);
		}

		if (cashAccount.getStatus() != PlatformCashAccountStatusEnum.NORMAL) {
			throw new BizException("账户不可用");
		}
		BigDecimal balance = cashAccount.getBalance().add(decimal);
		if (balance.doubleValue() < 0) {
			throw new BizException("现金账户[{}]余额不足，可用余额剩{}元", userId, cashAccount.getBalance().doubleValue());
		}

		Date date = new Date();

		SysUserCashAccountDetail detail = new SysUserCashAccountDetail();
		detail.setAmount(decimal);
		detail.setBalance(cashAccount.getBalance().add(decimal));
		detail.setComment(memo);
		detail.setCreateTime(date);
		detail.setStatus(DealStatusEnum.SUCCESS);
		detail.setType(type);
		detail.setUpdateTime(date);
		detail.setUserId(userId);

		sysUserCashAccountDetailDao.insert(detail);

		cashAccount.setBalance(balance);
		cashAccount.setUpdateTime(date);

		sysUserCashAccountDao.update(cashAccount);
		if(!decimal.equals(BigDecimal.ZERO)){
			//推送余额消费信息
			Map<Integer,String> phoneMap = new HashMap<>(1);
			SysUser sysUser = sysUserFeignService.queryUserById(userId);
			phoneMap.put(userId,sysUser.getPhone());
			sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.YIMEI, MessageTypeEnum.STUDENT_SMS_BALANCE_CONSUME,
					phoneMap,null,0,null,"",decimal,balance);
			Map<Integer,String> idMap = new HashMap<>(1);
			idMap.put(userId,userId.toString());
			sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.STUDENT_SMS_BALANCE_CONSUME,
					idMap,null,0,null,"",decimal,balance);
		}
		return true;
	}

	@Override
	public boolean updateCourseBalance(Integer userId, BigDecimal decimal) {
		SysUserCashAccount cashAccount = sysUserCashAccountDao.getLocked(userId);
		if (cashAccount == null) {
			throw new BizException("用户[{}]现金账户不存在", userId);
		}

		cashAccount.setCourseBalance(decimal);
		cashAccount.setUpdateTime(new Date());

		sysUserCashAccountDao.update(cashAccount);

		return true;
	}

	@Override
	public boolean appendCourseBalance(Integer userId, BigDecimal decimal) {
		SysUserCashAccount cashAccount = sysUserCashAccountDao.getLocked(userId);
		if (cashAccount == null) {
			throw new BizException("用户[{}]现金账户不存在", userId);
		}

		BigDecimal balance = cashAccount.getCourseBalance().add(decimal);
		if (balance.doubleValue() < 0) {
			throw new BizException("现金账户[{}]课程余额不足，可用余额剩{}元", userId, cashAccount.getBalance().doubleValue());
		}

		Date date = new Date();
		cashAccount.setCourseBalance(balance);
		cashAccount.setUpdateTime(date);

		sysUserCashAccountDao.update(cashAccount);

		return true;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public boolean transferCourseBalanceToBalance(Integer userId) {
		SysUserCashAccount cashAccount = sysUserCashAccountDao.getLocked(userId);
		if (cashAccount == null) {
			throw new BizException("用户[{}]现金账户不存在", userId);
		}

		if (cashAccount.getStatus() != PlatformCashAccountStatusEnum.NORMAL) {
			throw new BizException("账户不可用");
		}

		Date date = new Date();

		SysUserCashAccountDetail detail = new SysUserCashAccountDetail();
		detail.setAmount(cashAccount.getCourseBalance());
		detail.setBalance(cashAccount.getBalance().add(cashAccount.getCourseBalance()));
		detail.setComment("课程余额转账");
		detail.setCreateTime(date);
		detail.setStatus(DealStatusEnum.SUCCESS);
		detail.setType(PlatformCashAccountDetailTypeEnum.FILL_ACCOUNT);
		detail.setUpdateTime(date);
		detail.setUserId(userId);

		sysUserCashAccountDetailDao.insert(detail);

		cashAccount.setBalance(cashAccount.getBalance().add(cashAccount.getCourseBalance()));
		cashAccount.setCourseBalance(new BigDecimal(0));
		cashAccount.setUpdateTime(date);

		sysUserCashAccountDao.update(cashAccount);
		return true;
	}

	@Override
	public SysUserCashAccount getLocked(Integer userId) {
		return sysUserCashAccountDao.getLocked(userId);
	}

}
