package com.iamberry.wechat.service.qrcode;

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

import com.iamberry.cache.LocalCache;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.core.entity.qrcode.Qrcode;
import com.iamberry.wechat.core.entity.qrcode.QrcodeResult;
import com.iamberry.wechat.core.entity.wx.QRCJson;
import com.iamberry.wechat.face.qrcode.QrcodeService;
import com.iamberry.wechat.service.home.dao.HomeServiceDao;
import com.iamberry.wechat.service.qrcode.dao.QrcodeDao;
import com.iamberry.wechat.tools.NameUtils;
import com.iamberry.wechat.tools.WeixinUtil;

/**
 * @author 何秀刚
 * Class Description: 二维码Service接口实现
 * Create Date:2016年4月18日
 * Update Date:2016年4月18日
 */
@Service
public class QrcodeServiceImpl implements QrcodeService {
	
	private Object lock = new Object(); // 防止多人抢二维码
	
	public void setLock(Object lock) {
		this.lock = lock;
	}
	
	@Autowired
	private QrcodeDao qrcodeDao;
	
	private LocalCache<String, Qrcode> cache = new LocalCache<>(200);
	
	@Autowired
	private HomeServiceDao homeServiceDao;
	
	@Override
	public Qrcode selectQrcodeByQrcodeId(Integer id) {
		// TODO Auto-generated method stub
		Qrcode qrcode = cache.get("qrcode_" + id);
		if (qrcode != null) {
			return qrcode;
		}
		qrcode = qrcodeDao.selectQrcodeByQrcodeId(id);
		cache.put("qrcode_" + id, qrcode);
		return qrcode;
	}
	
	@Override
	public Integer updateQRcodeStatusByUserOpenid(String openid) {
		// TODO Auto-generated method stub
		return qrcodeDao.updateQRcodeStatusByUserOpenid(openid);
	}

	@Override
	public Integer updateQRcodeScannNumAndSubNum(Qrcode qrcode) {
		// TODO Auto-generated method stub
		try {
			return qrcodeDao.updateQRcodeScannNumAndSubNum(qrcode);
		} catch (Exception e) {
			return 1;
		}
	}

	@Override
	public QrcodeResult applyQrcodeUrl(String openid, Integer applyUserType) {
		// TODO Auto-generated method stub
		QrcodeResult qrcodeResult = new QrcodeResult();
		// 校验
		if (openid == null || openid.isEmpty()) {
			qrcodeResult.setQroceUrl("openid 不能为空!");
			return qrcodeResult;
		}
		if (applyUserType == null) {
			applyUserType = 1;
		}
		boolean typeFlag = false;
		switch (applyUserType) {
			case 1:
				typeFlag = true;
				break;
			case 2:
				typeFlag = true;
				break;
		}
		if (!typeFlag) {
			qrcodeResult.setQroceUrl("类型错误，类型只能为1或者2。");
			return qrcodeResult;
		}
		// 获取openid对应的qrcodeURL
		Member member = homeServiceDao.selectMemberQrcodeUrlByOpenid(openid);
		if (!(member != null && member.getUserId() != null)) {
			qrcodeResult.setQroceUrl("此用户不存在!");
			return qrcodeResult;
		}
		if (member.getUserQrcode() != null && !member.getUserQrcode().isEmpty()) {
			qrcodeResult.setQroceUrl("此用户存在二维码，请勿重复生成!");
			return qrcodeResult;
		}
		
		// 判断数据库是否存在其他方式的二维码，如果存在，不产生
		Qrcode qrcode = qrcodeDao.selectSpareQrcode();
		if (qrcode != null && qrcode.getQrcodeId() != null) {
			// 存在
			synchronized (lock) {
				qrcode.setQrcodeReplaceOpenid(openid);
				qrcode.setQrcodeStatus(1);
				Integer count = qrcodeDao.updateQRcodeUserAndStatusById(qrcode);
				if (count >= 1) {
					member.setUserQrcode(qrcode.getQrcodeUrl());
					member.setUserOpenid(openid);
					count = homeServiceDao.updateMemberQrcodeByOpenid(member);
					if (count >= 1) {
						qrcodeResult.setSuccess(true);
						qrcodeResult.setQroceUrl(qrcode.getQrcodeUrl());
						return qrcodeResult;
					} else {
						// 二维码被人抢占，理应重新发起
						// applyQrcodeUrl(openid, 1);
					}
					qrcodeResult.setQroceUrl("创建失败，请稍后再试...");
					return qrcodeResult;
				} else {
					qrcodeResult.setQroceUrl("服务器忙，请稍后...");
					return qrcodeResult;
				}
			}
		} else {
			
			// 生成记录
			qrcode = new Qrcode();
			qrcode.setQrcodeOpenid(openid);
			qrcode.setQrcodeReplaceOpenid(openid);
			qrcode.setQrcodeType(1);
			qrcode.setQrcodeUrl("");
			qrcode.setQrcodeValue("");
			qrcode.setQrcodeStatus(1);
			qrcode.setQrcodeSubNum(0);
			qrcode.setQrcodeScannNum(0);
			int count = qrcodeDao.insertQrcode(qrcode);
			if (count < 1 || qrcode.getQrcodeId() == null) {
				qrcodeResult.setQroceUrl("服务器忙，请稍后...");
				return qrcodeResult;
			}
			// 不存在就系统生成
			String qrCodeValue = "QR" + qrcode.getQrcodeId().toString();
			String json = String.format(NameUtils.QR_LIMIT_STR_SCENE, qrCodeValue);
			QRCJson qrc = WeixinUtil.createQrcode(json);
			if (!(qrc == null || qrc.getUrl() == null || qrc.getUrl().isEmpty())) {
				qrcode.setQrcodeUrl(qrc.getUrl());
				qrcode.setQrcodeValue(qrCodeValue);
				qrcodeDao.updateQrcodeURLByOpenid(qrcode);
				member.setUserQrcode(qrcode.getQrcodeUrl());
				member.setUserOpenid(openid);
				count = homeServiceDao.updateMemberQrcodeByOpenid(member);
				if (count >= 1) {
					qrcodeResult.setQroceUrl(qrcode.getQrcodeUrl());
					qrcodeResult.setSuccess(true);
					return qrcodeResult;
				}
			}
		}
		return qrcodeResult;
	}

