package com.qunzhixinxi.hnqz.admin.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.qunzhixinxi.hnqz.admin.api.constant.CacheConstants;
import com.qunzhixinxi.hnqz.admin.api.dto.OladingCommonRequest;
import com.qunzhixinxi.hnqz.admin.entity.OladingInputRecord;
import com.qunzhixinxi.hnqz.admin.service.gig.GigThirdApiService;
import com.qunzhixinxi.hnqz.admin.service.gig.OladingInputRecordService;
import com.qunzhixinxi.hnqz.admin.util.HMACSignProvider;
import com.qunzhixinxi.hnqz.common.log.annotation.SysLog;
import com.qunzhixinxi.hnqz.common.security.annotation.Inner;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 第三方零工接口
 *
 * @author lixuesong
 * @date 2022年04月17日 11:31
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/gig-third-api")
public class GigThirdApiController {

	private final GigThirdApiService gigThirdApiService;

	private final OladingInputRecordService oladingInputRecordService;

	private final RedisTemplate redisTemplate;

	private static final HMACSignProvider hMACSignProvide = new HMACSignProvider();

	/**
	 * 公钥 TODO 暂时没有
	 */
	private static final String PUBLIC_KEY = "123123123";

	/**
	 * 算法类型
	 */
	private static final String ALGORITHM_TYPE = "HmacSHA256";

	/**
	 * 自由职家统一请求地址
	 *
	 * @return
	 */
	@Inner(value = false)
	@SysLog("自由职家统一请求地址")
	@PostMapping("/olading")
	public void oladingRequest(@RequestParam(value = "req", required = false) String reqStr,
							   @RequestParam(required = false) String sign, HttpServletResponse response) {

		log.info("自由职家请求方法参数:req={}, sign={}", reqStr, sign);

		// 请求数据
		OladingCommonRequest.Req req = JSONUtil.toBean(reqStr, OladingCommonRequest.Req.class);
		// 请求接口名称
		String interfaceName = req.getName();
		// 请求data
		Map<String, Object> data = req.getData();
		// 请求requestId
		String requestId = (String) data.get("requestId");
		if (StrUtil.isBlank(requestId)) {
			requestId = (String) data.get("request_id");
		}
		String redisKey = String.format("%s_%s_%s", CacheConstants.OLADING_NOTIFY_KEY, interfaceName, requestId);
		Boolean absent = redisTemplate.opsForValue().setIfAbsent(redisKey, reqStr, 30, TimeUnit.MINUTES);
		if (!absent) {
			log.error("存在在途操作requestId={}", requestId);
			try {
				response.getWriter().write("SUCCESS");
				response.getWriter().flush();
			} catch (Exception e) {
				log.error("response返回异常", e);
			}
			return;
		}

		// 1.请求记录
		OladingInputRecord record = new OladingInputRecord();
		record.setRequestId(requestId);
		record.setInterfaceName(interfaceName);
		record.setReqBody(String.format("%s,%s", reqStr, sign));
		record.setPrivateKey("");
		record.setPublicKey("");
		oladingInputRecordService.save(record);

		try {
			// 2. 验签 TODO 暂不验签
//			boolean verfyResult =
//					hMACSignProvide.verfy(ALGORITHM_TYPE, PUBLIC_KEY, JSONUtil.toJsonStr(req.getData()), sign);
//			log.info("验签结果: {}", verfyResult);

			// 3.实际操作

			if (StrUtil.isNotBlank(requestId)) {
				try {
					// 睡3000ms，解决阿拉钉回调过快，找不到requestId的问题
					Thread.sleep(3000);
				} catch (Exception e) {
					log.warn("sleep异常", e);
				}

				gigThirdApiService.oladingNotify(requestId, req);
			}
		} catch (Exception e) {
			log.error("自由职家统一请求异常", e);
		} finally {
			redisTemplate.delete(redisKey);
			try {
				response.getWriter().write("SUCCESS");
				response.getWriter().flush();
			} catch (Exception e) {
				log.error("response返回异常", e);
			}
		}

	}

}
