package com.buy507.mall.service.impl;

import java.util.List;

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

import com.buy507.mall.component.RedisLock;
import com.buy507.mall.dao.UmsMemberDao;
import com.buy507.mall.dto.MemberResult;
import com.buy507.mall.dto.MemberTradeRecordResult;
import com.buy507.mall.mapper.DmsMemberBankAccountMapper;
import com.buy507.mall.mapper.UmsMemberMapper;
import com.buy507.mall.model.DmsMemberBankAccount;
import com.buy507.mall.model.StoreStatus;
import com.buy507.mall.model.UmsMember;
import com.buy507.mall.service.UmsMemberService;
import com.github.pagehelper.PageHelper;

@Service
public class UmsMemberServiceImpl implements UmsMemberService {
	
	@Autowired
	private UmsMemberDao memberDao;
	
	@Autowired
	private UmsMemberMapper memberMapper;
	
	@Autowired
	private DmsMemberBankAccountMapper memberBankAccountMapper;
	
	@Autowired
    private RedisLock redisLock;

	@Override
	public List<MemberResult> list(String nickname, String inviter, Integer memberLevel, Integer storeStatus, Integer pageSize, Integer pageNum) {
		PageHelper.startPage(pageNum, pageSize);
		return memberDao.selectByExample(nickname, inviter, memberLevel, storeStatus);
	}

	@Override
	public void updateStoreStatus(Long id, Integer storeStatus) {
		
		StoreStatus status = null;
		if(StoreStatus.No.getValue() == storeStatus) {
			status = StoreStatus.No;
		}
		if(StoreStatus.Yes.getValue() == storeStatus) {
			status = StoreStatus.Yes;
		}
		
		if(status != null) {
			UmsMember member = memberMapper.selectByPrimaryKey(id);
			if(member != null && member.getStoreStatus().getValue() != storeStatus) {
				while(true) {
					long time = System.currentTimeMillis() + RedisLock.TIMEOUT;
					if(redisLock.lock(String.valueOf(member.getId()), String.valueOf(time))) {
						member = memberMapper.selectByPrimaryKey(member.getId());
						member.setStoreStatus(status);
						memberMapper.updateByPrimaryKey(member);
						redisLock.unlock(String.valueOf(member.getId()), String.valueOf(time));
						break;
					}
				}
			}
		}
		
	}

	@Override
	public List<DmsMemberBankAccount> bankAccountList(Long memberId) {
		return memberBankAccountMapper.selectByMemberId(memberId);
	}

	@Override
	public List<MemberTradeRecordResult> tradeRecordList(Long memberId, String orderSn,
			Integer itemType, Integer type, Integer pageSize, Integer pageNum) {
		PageHelper.startPage(pageNum, pageSize);
		return memberDao.selectMemberTradeRecord(memberId, orderSn, itemType, type);
	}

}
