package com.iamberry.wechat.service.qrcode;

import java.util.List;
import java.util.regex.Matcher;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.iamberry.app.tool.log.RatFWLogger;
import com.iamberry.wechat.core.entity.drp.PlaceInfo;
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.relationship.WdRelation;
import com.iamberry.wechat.core.entity.wx.QRCJson;
import com.iamberry.wechat.face.home.HomeService;
import com.iamberry.wechat.face.qrcode.QrcodeService;
import com.iamberry.wechat.face.wechat.WeChatService;
import com.iamberry.wechat.service.home.dao.HomeServiceDao;
import com.iamberry.wechat.service.mapper.PlaceInfoMapper;
import com.iamberry.wechat.service.qrcode.dao.QrcodeDao;
import com.iamberry.wechat.service.relationship.Dao.WdRelationDao;
import com.iamberry.wechat.tools.NameUtils;
import com.iamberry.wechat.tools.StaticInfo;
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 {
	@Autowired
	private RatFWLogger log;
	
	private Object lock = new Object(); // 防止多人抢二维码

	private WeixinUtil weixinUtil;
	
	@Autowired
	private HomeService homeService;
	
	@Autowired
	private PlaceInfoMapper placeInfoMapper;
	
	@Autowired
	private WdRelationDao wdRelationDao;
	
	public void setLock(Object lock) {
		this.lock = lock;
	}
	
	@Autowired
	private QrcodeDao qrcodeDao;
	public void setQrcodeDao(QrcodeDao qrcodeDao) {
		this.qrcodeDao = qrcodeDao;
	}
	
	@Autowired
	private HomeServiceDao homeServiceDao;
	public void setHomeServiceDao(HomeServiceDao homeServiceDao) {
		this.homeServiceDao = homeServiceDao;
	}
	
	@Autowired
	private WeChatService weChatService;
	
	@Override
	public Qrcode selectQrcodeByQrcodeId(Integer id) {
		// TODO Auto-generated method stub
		return qrcodeDao.selectQrcodeByQrcodeId(id);
	}
	
	@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();
			@SuppressWarnings("static-access")
			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();
			@SuppressWarnings("static-access")
			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());
	}

	@Override
	public boolean bulidUser(String nowUserOpenId, Object parent, Integer type) {
		// TODO Auto-generated method stub
		if (!StringUtils.isNotEmpty(nowUserOpenId) || parent == null || type == null) {
			return false;
		}
		
		//赋值&更新数据
		Member member = homeService.selectMemberInfoByOpenId(nowUserOpenId);
//System.out.println("----------------------member------111111111-----------------------" + member);
		// isNew: true:更新用户绑定信息，false：不能更新用户绑定信息
		boolean isNew = false;
		if (member != null && member.getUserId() != null) {
			member.setUserOpenid(nowUserOpenId);
			//没绑关系、没有来源、上线是代理商时的id为空、没有微代理层关系 时， 则可以绑定用户关系 
			if (member.getUserIsFlag() != null && member.getUserIsFlag().intValue() == 1
					&& member.getUserResType().intValue() == 1 && member.getUserDealers() == null) {
				WdRelation selectWdr = new WdRelation();
				selectWdr.setOpenid(member.getUserOpenid());
				List<WdRelation> list = wdRelationDao.getWdRelationByWd(selectWdr);
				if(list != null && list.size() < 1){	//若已经存在关系则不绑定
					isNew = true;
				}
			} 
		} else {
			// 如果用户不存在，添加用户信息（openid、未关注、性别未知）
			member = new Member();
			member.setUserStatus(1); 					// 未关注
			member.setUserSex(0);
			member.setUserOpenid(nowUserOpenId);
			homeService.insertMemberInfo(member);
			isNew = true; 								// 更新
		}
		if (!isNew) {
			return false;
		}
		
//System.out.println("----------------------type--intValue---222222----------------------" + type.intValue());
//System.out.println("---------------------isNew---3333333333----------------------" + type.intValue());
		// 绑定类型
		if (type.intValue() == 1) {	//微代理:parent:为openid
			if (parent.toString().equals(nowUserOpenId)) {
				return false;
			}
			member.setUserResType(2);
    		Member dealer = homeService.selectMemberInfoByOpenId(parent.toString());
//System.out.println("----------------------dealer---44444444444----------------------" + type.intValue());
    		if(dealer != null){
    			if(dealer.getTemplateId() != null){
    				member.setTemplateId(dealer.getTemplateId());
    			}
    			if(dealer.getUserDealers() != null){
    				member.setUserDealers(dealer.getUserDealers());
    			}
    		}
    		Integer i = homeService.updateUserResAndTypeByOpenid(member); // 更新
//System.out.println("---------------------homeService.updateUserResAndTypeByOpenid(member)---5555---------------------" + i);
    		boolean flag = weChatService.insertWdrelation(dealer, member);//插入微代理层关系
    		log.info(this,"------------插入微代理层级关系：------------" + flag);
    		if(i.intValue() > 0 && flag){
    			return true;
    		}
		} else if (type.intValue() == 2) {	//代理商:parent：为代理商ID
			Matcher match= StaticInfo.pattern.matcher(parent.toString());
	        if(!match.find()) {
	        	return false;
	        }
			PlaceInfo info = placeInfoMapper.selectPlaceInfobyId(Integer.parseInt(parent.toString()));
			if (info == null || nowUserOpenId.equals(info.getOpenid())) {
				return false;
			}
			if(info.getTemplateId() != 0){
				member.setTemplateId(info.getTemplateId());
			}
			if(info.getPlaceIds() != null){
				member.setUserDealers(info.getPlaceIds()); // bilud商户层关系
			}
			member.setUserResType(3);
    		Integer i = homeService.updateUserResAndTypeByOpenid(member); // 更新
    		if(i > 0){
    			return true;
    		}
		}
		return false;
	}
}
