package com.yd.rmi.tencent.wechat;

import com.google.common.base.Strings;
import com.yd.api.result.JsonResult;
import com.yd.dal.entity.customer.AclCustomer;
import com.yd.dal.entity.customer.AclCustomerLog;
import com.yd.dal.service.customer.AclCustomerDALService;
import com.yd.dal.service.customer.AclCustomerLogDALService;
import com.yd.rmi.cache.SystemConfigService;
import com.yd.rmi.tencent.wechat.service.WechatService;
import com.yd.rmi.tencent.wechat.vo.accesstoken.AccessTokenByCodeRequest;
import com.yd.rmi.tencent.wechat.vo.accesstoken.AccessTokenByCodeResponse;
import com.yd.rmi.tencent.wechatinterf.pojo.ticket.TicketRequest;
import com.yd.rmi.tencent.wechatinterf.pojo.token.TokenRequest;
import com.yd.rmi.tencent.wechatinterf.pojo.wechatpay.WxConfigRequestVO;
import com.yd.rmi.tencent.wechatinterf.pojo.wechatpay.WxConfigResponseVO;
import com.yd.rmi.tencent.wechatinterf.service.WechatInterfService;
import com.yd.util.SpringContextUtil;
import com.yd.util.config.ZHBErrorConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;
import java.util.Map;

@Controller
@CrossOrigin(origins = "*")
public class WechatController {
	@Autowired
	private WechatService wechatService;
	@Autowired
	private SystemConfigService systemConfigService;
	@Autowired
	private AclCustomerDALService aclCustomerDALService;
	@Autowired
	private WechatInterfService wechatInterfService;
	@Autowired
	private AclCustomerLogDALService aclCustomerLogDALService;
	/**
	 * 微信分享时授权
	 * @param wxConfigRequestVO
	 * @return
	 */
	@RequestMapping("/wxConfig")
	@ResponseBody
	public Object wxConfig(@RequestBody WxConfigRequestVO wxConfigRequestVO){
		System.out.println("开始分享-----------------------");
		String accessToken = wechatService.obtainToken(new TokenRequest());
		TicketRequest ticketRequest = new TicketRequest();
		ticketRequest.setAccessToken(accessToken);
		String jsapiTicket = wechatService.obtainTicket(ticketRequest);
		System.out.println("wxConfigRequestVO.getUrl()");
		String url = wxConfigRequestVO.getUrl();
		System.out.println("wxConfigRequestVO.getUrl() END");
		System.out.println("URLDecoder.decode开始");
		try {url = URLDecoder.decode(wxConfigRequestVO.getUrl(), "utf-8");} catch (UnsupportedEncodingException e) {}
		System.out.println("URLDecoder.decode结束");
		System.out.println("jsapiTicketSign开始");
		Map<String, String> ret = wechatService.jsapiTicketSign(jsapiTicket,url);
		System.out.println("jsapiTicketSign结束");
		JsonResult result = new JsonResult();
		WxConfigResponseVO wxConfigResponseVO = new WxConfigResponseVO();
		if(SpringContextUtil.isProd()){
			wxConfigResponseVO.setAppId(systemConfigService.getSingleConfigValue("YD-TENCENT_WECHAT_APPID"));
		}else {
			wxConfigResponseVO.setAppId(systemConfigService.getSingleConfigValue("TENCENT_WECHAT_APPID"));
		}
		wxConfigResponseVO.setTimestamp(ret.get("timestamp"));
		wxConfigResponseVO.setNonceStr(ret.get("nonceStr"));
		wxConfigResponseVO.setSignature(ret.get("signature"));
		wxConfigResponseVO.setJsApiList(new String[]{"updateAppMessageShareData","updateTimelineShareData","onMenuShareTimeline","onMenuShareAppMessage","onMenuShareQQ","onMenuShareWeibo","onMenuShareQZone","chooseImage","uploadImage","downloadImage","getLocalImgData"});
		result.setData(wxConfigResponseVO);
		result.setSuccess(true);
		result.setMessage(ZHBErrorConfig.getErrorInfo("800000"));
		System.out.println("结束分享-----------------------");
		return result;
	}

