package com.cirle.scientific.controller.pay;

import com.cirle.scientific.dao.OrderDao;
import com.cirle.scientific.dto.WxUerInfoDTO;
import com.cirle.scientific.po.SalesOrdersMain;
import com.cirle.scientific.pojo.Result;
import com.cirle.scientific.service.OrderService;
import com.cirle.scientific.service.WeixinService;
import com.cirle.scientific.utils.IpUtil;
import com.cirle.scientific.utils.QRCodeUtil;
import com.cirle.scientific.utils.weixin.WeiXinPay;
import com.cirle.scientific.utils.weixin.WeixinpayConfig;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

/**
 * 微信相关
 */
@Controller
@RequestMapping(value = "/weixin")
@Slf4j
public class WeixinController {

	@Autowired
	private WeixinService weixinService;

	@Autowired
	private OrderDao orderDao;

	@Autowired
	private OrderService orderService;

	/**
	 * jsapi支付
	 */
	@RequestMapping(value = "/jsapipay", method = RequestMethod.GET)
	public String jsapipay(
		HttpServletRequest request,
		@RequestAttribute(value = "memCard",required = false) String memCard,
		@RequestParam String code,
		@RequestParam String orderId,
		@RequestParam String redirectUrl
	) {
		log.info("进入微信公众号支付签名接口controller");
		log.info("微信授权返回code:"+code);
		log.info("当前用户memCard:"+memCard);

		//获取订单信息
		SalesOrdersMain ordersMain =  orderDao.getOrderInfo(orderId);

		if (ordersMain == null || ordersMain.getOrderId() == null) {
			log.warn("订单获取失败！");
			return "redirect:" + redirectUrl;
		}

		//客户端IP
		String ip = IpUtil.getIpAddr(request);
		log.info("ip:"+ip);

		WeiXinPay weiXinPay = new WeiXinPay();
			weiXinPay.setAppId(WeixinpayConfig.appId);
			weiXinPay.setAppSecret(WeixinpayConfig.appSecret);
			weiXinPay.setMchId(WeixinpayConfig.mchId);
			weiXinPay.setApiKey(WeixinpayConfig.apiKey);
			weiXinPay.setTradeType("JSAPI");
			weiXinPay.setIp(ip);
			weiXinPay.setCode(code);
			weiXinPay.setDeviceInfo("");

		//拼装订单信息
		weiXinPay = setOrderInfo(ordersMain, weiXinPay);

		//统一下单
		Map<String,String> wxInfo = weixinService.jsapipay(weiXinPay);

		if(wxInfo != null){
			redirectUrl += "&appId="+wxInfo.get("appId");
			redirectUrl += "&timeStamp="+wxInfo.get("timeStamp");
			redirectUrl += "&nonceStr="+wxInfo.get("nonceStr");
			redirectUrl += "&packages="+wxInfo.get("packages");
			redirectUrl += "&signType="+wxInfo.get("signType");
			redirectUrl += "&paySign="+wxInfo.get("paySign");
		}

		log.info("入微信公众号支付签名回掉url:"+redirectUrl);

		return "redirect:" + redirectUrl;
	}

	/**
	 * NATIVE支付
	 */
	@RequestMapping(value = "/nativepay", method = RequestMethod.GET)
	public String nativepay(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		log.info("进入扫码支付NATIVE支付controller");

		try {
			//订单号
			String orderId = request.getParameter("orderid").trim();
			//客户端IP
			String ip = IpUtil.getIpAddr(request);
			//获取订单信息
			SalesOrdersMain ordersMain =  orderDao.getOrderInfo(orderId);
			//ordersMain.setOrderSizes(0.01);
			request.setAttribute("orderInfo",ordersMain);

			//统一下单
			Map<String,String> wxInfo = weixinService.nativepay(ordersMain, ip);
			request.setAttribute("wxInfo",wxInfo);
			request.setAttribute("out_trade_no",orderId);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("生成二维码失败!");

		}

		return "web/pay/prepaidPay";
	}