	@Override
	public Integer updateQRcodeUserAndStatusById(Qrcode qrcode) {
		// TODO Auto-generated method stub
		return qrcodeDao.updateQRcodeUserAndStatusById(qrcode);
	}

	@Override
	public QrcodeResult applyPlaceQrcodeUrl(Integer placeId) {
		// TODO Auto-generated method stub
		QrcodeResult qrcodeResult = new QrcodeResult();
		// 校验
		Qrcode qrcode = new Qrcode();
		qrcode.setQrcodeOpenid(placeId.toString());
		qrcode.setQrcodeReplaceOpenid(placeId.toString());
		qrcode.setQrcodeType(2);
		qrcode.setQrcodeUrl("");
		qrcode.setQrcodeValue("");
		qrcode.setQrcodeStatus(1);
		qrcode.setQrcodeSubNum(0);
		qrcode.setQrcodeScannNum(0);
		int count = qrcodeDao.insertQrcode(qrcode);
		if (count >= 1) {

			String qrCodeValue = "QR" + qrcode.getQrcodeId().toString();
			String json = String.format(NameUtils.QR_LIMIT_STR_SCENE, qrCodeValue);
			QRCJson qrc = WeixinUtil.createQrcode(json);
			if (!(qrc == null || qrc.getUrl() == null || qrc.getUrl().isEmpty())) {
				qrcode.setQrcodeValue(qrCodeValue);
				qrcode.setQrcodeUrl(qrc.getUrl());
				qrcodeDao.updateQrcodeURLByOpenid(qrcode);
				qrcodeResult.setQroceUrl(qrc.getUrl());
				qrcodeResult.setSuccess(true);
			} else {
				qrcodeResult.setQroceUrl("产生二维码失败，请联系我们!");
				qrcodeResult.setSuccess(false);
				return qrcodeResult;
			}
		} else {
			qrcodeResult.setQroceUrl("产生二维码失败!");
			qrcodeResult.setSuccess(false);
		}
		return qrcodeResult;
	}

	@Override
	public String selectQrcodeUrlByReplaceUser(Object replaceUserOpenid) {
		// TODO Auto-generated method stub
		if (replaceUserOpenid == null)
			return null;
		else
			return qrcodeDao.selectQrcodeUrlByReplaceUser(replaceUserOpenid.toString());
	}

}
