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.SysUserBankCardDao;
import com.ym.mec.biz.dal.entity.SysUserBankCard;
import com.ym.mec.biz.service.SysUserBankCardService;
import com.ym.mec.common.dal.BaseDAO;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.common.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SysUserBankCardServiceImpl extends BaseServiceImpl<Long, SysUserBankCard> implements SysUserBankCardService {
	
	@Autowired
	private SysUserBankCardDao sysUserBankCardDao;
	
	@Autowired
	private SysUserFeignService sysUserFeignService;

	@Override
	public BaseDAO<Long, SysUserBankCard> getDAO() {
		return sysUserBankCardDao;
	}

	@Override
    @Transactional(rollbackFor = Exception.class)
	public SysUserBankCard add(SysUserBankCard sysUserBankCard) {
		/*if(StringUtils.isEmpty(sysUserBankCard.getSmsCode()) || StringUtils.isEmpty(sysUserBankCard.getMobilePhone())){
			return false;
		}
		String verifyCode = redisTemplate.opsForValue().get(loginVerifyCodeKey + sysUserBankCard.getMobilePhone());
		if(StringUtils.isNotEmpty(verifyCode) && StringUtils.equalsIgnoreCase(verifyCode,sysUserBankCard.getSmsCode())){
			sysUserBankCardDao.insert(sysUserBankCard);
			return true;
		}*/
        if(sysUserBankCard.getIsDefault() != null && sysUserBankCard.getIsDefault() == 1){
            //该用户所有卡设置未非默认
            sysUserBankCardDao.setNotDefault(sysUserBankCard.getUserId());
        }
		sysUserBankCardDao.insert(sysUserBankCard);
		
		//更新user表信息
		Integer userId = sysUserBankCard.getUserId();
		SysUser user = sysUserFeignService.queryUserById(userId);
		if(user == null){
			throw new BizException("用户信息查询失败");
		}
		user.setRealName(sysUserBankCard.getRealName());
		user.setIdCardNo(sysUserBankCard.getIdCardNo());
		sysUserFeignService.updateSysUser(user);
		
		return sysUserBankCard;
	}

	@Override
	public List<SysUserBankCard> findByUser(Integer userId) {
		return sysUserBankCardDao.findByUser(userId);
	}

	@Override
	public void del(Long id, Integer userId) {
		sysUserBankCardDao.del(id,userId);
	}
}