	/**
	 * 微信h5支付签名
	 */
	@RequestMapping(value = "/mweb", produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public String mweb(HttpServletRequest request,
			@RequestAttribute(value = "memCard",required = false) String memCard,
			@RequestParam String orderId
	) throws ServletException, IOException {

		log.info("进入微信h5支付签名接口");

		if (orderId == null || "".equals(orderId)) {
			log.warn("微信h5支付签名接口请求参数有误,orderId为空或者不存在");
			return "";
		}

		//获取订单名称、描述、金额
		SalesOrdersMain ordersMain = orderDao.getOrderInfo(orderId);
		if (ordersMain == null) {
			log.warn("微信h5支付未查询到订单号为：" + orderId +"的订单");
			return "";
		}
		if(ordersMain.getStatus() == 1){
			log.warn("微信h5支付请求支付的订单已完成 ");
			return "";
		}

		// 客户端IP
		String ip = IpUtil.getIpAddr(request);
		log.info("ip:"+ip);

		String wap_name = "";
		if(ordersMain.getOrderType() == 1){
			wap_name = "\"美沃斯大会报名支付\"";
		}else{
			wap_name = "\"美沃斯线上课程购买支付\"";
		}

		WeiXinPay weiXinPay = new WeiXinPay();
		weiXinPay.setDeviceInfo("WEB");
		weiXinPay.setAppId(WeixinpayConfig.appId);
		weiXinPay.setAppSecret(WeixinpayConfig.appSecret);
		weiXinPay.setMchId(WeixinpayConfig.mchId);
		weiXinPay.setApiKey(WeixinpayConfig.apiKey);
		weiXinPay.setTradeType("MWEB");
		weiXinPay.setIp(ip);
		weiXinPay.setSceneInfo("{\"h5_info\": {\"type\":\"Wap\",\"wap_url\": \"http://www.btmculture.com\",\"wap_name\":"+wap_name+"}}");

		// 拼装订单信息
		weiXinPay = setOrderInfo(ordersMain, weiXinPay);

		// 统一下单
		String mweb_url = weixinService.mwebpay(weiXinPay);
		String redirect_url = "/web/v2/toWxPay/goodsInformation?orderType="+ordersMain.getOrderType()+"&objId="+ordersMain.getObjId()+"&ispackage="+ordersMain.getIspackage()+"&packDetailsId="+ordersMain.getPackDetailsId()+"&isCollage="+"&orderId="+ordersMain.getOrderId()+"&return_sign=pay";
		redirect_url = URLEncoder.encode(redirect_url, "UTF-8");
		mweb_url = mweb_url + "&redirect_url=" + redirect_url;
		log.info("微信h5支付签名接口返回值：" + mweb_url);

		return mweb_url;
	}

	@RequestMapping(value = "/payFinish")
	public String payFinish(HttpServletRequest request){
		log.info("支付成功跳转");
		String orderId = request.getParameter("out_trade_no").trim();

		log.info("获取订单号：" + orderId);
		String return_page = "/web/v2/home/index?orderId=" + orderId;
		SalesOrdersMain order = orderDao.getOrderInfo(orderId);
		if(order != null){
			if(order.getOrderType() == 2){
				//专栏
				return_page ="/web/v2/column/cDetail?columnId=" + order.getObjId();
			}else if(order.getOrderType() == 3){ // 会议
				//精品课
				if(order.getIspackage() == 0){ // 系列会议
//					return_page = "/web/v2/tq/sonDetail?courseId=" + order.getObjId();
					return_page = "/web/meeting/details?conferId=" + order.getObjId()+"&from=web";
				}else{ // 普通会员
//					return_page = "/web/v2/tq/detail?tqcourseId=" + order.getObjId();
					return_page = "/web/meeting/details?conferId=" + order.getObjId()+"&from=web";
				}
			}else if(order.getOrderType() == 7){
				//直播
				return_page = "/web/v2/live/lDetail?liveId=" + order.getObjId();
			}else if(order.getOrderType() == 4){
				//课件
				return_page = "/courseware/index?from=web";
			}
		}
		return "redirect:" + return_page;
	}



	/**
	 * 微信分享
	 */
	@ResponseBody
	@PostMapping("/share")
	public Result wxshare(@RequestParam String url) {
		Map<String,String> wxInfo = weixinService.wxshare(url);
		return Result.success(wxInfo);
	}

	protected WeiXinPay setOrderInfo(SalesOrdersMain ordersMain, WeiXinPay weiXinPay) {
		// 订单名称
		String body = ordersMain.getOrderName();
		// 订单号
		String outTradeNo = ordersMain.getOrderId();
		// 订单金额
		int totalFee = (int) (ordersMain.getOrderSizes() * 100);
		// 商品ID
		String productId = ordersMain.getProductId();

		weiXinPay.setBody(body);
		weiXinPay.setOutTradeNo(outTradeNo);
		weiXinPay.setTotalFee(totalFee);
		weiXinPay.setProductId(productId);

		return weiXinPay;
	}

	@GetMapping("/queryPayStatus")
	@ResponseBody
	@ApiModelProperty(value = "查询订单状态")
	public Result queryPayStatus(
			@RequestParam String orderNo
	) {
		Map<String,String> map = weixinService.queryPayStatus(orderNo);
		System.out.println("***获取查询订单map集合***:"+map);
		if (map == null){
			return Result.failed("支付出错了");
		}
		if (map.get("trade_state").equals("SUCCESS")){
			//支付成功,修改订单状态
			return Result.success("支付成功");
		}
		return Result.success("支付中...");
	}

		/*
		1.扫描二维码后，跳转到回调接口
		2.回调接口判断用户是否用系统绑定、获取用户基本信息
		3.跳转到生成海报页面
		4.分享朋友圈或微信好友
		*
		* */
	/**
	 * 获取专属海报
	 *
	 * @param objType
	 * @param openId
	 * @return
	 */
	@ApiOperation(value = "获取专属海报")
	@RequestMapping(value = "/getOwnPoster")
	public String getOwnPoster(@RequestParam Integer objType,
									 @RequestParam Long objId,
									 @RequestParam(value = "code", required = false) String code,
									 @RequestParam(value = "openId", required = false) String openId,
							   		 @RequestAttribute(value = "memCard",required = false) String memCard,
									 HttpServletRequest request) {


		//TODO 暂时注释获取用户信息，判断是否绑定，未绑定进行绑定
		//WxUerInfoDTO weixin =  weixinService.oauth2getAccessToken(code,memCard);
		WxUerInfoDTO  weixin =new WxUerInfoDTO();
		weixin.setNickname("测试昵称");
		weixin.setCity("北京");
		weixin.setHeadimgurl("https://www.qkyxzx.com/images/navlogo.svg");

		// 生成专属二维码
		String url = "https://www.qkyxzx.com";
		if (objType == 1) {
			//精品课
			url += "/course/courseDetails?from=web&id="+objId;
		} else if (objType == 2) {
			//直播
			url += "/live/detail?from=web&liveId="+objId;
		} else if (objType == 3) {
			//会议
			url += "/meeting/details?from=web&conferId="+objId;
		}
		String qrcode = QRCodeUtil.creatRrCode(url, 200, 200);

		request.setAttribute("qrcode", qrcode);
		if (weixin.getNickname().length() > 5) {
			weixin.setNickname(weixin.getNickname().substring(0, 3) + "...");
		}
		request.setAttribute("wxUserInfo", weixin);

		//业务逻辑处理
		Result objInfo = orderService.getObjInfo("", objType, objId, 0);
		Map<String, Object> dataInfo = (Map<String, Object>) objInfo.getData();
		request.setAttribute("dataInfo",dataInfo);
		//获取请求参数名信息
//		Enumeration enu = request.getParameterNames();
//		String key = "";
//		int a = 1;
//		while (enu.hasMoreElements()) {
//			key = (String) enu.nextElement();
//			//得到参数名
//			if (!"id".equals(key)) {
//				sb.append((a == 1 ? "?" : "&") + key + "=" + request.getParameter(key));
//				//获取参数值，同时进行拼装
//				a++;
//			}
//		}
		return "web/share/poster";
	}

	/**
	 * 去生成分享扫描的二维码
	 *
	 * @param objId      会议编号/直播id/课程id
	 * @param objType      1-精品课， 2-直播，3-会议
	 * @param request
	 */
	@ApiOperation(value = "去生成分享扫描的二维码")
	@RequestMapping(value = "/getShareQrCode")
	public String  getShareQrCode(@RequestParam Integer objType, @RequestParam Integer objId,
								HttpServletRequest request) {

		if(request.getSession().getAttribute("UserCard")==null){
			return "web/user/login";
		}
		String memCard = (String)request.getSession().getAttribute("UserCard");
		String callbackUrl = "https://www.qkyxzx.com/weixin/getOwnPoster?objType="+objType+"&objId="+objId+"&memCard="+memCard;
		try {

			String redirect_uri = URLEncoder.encode(callbackUrl, "GBK");
			//格式化，返回拼接后的url，去调微信的二维码
			String shareUrl = String.format(WeixinpayConfig.OPEN_OAUTH_URL, WeixinpayConfig.appId, redirect_uri);
			request.setAttribute("shareUrl", shareUrl);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return "web/share/share";
	}



//	public static void main(String[] args) {
//		//获取海报url(详情页)
//		String callbackUrl = "https://www.qkyxzx.com/meeting/details?from=web&conferId=28";
//		try {
//
//
//			//String redirect_uri = "https://www.qkyxzx.com/meeting/details?from=web&conferId=28?redirectUrl=" + localurl;
//			String redirect_uri = URLEncoder.encode(callbackUrl, "GBK");
//			String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxa35f548647a3fa20&redirect_uri=" + redirect_uri + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
//			//String OPEN_QRCODE_URL = "https://open.weixin.qq.com/connect/qrconnect?appid=wxa35f548647a3fa20&redirect_uri=" + redirect_uri + "response_type=code&scope=snsapi_login&state=STATE#wechat_redirect";
//			//格式化，返回拼接后的url，去调微信的二维码
//			String oauthUrl = String.format(WeixinpayConfig.OPEN_OAUTH_URL,WeixinpayConfig.appId,callbackUrl);
//			System.out.println(url);
//			//System.out.println(OPEN_QRCODE_URL);
//		} catch (UnsupportedEncodingException e) {
//			e.printStackTrace();
//		}
//	}
}


