package com.cyksj.web.controller.zfb;

import cn.hutool.json.JSONObject;
import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.util.Jsons;
import com.cyksj.config.zfb.BaseZfbConfig;
import com.cyksj.mapper.ZfbShopOrderDayLimitMapper;
import com.cyksj.mapper.channel.ShopConfigMapper;
import com.cyksj.model.entity.ZfbShopOrderDayLimit;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * 项目名: yhlxj2
 * 文件名: ZfbAsyncNotifyInfoController
 * 创建者: JavaZou
 * 创建时间:2024/11/29 9:56
 * 支付宝异步通知信息
 */
@Slf4j
@RequestMapping("/alipay/async/notify")
@RestController
@RequiredArgsConstructor
public class ZfbAsyncNotifyInfoController {
	private final ShopConfigMapper shopConfigMapper;

	private final ZfbShopOrderDayLimitMapper zfbShopOrderDayLimitMapper;

	@PostMapping("/handle")
	public String alipayAsyncNotify(HttpServletRequest request) throws Exception {
		Map<String, String> params = convertRequestParamsToMap(request);
		String appId = params.get("app_id");
		log.info("支付宝异步信息回调信息:{}", params);
		boolean signVerified = AlipaySignature.rsaCheckV1(params, shopConfigMapper.getByAppId(appId).getPublicKey(), BaseZfbConfig.charset, BaseZfbConfig.signType);
		if (!signVerified) {
			log.error("{}异步信息回调校验签名错误,自定义入参", appId);
			return "fail";
		}
		String notifyType = params.get("notify_type");
		//非商户变更通知回调 不处理
		if (!"merchant_status_update".equals(notifyType)) {
			return "success";
		}
		log.info("开始处理商户:{}状态变更回调信息", appId);
		String bizContent = request.getParameter("biz_content");

		JSONObject re = Jsons.parseObject(bizContent, JSONObject.class);

		/**
		 * NORMAL	正常状态，商户账户功能可用，无限制。
		 * FROZEN	冻结状态，商户账户受到限制，可能是由于违规操作、账户风险等。
		 * CLOSED	关闭状态，商户账户已被关闭，不可使用。
		 * LIMITED	限制状态，商户账户部分功能受限。
		 * AUDITING	审核中，商户信息或账户正在审核中，暂时不可用。
		 * AUDIT_REJECT	审核未通过，商户信息审核失败，账户不可用。
		 * TERMINATED	商户终止合作，账户已永久关闭。
		 */
		String status = re.getStr("status");
		log.info("{}商户目前状态：{}", appId, status);
		if (!"NORMAL".equals(status)) {
			ZfbShopOrderDayLimit dayLimit = zfbShopOrderDayLimitMapper.selectOne(Wrappers.lambdaQuery(ZfbShopOrderDayLimit.class)
					.eq(ZfbShopOrderDayLimit::getAppId, appId)
					.last("limit 1"));
			if (dayLimit != null) {
				dayLimit.setStatus(false);
				zfbShopOrderDayLimitMapper.updateById(dayLimit);
			}
		}
		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;
	}
}
