package com.jsowell.api.uniapp;

import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.ImmutableMap;
import com.jsowell.common.annotation.Anonymous;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.core.redis.RedisCache;
import com.jsowell.common.enums.ykc.ReturnCodeEnum;
import com.jsowell.common.enums.ykc.ScenarioEnum;
import com.jsowell.common.exception.BusinessException;
import com.jsowell.common.response.RestApiResponse;
import com.jsowell.common.util.StringUtils;
import com.jsowell.common.util.id.IdUtils;
import com.jsowell.pile.dto.GetPayModeDTO;
import com.jsowell.pile.dto.PayOrderDTO;
import com.jsowell.pile.dto.PaymentScenarioDTO;
import com.jsowell.pile.dto.WeixinPayDTO;
import com.jsowell.pile.vo.uniapp.PayModeVO;
import com.jsowell.service.MemberService;
import com.jsowell.service.OrderService;
import com.jsowell.wxpay.dto.WeChatRefundDTO;
import com.jsowell.wxpay.response.WechatPayNotifyParameter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 支付相关controller
 */
@Anonymous
@RestController
@RequestMapping("/uniapp/pay")
public class PayController extends BaseController {
	@Autowired
	private MemberService memberService;

	@Autowired
	private OrderService orderService;

	@Autowired
	private RedisCache redisCache;

	/**
	 * 充值余额支付
	 * 提供给小程序使用
	 * http://localhost:8080/uniapp/pay/weixinPay
	 */
	@PostMapping("/weixinPay")
	public RestApiResponse<?> weixinPay(HttpServletRequest request, @RequestBody WeixinPayDTO dto) {
		logger.info("微信支付 param:{}", dto.toString());
		RestApiResponse<?> response;
		try {
			if (StringUtils.isBlank(dto.getCode()) || StringUtils.isBlank(dto.getAmount())) {
				return new RestApiResponse<>(ReturnCodeEnum.CODE_PARAM_NOT_NULL_ERROR);
			}
			// 鉴权
			String memberId = getMemberIdByAuthorization(request);
			if (StringUtils.isBlank(memberId)) {
				throw new BusinessException(ReturnCodeEnum.CODE_TOKEN_ERROR);
			}
			dto.setMemberId(memberId);
			String openId = memberService.getOpenIdByCode(dto.getCode());
			if (StringUtils.isBlank(openId)) {
				throw new BusinessException(ReturnCodeEnum.CODE_GET_OPEN_ID_BY_CODE_ERROR);
			}
			dto.setOpenId(openId);
			// 充值余额 附加参数
			PaymentScenarioDTO paymentScenarioDTO = new PaymentScenarioDTO();
			paymentScenarioDTO.setType(ScenarioEnum.BALANCE.getValue());
			paymentScenarioDTO.setMemberId(memberId);
			dto.setAttach(JSONObject.toJSONString(paymentScenarioDTO));
			dto.setDescription("会员充值余额");
			Map<String, Object> weixinMap = orderService.weixinPayV3(dto);
			response = new RestApiResponse<>(ImmutableMap.of("weixinMap", weixinMap));
		} catch (Exception e) {
			response = new RestApiResponse<>();
		}
		return response;
	}


	/**
	 * 会员充值余额 汇付
	 * http://localhost:8080/uniapp/pay/rechargeBalance
	 */
	@PostMapping("/rechargeBalance")
	public RestApiResponse<?> rechargeBalance(HttpServletRequest request, @RequestBody WeixinPayDTO dto) {
		logger.info("adapay会员充值余额 param:{}", dto.toString());
		RestApiResponse<?> response;
		try {
			if (StringUtils.isBlank(dto.getCode()) || StringUtils.isBlank(dto.getAmount())) {
				return new RestApiResponse<>(ReturnCodeEnum.CODE_PARAM_NOT_NULL_ERROR);
			}
			// 鉴权
			String memberId = getMemberIdByAuthorization(request);
			if (StringUtils.isBlank(memberId)) {
				throw new BusinessException(ReturnCodeEnum.CODE_TOKEN_ERROR);
			}
			dto.setMemberId(memberId);
			String openId = memberService.getOpenIdByCode(dto.getCode());
			if (StringUtils.isBlank(openId)) {
				throw new BusinessException(ReturnCodeEnum.CODE_GET_OPEN_ID_BY_CODE_ERROR);
			}
			dto.setOpenId(openId);
			// 充值余额 附加参数
			Map<String, Object> weixinMap = memberService.rechargeBalanceWithAdapay(dto);
			response = new RestApiResponse<>(ImmutableMap.of("weixinMap", weixinMap));
		} catch (Exception e) {
			response = new RestApiResponse<>();
		}
		return response;
	}

