package com.fs.app.pay.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.fs.app.annotation.Login;
import com.fs.app.pay.bean.AliPayBean;
import com.fs.common.core.domain.R;
import com.fs.company.domain.CompanyUser;
import com.fs.company.service.ICompanyUserService;
import com.fs.store.domain.FsStorePayment;
import com.fs.store.mapper.FsStorePaymentMapper;
import com.fs.store.param.FsStorePaymentPayParam;
import com.fs.store.service.IFsStorePaymentService;
import com.ijpay.alipay.AliPayApi;
import com.ijpay.alipay.AliPayApiConfig;
import com.ijpay.alipay.AliPayApiConfigKit;
import com.ijpay.core.kit.PayKit;
import com.ijpay.core.kit.RsaKit;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Controller
@RequestMapping("/app/aliPay")
public class AliPayController extends AliPayApiController {

	private static final Logger log = LoggerFactory.getLogger(AliPayController.class);

	@Autowired
	private AliPayBean aliPayBean;
	@Autowired
	private IFsStorePaymentService storePaymentService;
	@Autowired
	private ICompanyUserService companyUserService;
	/**
	 * 普通公钥模式
	 */
//     private final static String NOTIFY_URL = "/app/aliPay/payNotify";
	/**
	 * 证书模式
	 */
	private final static String NOTIFY_URL = "/app/aliPay/payNotify";
	private final static String RETURN_URL = "/#/pages/success";
	/**
	 * 证书模式
	 */
	//private final static String RETURN_URL = "/aliPay/cert_return_url";



	@Override
	public AliPayApiConfig getApiConfig() throws AlipayApiException {

		AliPayApiConfig aliPayApiConfig;
		try {
			aliPayApiConfig = AliPayApiConfigKit.getApiConfig(aliPayBean.getAppId());
		} catch (Exception e) {
			aliPayApiConfig = AliPayApiConfig.builder()
					.setAppId(aliPayBean.getAppId())
					.setAliPayPublicKey(aliPayBean.getPublicKey())
					.setAppCertPath(aliPayBean.getAppCertPath())
					.setAliPayCertPath(aliPayBean.getAliPayCertPath())
					.setAliPayRootCertPath(aliPayBean.getAliPayRootCertPath())
					.setCharset("UTF-8")
					.setPrivateKey(aliPayBean.getPrivateKey())
					.setServiceUrl(aliPayBean.getServerUrl())
					.setSignType("RSA2")
					// 普通公钥方式
					.build();
					// 证书模式
//					.buildByCert();

		}

		return aliPayApiConfig;
	}
	@ApiOperation(value="支付宝APP支付Test",notes="支付宝APP支付Test")
	@RequestMapping(value = "/test",method = RequestMethod.POST)
	@ResponseBody
	public AliPayApiConfig test() {
		AliPayApiConfig aliPayApiConfig = AliPayApiConfigKit.getAliPayApiConfig();
		String charset = aliPayApiConfig.getCharset();
		log.info("charset>" + charset);
		return aliPayApiConfig;
	}




	/**
         * app支付
         */
	@ApiOperation(value="支付宝APP支付",notes="支付宝APP支付")
	@RequestMapping(value = "/wapPay",method = RequestMethod.POST)
	@ResponseBody
	public R wapPay(@Validated @RequestBody FsStorePaymentPayParam param, HttpServletRequest request){
		try {
			CompanyUser companyUser=companyUserService.selectCompanyUserById(param.getCompanyUserId());
			String orderSn = IdUtil.getSnowflake(0, 0).nextIdStr();
			AliPayApiConfig aliPayApiConfig = AliPayApiConfigKit.getAliPayApiConfig();
			Map<String, String> paramsMap = new HashMap<>();
			paramsMap.put("app_id", aliPayApiConfig.getAppId());
			paramsMap.put("method", "alipay.trade.wap.pay");
			paramsMap.put("return_url",aliPayBean.getReturnDomain() +  RETURN_URL);
			paramsMap.put("charset", aliPayApiConfig.getCharset());
			paramsMap.put("sign_type", aliPayApiConfig.getSignType());
			paramsMap.put("timestamp", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
			paramsMap.put("version", "1.0");
			paramsMap.put("notify_url", aliPayBean.getDomain() + NOTIFY_URL);

			Map<String, String> bizMap = new HashMap<>();
			bizMap.put("body", "超重/肥胖/气血/代谢/慢病医学管理方案服务");
			bizMap.put("subject", "支付");
			bizMap.put("out_trade_no","payment-"+orderSn);
			bizMap.put("total_amount", param.getPayMoney().toString());
			bizMap.put("product_code", "QUICK_WAP_WAY");
			paramsMap.put("biz_content", JSON.toJSONString(bizMap));
			String content = PayKit.createLinkString(paramsMap);
			System.out.println(content);
			String encrypt =  RsaKit.encryptByPrivateKey(content, aliPayApiConfig.getPrivateKey());
			System.out.println(encrypt);
//            encrypt = AlipaySignature.rsaSign(content,aliPayApiConfig.getPrivateKey(), "UTF-8","RSA2");
//            System.out.println(encrypt);
			paramsMap.put("sign", encrypt);
			String url = aliPayApiConfig.getServiceUrl() + "?" + PayKit.createLinkString(paramsMap, true);
			FsStorePayment storePayment=new FsStorePayment();
			storePayment.setCompanyId(param.getCompanyId());
			storePayment.setCompanyUserId(param.getCompanyUserId());
			storePayment.setStatus(0);
			storePayment.setPayCode(orderSn);
			storePayment.setPayMoney(param.getPayMoney());
			storePayment.setCreateTime(new Date());
			storePayment.setPayTypeCode("alipay");
			storePayment.setBusinessType(1);
			storePayment.setRemark(param.getRemark());
			storePayment.setDeptId(companyUser.getDeptId());
			storePaymentService.insertFsStorePayment(storePayment);

			return R.ok().put("data",url);
		} catch (Exception e) {
			return R.error(e.getMessage());
		}
	}

	@RequestMapping(value = "/payNotify")
	@ResponseBody
	public String payNotify(HttpServletRequest request) {
		Map<String, String> params = AliPayApi.toMap(request);
		for (Map.Entry<String, String> entry : params.entrySet()) {
			System.out.println(entry.getKey() + " = " + entry.getValue());
		}
		boolean verifyResult = false;
		try {
			verifyResult = AlipaySignature.rsaCheckV1(params, aliPayBean.getPublicKey(), "UTF-8", "RSA2");
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}
		if (verifyResult) {// 验证成功
			// TODO 请在这里加上商户的业务逻辑程序代码 异步通知可能出现订单重复通知 需要做去重处理
			System.out.println("notify_url 验证成功succcess");
			String trade_status = params.get("trade_status");
			//交易支付成功
			if (trade_status.equals("TRADE_SUCCESS")) {
				//更新订单信息
				String transaction_id = params.get("trade_no");
				String out_trade_no = params.get("out_trade_no");
				String[] order = out_trade_no.split("-");
				switch (order[0]) {
					case "payment":
						return storePaymentService.payConfirm(order[1], transaction_id, "", "");
				}
				return "success";
			} else {
				System.out.println("notify_url 验证失败");
				// TODO
				return "failure";
			}

		}
		return "failure";
	}

}
