package com.yingying.tourist.web;

import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.yingying.tourist.common.WechatUtil;
import com.yingying.tourist.domain.User;
import com.yingying.tourist.exception.ErrorCode;
import com.yingying.tourist.result.MessageResult;
import com.yingying.tourist.service.UserService;
import com.yingying.tourist.service.WechatService;

import lombok.extern.slf4j.Slf4j;

@Controller
@Slf4j
public class WechatController {

	@Autowired
	private WechatService wechatService;

	@Autowired
	private UserService userService;

	@Autowired
	private StringRedisTemplate redisTemplate;

	@RequestMapping(value = "token")
	@ResponseBody
	public String checkToken(String signature, String echostr, String timestamp, String nonce) {

		return echostr;
	}

	@RequestMapping(value = "checkJsAuth")
	@ResponseBody
	public MessageResult<Map<String, String>> checkJsAuth(String url) {

		// 先从redis取jsapi_ticket,如果未取到，调用微信接口获取
		ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
		String jsapiTicket = opsForValue.get("jsapi_ticket");
		if (StringUtils.isBlank(jsapiTicket)) {
			jsapiTicket = wechatService.getTicket();
			opsForValue.set("jsapi_ticket", jsapiTicket, 7200, TimeUnit.SECONDS);
		}
		Map<String, String> map = WechatUtil.sign(jsapiTicket, url);

		String sign = JSON.toJSONString(map);

		if (StringUtils.isBlank(sign)) {
			return new MessageResult<Map<String,String>>().failure(ErrorCode.JS_SIGN_NULL);
		}

		return new MessageResult<Map<String,String>>().ok(map);

	}

	@RequestMapping(value = "code", produces = "application/json;charset=utf-8")
	@ResponseBody
	public MessageResult<String> code(String code) {
		String result = wechatService.getAuthToken(code);
		JSONObject jsonObject = JSONObject.parseObject(result);
		String openId = jsonObject.getString("openid");
		String token = jsonObject.getString("access_token");

		if (StringUtils.isBlank(openId)) {
			return new MessageResult<String>().failure(ErrorCode.OPENID_NULL);
		}

		// 首先查询openid 是否在数据库中，如果存在直接返回openid
		EntityWrapper<User> userWrapper = new EntityWrapper<>();
		userWrapper.eq("openid", openId);
		User user = userService.selectOne(userWrapper);
		if (user != null) {
			return new MessageResult<String>().ok(openId);
		}

		try {
			// 如果不存在，通过token和openid去获取用户信息，并插入到数据库中
			User wechatUser = wechatService.getWechatUser(token, openId);
			if (wechatUser != null) {
				userService.insert(wechatUser);
			}
		} catch (UnsupportedEncodingException e) {
			log.info("编码集转换失败");
		}

		return new MessageResult<String>().ok(openId);
	}
}
