package com.cyksj.web.controller.mirrorshop;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.config.zfb.BaseZfbConfig;
import com.cyksj.config.zfb.ZfbProductCode;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.mirrorshop.UserMirrorShopFeeOrderDonMapper;
import com.cyksj.mapper.mirrorshop.UserMirrorShopMapper;
import com.cyksj.model.dto.AliPayParams;
import com.cyksj.model.entity.UserMirrorShop;
import com.cyksj.model.entity.UserMirrorShopFeeOrderDon;
import com.cyksj.model.request.AlipayOrderDonReq;
import com.cyksj.model.request.UserMirrorShopSubmitReq;
import com.cyksj.model.response.AliPayTradeStatus;
import com.cyksj.model.views.UserMirrorShopAdvertiseFrontView;
import com.cyksj.model.views.UserMirrorShopInfoView;
import com.cyksj.service.order.UserMirrorShopOrderService;
import com.cyksj.web.util.StpUserUtil;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.SearchResult;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

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

/**
 * 项目名: yhlxj2
 * 文件名: UserMirrorShopFrontController
 * 创建者: JavaZou
 * 创建时间:2024/10/25 15:53
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/applets/mirror/shop")
public class UserMirrorShopFrontController {
	private final BeanSearcher beanSearcher;

	private final HttpServletRequest request;

	private final UserMirrorShopOrderService userMirrorShopOrderService;

	private final UserMirrorShopMapper userMirrorShopMapper;

	private final UserMirrorShopFeeOrderDonMapper userMirrorShopFeeOrderDonMapper;

	/**
	 * 镜像店铺主 个人信息
	 */
	@GetMapping("/get/detail/{customId}")
	public Result<UserMirrorShopInfoView> getShopDetail(@PathVariable String customId) {
		UserMirrorShopInfoView userMirrorShopInfoView = beanSearcher.searchFirst(UserMirrorShopInfoView.class, MapUtils.flatBuilder(request.getParameterMap()).field(UserMirrorShopInfoView::getCustomId, customId).build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(userMirrorShopInfoView);
	}

	/**
	 * 用户镜像店铺广告列表
	 */
	@GetMapping("/get/advertise/{customId}")
	public Result<SearchResult<UserMirrorShopAdvertiseFrontView>> getAdvertise(@PathVariable String customId) {
		SearchResult<UserMirrorShopAdvertiseFrontView> search = beanSearcher.search(UserMirrorShopAdvertiseFrontView.class, MapUtils.flatBuilder(request.getParameterMap())
				.put("cm", String.format(" and um.custom_id = '%s'", customId))
				.build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}


	/**
	 * 用户开店信息
	 */
	@GetMapping("/get/user/shop")
	public Result<UserMirrorShop> getUserShop() {
		long userId = StpUserUtil.getLoginIdAsLong();
		UserMirrorShop userMirrorShop = userMirrorShopMapper.selectOne(Wrappers.lambdaQuery(UserMirrorShop.class)
				.eq(UserMirrorShop::getUserId, userId)
				.last("limit 1")
				.select(UserMirrorShop::getCustomId, UserMirrorShop::getName, UserMirrorShop::getContact, UserMirrorShop::getLogo, UserMirrorShop::getStatus, UserMirrorShop::getQrCode));

		if (userMirrorShop != null) {
			UserMirrorShopFeeOrderDon userMirrorShopFeeOrderDon = userMirrorShopFeeOrderDonMapper.selectOne(Wrappers.lambdaQuery(UserMirrorShopFeeOrderDon.class)
					.eq(UserMirrorShopFeeOrderDon::getUserId, userId)
					.eq(UserMirrorShopFeeOrderDon::getStatus, UserMirrorShopFeeOrderDon.Status.hasPayment)
					.last("limit 1"));
			userMirrorShop.setJoinFeeStatus(userMirrorShopFeeOrderDon != null ? true : false);
		}
		return GatewayResponse.SUCCESS.newBuilder().toResult(userMirrorShop);
	}

	/**
	 * 立即开店
	 */
	@PostMapping("/submit")
	public Result<UserMirrorShopFeeOrderDon> submit(@RequestBody UserMirrorShopSubmitReq shopSubmitReq) throws Exception {
		long userId = StpUserUtil.getLoginIdAsLong();
		shopSubmitReq.setUserId(userId);
		UserMirrorShopFeeOrderDon feeOrderDon = userMirrorShopOrderService.submitOpenShop(shopSubmitReq);
		return GatewayResponse.SUCCESS.newBuilder().toResult(feeOrderDon);
	}


	/**
	 * 支付宝web支付
	 */
	@PostMapping("/zfb/orderQrCode")
	public Result<String> zfbWebQrCode(@RequestBody @Validated AlipayOrderDonReq re) throws Exception {
		AliPayParams aliPayParams = userMirrorShopOrderService.aliPay(re, ZfbProductCode.PC_WEB.getProductCode(), BaseZfbConfig.qrPayMode_orderCode);
		return GatewayResponse.SUCCESS.newBuilder().toResult(aliPayParams.getBody());
	}

	/**
	 * 支付宝表单支付
	 * 手机支付
	 */
	@PostMapping("/pay/zfb")
	public Result<String> aliPay(@RequestBody @Validated AlipayOrderDonReq re) throws Exception {
		AliPayParams aliPayParams = userMirrorShopOrderService.aliPay(re, ZfbProductCode.MOBILE_WEB.getProductCode(), null);
		return GatewayResponse.SUCCESS.newBuilder().toResult(aliPayParams.getBody());
	}

	/**
	 * 订单支付状态
	 */
	@GetMapping("/get/order/status/{orderId}")
	public Result<UserMirrorShopFeeOrderDon> getFeeOrderStatusById(@PathVariable Long orderId) {
		if (orderId < 1) {
			throw BusinessRuntimeException.getInstance("订单不存在");
		}
		UserMirrorShopFeeOrderDon orderDonView = beanSearcher.searchFirst(UserMirrorShopFeeOrderDon.class, MapUtils.builder()
				.field(UserMirrorShopFeeOrderDon::getId, orderId)
				.build());
		if (orderDonView == null) {
			throw BusinessRuntimeException.getInstance("订单不存在");
		}
		return GatewayResponse.SUCCESS.newBuilder().toResult(orderDonView);
	}

	/**
	 * 支付宝回调
	 */
	@PostMapping("/prepay/zfb/notify")
	public String aliPayNotify(HttpServletRequest request) throws Exception {
		////将异步通知中收到的所有参数都存放到map中
		Map<String, String> params = convertRequestParamsToMap(request);
		String tradeStatus = params.get("trade_status");
		String orderNo = params.get("out_trade_no");
		if (AliPayTradeStatus.TRADE_SUCCESS.getStatus().equals(tradeStatus) || AliPayTradeStatus.TRADE_FINISHED.getStatus().equals(tradeStatus)) {
			log.info("支付宝商家订单号orderNo:{},status:{}开始回调", orderNo, tradeStatus);
			userMirrorShopOrderService.aliPayNotify(params);
		} else {
			log.error("支付宝回调 error 状态不符合 成功或完成 status:{} ,orderNo:{}", tradeStatus, orderNo);
			return "fail";
		}
		return "success";
	}



	/**
	 * 获取支付宝回调参数
	 */
	private static Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
		Map<String, String> retMap = new HashMap<>();
		Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();
		for (Map.Entry<String, String[]> entry : entrySet) {
			String name = entry.getKey();
			String[] values = entry.getValue();
			int valLen = values.length;
			if (valLen == 1) {
				retMap.put(name, values[0]);
			} else if (valLen > 1) {
				StringBuilder sb = new StringBuilder();
				for (String val : values) {
					sb.append(",").append(val);
				}
				retMap.put(name, sb.substring(1));
			} else {
				retMap.put(name, "");
			}
		}
		return retMap;
	}
}
