package com.community.huiju.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.community.commom.mode.ResponseBean;
import com.community.huiju.common.code.ICode;
import com.community.huiju.common.perproties.LoginCodePerproties;
import com.community.huiju.dao.TaUserMapper;
import com.community.huiju.enums.UserVerifyEnum;
import com.community.huiju.model.TaUser;
import com.community.huiju.service.ITaUserService;
import com.community.huiju.service.WxLoginServiceI;
import com.github.sd4324530.fastweixin.api.OauthAPI;
import com.github.sd4324530.fastweixin.api.UserAPI;
import com.github.sd4324530.fastweixin.api.config.ApiConfig;
import com.github.sd4324530.fastweixin.api.response.GetUserInfoResponse;
import com.github.sd4324530.fastweixin.api.response.OauthGetTokenResponse;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.Map;

/**
 * @author FXF
 * @date 2019-03-29
 */
@Service("wxLoginService")
public class WxLoginServiceImpl implements WxLoginServiceI {
	
	private Logger logger = LoggerFactory.getLogger(WxLoginServiceImpl.class);
	
	@Autowired
	private TaUserMapper taUserMapper;

	@Autowired
	private ITaUserService iTaUserService;

	@Autowired
	@Qualifier("phoneCodeImpl")
	private ICode iCode;

	@Autowired
	private LoginCodePerproties loginCodePerproties;
	
	@Override
	public ResponseBean getOpenidByWxcode(String wxcode) {
		ResponseBean responseBean = new ResponseBean();
		ApiConfig apiConfig = new ApiConfig("wx6070fd3e8ef854e4","cb07709de2f05b824f1ebda220684d3b", true);
		logger.info("获取微信相关信息");
		OauthAPI oauthAPI = new OauthAPI(apiConfig);
		OauthGetTokenResponse codeResponse = oauthAPI.getToken(wxcode);
		String openId = codeResponse.getOpenid();
		logger.info("获取到wxcode:" + wxcode + " 获取到的openid: " + openId + "accesstoken: " + codeResponse.getAccessToken());
		
		//根据openId查询关联的手机号
		TaUser taUser = taUserMapper.getByOpenId(openId);
		if (null == taUser) {
			//根据OPENID获取用户信息
			RestTemplate restTemplate = new RestTemplate();
			String wxUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+codeResponse.getAccessToken()+"&openid=" + openId;
			String userInfo = restTemplate.getForEntity(wxUrl,String.class).getBody();
			logger.info("获取到用户信息:" + userInfo);

			Map<String, Object> result = Maps.newHashMap();
			result.put("userInfo", userInfo);
			result.put("openid", openId);

			responseBean.addSuccess(UserVerifyEnum.NO_ACCOUNT.getMsg(), result, loginCodePerproties.getLoginCode().get(UserVerifyEnum.NO_ACCOUNT.getCode()));
			return responseBean;
		}

		responseBean = iTaUserService.checkLogin(responseBean, taUser);

		return responseBean;
	}

	@Override
	public ResponseBean associatedWX(String parameter) {
		ResponseBean responseBean = new ResponseBean();

		JSONObject jsonObject = JSONObject.parseObject(parameter);
		String loginName = jsonObject.getString("loginName");
		String code = jsonObject.getString("code");

		// 检验手机号和验证码
		iCode.checkPhoneAndCode(loginName, code);

		// 获取用户
		TaUser user = iTaUserService.hasUserPhone(loginName);
		// 未注册
		if (null == user) {
			responseBean.addError(UserVerifyEnum.NO_UNREGISTERED.getCode(), UserVerifyEnum.NO_UNREGISTERED.getMsg());
			return responseBean;
		}

		// 检验微信绑定
		responseBean = checkWX(responseBean, user, parameter);

		return responseBean;
	}

	/**
	 *  检验微信绑定
	 * @param responseBean
	 * @param user
	 * @param parameter
	 * @return
	 */
	private ResponseBean checkWX(ResponseBean responseBean, TaUser user, String parameter) {
		// 检验用户状态
		iTaUserService.checkBlacklistStatusUser(user);

		// 检验是否关联了微信
		String userOpenid = user.getOpenid();
		if (StringUtils.isNotBlank(userOpenid)) {
			responseBean.addError("已关联了微信账号!");
			return responseBean;
		}

		JSONObject jsonObject = JSONObject.parseObject(parameter);

		String openid = jsonObject.getString("openid");
		if (StringUtils.isNotBlank(openid)) {
			responseBean.addError("openid 参数缺失！");
			return responseBean;
		}
		JSONObject userInfoJSON = jsonObject.getJSONObject("userInfo");
		if (null == userInfoJSON) {
			responseBean.addError("openid 参数缺失！");
			return responseBean;
		}

		user.setOpenid(openid);
		user.setNickname(userInfoJSON.getString("nickname"));

		// 更新用户信息
		taUserMapper.updateByPrimaryKeySelective(user);

		// 检验登录房产
		responseBean = iTaUserService.checkLogin(responseBean, user);

		return responseBean;
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public ResponseBean register(String parameter) {
		ResponseBean<TaUser> response = new ResponseBean();

		JSONObject jsonObject = JSONObject.parseObject(parameter);
		TaUser user = jsonObject.toJavaObject(TaUser.class);

		Map<String,Object> map = Maps.newHashMap();
		map.put("loginName",user.getLoginName());
		TaUser currentUser = taUserMapper.selectByLoginName(map);
		if (null != currentUser) {
			response.addError("手机号已被注册");
			return response;
		}

		String code = jsonObject.getString("code");

		// 校验手机号 和验证码
		iCode.checkPhoneAndCode(user.getLoginName(), code);

		// 开始注册
		user.setCreateDate(new Date());
		user.setUpdateDate(new Date());
		user.setStatus("1");
		user.setAcceptAgreementStatus("1");
		user.setUserName(user.getLoginName());
		user.setRemark("这是系统自动注册!");
		user.setVerifyStatus("0");
		user.setFaceStatus("0");
		taUserMapper.insertSelective(user);

		user.setCreateUser(user.getId());
		user.setUpdateUser(user.getId());

		// 更新
		taUserMapper.updateByPrimaryKeySelective(user);

		// 检验微信绑定
		response = checkWX(response, user, parameter);

		return response;
	}

}