	/**
	 * 获取用户的openID
	 * @param request
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping("/getOpenId")
	@ResponseBody
	public Object getOpenId(HttpServletRequest request) {
		String code = request.getParameter("code");
		String info = request.getParameter("info");
		System.out.println(">>>>>>code>>>>>>" + code);
		System.out.println(">>>>>>info>>>>>>" + info);
		String jumpUrl = systemConfigService.getSingleConfigValue("YdLifeIndex");//https://mdev.zuihuibi.cn/ydLife/my
		if (!Strings.isNullOrEmpty(code) && !Strings.isNullOrEmpty(info)) {
			String[] infoArr = info.split(",");
			String appId = infoArr[0];
			String customerIdStr = infoArr[1];
			AccessTokenByCodeResponse accessTokenByCodeResponse = getAccessTokenByCode(code, appId);
			if (!Strings.isNullOrEmpty(customerIdStr) && accessTokenByCodeResponse != null) {
				Long customerId = Long.parseLong(customerIdStr);
				String openId = accessTokenByCodeResponse.getOpenid();
				AclCustomer customer = aclCustomerDALService.findById(customerId);
				customer.setYdWechatOpenid(openId);
				aclCustomerDALService.update(customer);
				List<AclCustomerLog> customerLogList = aclCustomerLogDALService.findLogInfoByCustomerId(customerId);
				int logTimes = (customerLogList.isEmpty()) ? 0 : customerLogList.size();
				jumpUrl = (logTimes < 2) ? systemConfigService.getSingleConfigValue("YdLifeThanksPage") : jumpUrl;
			}
		}
		return new ModelAndView(new RedirectView(jumpUrl));
	}

	private AccessTokenByCodeResponse getAccessTokenByCode(String code, String appId) {
		AccessTokenByCodeResponse accessTokenByCodeResponse = null;
		String appIdZHB = systemConfigService.getSingleConfigValue("TENCENT_WECHAT_APPID");//最惠比公众账号id
		String appIdYD = systemConfigService.getSingleConfigValue("YD-TENCENT_WECHAT_APPID");//银盾公众账号id
		String appIdAJB = systemConfigService.getSingleConfigValue("AJB-TENCENT_WECHAT_APPID");//安吉保公众账号id
		String appIdYD2 = systemConfigService.getSingleConfigValue("YD2-TENCENT_WECHAT_MINIPRO_APPID");//银盾公众账号id--小程序福利产品
		String secret = null;
		if(appId.equals(appIdYD)){//银盾
			secret = systemConfigService.getSingleConfigValue("YD-TENCENT_WECHAT_APP_SECRET");//第三方用户唯一凭证密钥
		}else if(appId.equals(appIdAJB)){//安吉保
			secret = systemConfigService.getSingleConfigValue("AJB-TENCENT_WECHAT_APP_SECRET");//第三方用户唯一凭证密钥
		}else if(appId.equals(appIdYD2)){//银盾2--福利产品支付
			secret = systemConfigService.getSingleConfigValue("YD2-TENCENT_WECHAT_APP_SECRET");//第三方用户唯一凭证密钥
		}else if(appId.equals(appIdZHB)){//最惠比--appid
			secret = systemConfigService.getSingleConfigValue("TENCENT_WECHAT_APP_SECRET");//第三方用户唯一凭证密钥
		}
		if(!Strings.isNullOrEmpty(secret)){
			String grantType = systemConfigService.getSingleConfigValue("TENCENT_WECHAT_ACCESS_TOKEN_GRANT_TYPE");
			AccessTokenByCodeRequest accessTokenByCodeRequest = new AccessTokenByCodeRequest();
			accessTokenByCodeRequest.setCode(code);
			accessTokenByCodeRequest.setAppid(appId);
			accessTokenByCodeRequest.setSecret(secret);
			accessTokenByCodeRequest.setGrant_type(grantType);
			accessTokenByCodeResponse = wechatInterfService.getAccessTokenByCode(accessTokenByCodeRequest);
		}
		return accessTokenByCodeResponse;
	}
}