	/**
	 * 7002 支付订单
	 * http://localhost:8080/uniapp/pay/payOrder
	 *
	 * @param request
	 * @param dto
	 * @return
	 */
	@PostMapping("/payOrder")
	public RestApiResponse<?> payOrder(HttpServletRequest request, @RequestBody PayOrderDTO dto) {
		logger.info("wechatpay支付订单 param:{}", dto.toString());
		RestApiResponse<?> response;

		// 支付订单加锁
		String lockKey = "pay_order_" + dto.getOrderCode();
		String lockValue = IdUtils.fastUUID();
		try {
			String memberId = getMemberIdByAuthorization(request);
			if (StringUtils.isBlank(memberId)) {
				throw new BusinessException(ReturnCodeEnum.CODE_TOKEN_ERROR);
			}
			if (dto.getPayAmount() == null) {
				throw new BusinessException(ReturnCodeEnum.CODE_PARAM_NOT_NULL_ERROR);
			}
			dto.setMemberId(memberId);
			dto.setLockValue(lockValue);
			// redis锁
			Boolean isLock = redisCache.lock(lockKey, lockValue, 60);
			Map<String, Object> map = null;
			if (isLock) {
				map = orderService.payOrder(dto);
			}
			response = new RestApiResponse<>(map);
		} catch (BusinessException e) {
			logger.warn("wechatpay支付订单 warn param:{}", dto.toString(), e);
			response = new RestApiResponse<>(e.getCode(), e.getMessage());
		} catch (Exception e) {
			logger.error("wechatpay支付订单 error param:{}", dto.toString(), e);
			response = new RestApiResponse<>(ReturnCodeEnum.CODE_ORDER_PAY_ERROR);
		} finally {
			// 支付订单解锁
			if (lockValue.equals(redisCache.getCacheObject(lockKey).toString())) {
				redisCache.unLock(lockKey);
			}
		}
		logger.info("wechatpay支付订单 result:{}", JSONObject.toJSONString(response));
		return response;
	}

	/**
	 * 使用adapay支付订单
	 * http://localhost:8080/uniapp/pay/payOrderWithAdapay
	 * @param request
	 * @param dto
	 * @return
	 */
	@PostMapping("/payOrderWithAdapay")
	public RestApiResponse<?> payOrderWithAdapay(HttpServletRequest request, @RequestBody PayOrderDTO dto) {
		logger.info("adapay支付订单 param:{}", dto.toString());
		RestApiResponse<?> response;

		// 支付订单加锁
		String lockKey = "pay_order_" + dto.getOrderCode();
		String lockValue = IdUtils.fastUUID();
		try {
			String memberId = getMemberIdByAuthorization(request);
			if (StringUtils.isBlank(memberId)) {
				throw new BusinessException(ReturnCodeEnum.CODE_TOKEN_ERROR);
			}
			if (dto.getPayAmount() == null) {
				throw new BusinessException(ReturnCodeEnum.CODE_PARAM_NOT_NULL_ERROR);
			}
			dto.setMemberId(memberId);
			dto.setLockValue(lockValue);
			// redis锁
			Boolean isLock = redisCache.lock(lockKey, lockValue, 60);
			Map<String, Object> map = null;
			if (isLock) {
				map = orderService.payOrderWithAdapay(dto);
			}
			response = new RestApiResponse<>(map);
		} catch (BusinessException e) {
			logger.warn("adapay支付订单 warn param:{}", dto.toString(), e);
			response = new RestApiResponse<>(e.getCode(), e.getMessage());
		} catch (Exception e) {
			logger.error("adapay支付订单 error param:{}", dto.toString(), e);
			response = new RestApiResponse<>(ReturnCodeEnum.CODE_ORDER_PAY_ERROR);
		} finally {
			// 支付订单解锁
			if (lockValue.equals(redisCache.getCacheObject(lockKey).toString())) {
				redisCache.unLock(lockKey);
			}
		}
		logger.info("adapay支付订单 result:{}", JSONObject.toJSONString(response));
		return response;
	}

	/**
	 * 7003 获取支付方式
	 * http://localhost:8080/uniapp/pay/getPayMode
	 */
	@PostMapping("/getPayMode")
	public RestApiResponse<?> getPayMode(HttpServletRequest request, @RequestBody GetPayModeDTO dto) {
		RestApiResponse<?> response;
		try {
			dto.setMemberId(getMemberIdByAuthorization(request));
			List<PayModeVO> list = orderService.getPayMode(dto);
			response = new RestApiResponse<>(ImmutableMap.of("list", list));
		} catch (BusinessException e) {
			logger.warn("获取支付方式 warn param:{}", dto.toString(), e);
			response = new RestApiResponse<>(e.getCode(), e.getMessage());
		} catch (Exception e) {
			logger.error("获取支付方式 error param:{}", dto.toString(), e);
			response = new RestApiResponse<>(ReturnCodeEnum.CODE_GET_PAY_MODE);
		}
		return response;
	}

	/**
	 * 微信支付回调接口
	 * http://localhost:8080/uniapp/pay/callback
	 * https://api.jsowellcloud.com/uniapp/pay/wechatPayCallback
	 */
	@PostMapping("/wechatPayCallback")
	public RestApiResponse<?> wechatPayCallback(HttpServletRequest request, @RequestBody WechatPayNotifyParameter body) {
		logger.info("1----------->微信支付回调开始 body:{}", JSONObject.toJSONString(body));
		RestApiResponse<?> response;
		try {
			orderService.wechatPayCallback(request, body);
			response = new RestApiResponse<>();
		} catch (BusinessException e) {
			logger.warn("微信支付回调接口warn", e);
			response = new RestApiResponse<>(e.getCode(), e.getMessage());
		} catch (Exception e) {
			logger.error("微信支付回调接口error", e);
			response = new RestApiResponse<>(ReturnCodeEnum.CODE_ORDER_PAY_CALLBACK_ERROR);
		}
		return response;
	}

	/**
	 * 微信退款回调接口
	 * @param request
	 * @param body
	 * @return
	 */
	@PostMapping("/wechatPayRefundCallback")
	public RestApiResponse<?> wechatPayRefundCallback(HttpServletRequest request, @RequestBody WechatPayNotifyParameter body) {
		logger.info("微信退款回调接口 body:{}", JSONObject.toJSONString(body));
		RestApiResponse<?> response;
		try {
			orderService.wechatPayRefundCallback(request, body);
			response = new RestApiResponse<>();
		} catch (BusinessException e) {
			logger.warn("微信退款回调接口warn", e);
			response = new RestApiResponse<>(e.getCode(), e.getMessage());
		} catch (Exception e) {
			logger.error("微信退款回调接口error", e);
			response = new RestApiResponse<>(ReturnCodeEnum.CODE_ORDER_PAY_CALLBACK_ERROR);
		}
		return response;
	}

	/**
	 * 微信退款接口
	 * https://api.jsowellcloud.com/uniapp/pay/refund
	 */
	@PostMapping("/refund")
	public RestApiResponse<?> weChatRefund(HttpServletRequest request, @RequestBody WeChatRefundDTO dto) {
		RestApiResponse<?> response;
		try {
			if (dto.getRefundAmount() == null) {
				throw new BusinessException(ReturnCodeEnum.CODE_PARAM_NOT_NULL_ERROR);
			}
			String memberId = getMemberIdByAuthorization(request);
			if (StringUtils.isBlank(memberId)) {
				throw new BusinessException(ReturnCodeEnum.CODE_TOKEN_ERROR);
			}
			dto.setMemberId(memberId);
			dto.setRefundType("2");
			orderService.weChatRefund(dto);
			response = new RestApiResponse<>();
		} catch (BusinessException e) {
			logger.warn("微信退款接口 warn", e);
			response = new RestApiResponse<>(e.getCode(), e.getMessage());
		} catch (Exception e) {
			logger.error("微信退款接口 error", e);
			response = new RestApiResponse<>(ReturnCodeEnum.CODE_WEIXIN_REFUND_ERROR);
		}
		return response;
	}

	/**
	 * 汇付支付退款
	 * 用户余额退款
	 * https://api.jsowellcloud.com/uniapp/pay/adapayRefund
	 */
	@PostMapping("/adapayRefund")
	public RestApiResponse<?> adapayRefund(HttpServletRequest request, @RequestBody WeChatRefundDTO dto) {
		RestApiResponse<?> response;
		try {
			if (dto.getRefundAmount() == null) {
				throw new BusinessException(ReturnCodeEnum.CODE_PARAM_NOT_NULL_ERROR);
			}
			String memberId = getMemberIdByAuthorization(request);
			if (StringUtils.isBlank(memberId)) {
				throw new BusinessException(ReturnCodeEnum.CODE_TOKEN_ERROR);
			}
			dto.setMemberId(memberId);
			dto.setRefundType("2");
			orderService.adapayRefund(dto);
			response = new RestApiResponse<>();
		} catch (BusinessException e) {
			logger.warn("汇付支付退款接口 warn", e);
			response = new RestApiResponse<>(e.getCode(), e.getMessage());
		} catch (Exception e) {
			logger.error("汇付支付退款接口 error", e);
			response = new RestApiResponse<>(ReturnCodeEnum.CODE_WEIXIN_REFUND_ERROR);
		}
		return response;
	}

	/**
	 * 汇付支付回调
	 * <a href="https://api.jsowellcloud.com/uniapp/pay/adapayCallback">...</a>
	 */
	@PostMapping("/adapayCallback")
	public void adapayCallback(HttpServletRequest request) {
		try {
			orderService.adapayCallback(request);
		} catch (Exception e) {
			logger.error("汇付支付回调失败 error", e);
		}
	}

	/**
	 * 汇付退款回调接口
	 * https://api.jsowellcloud.com/uniapp/pay/adapayRefundCallback
	 * @param request
	 */
	@PostMapping("/adapayRefundCallback")
	public void adapayRefundCallback(HttpServletRequest request) {
		try {
			orderService.adapayRefundCallback(request);
		} catch (Exception e) {
			logger.error("汇付支付退款回调失败 error", e);
		}
	}
}
