package org.ta.pddserver.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.ta.pddserver.config.PddAPIConfig;
import org.ta.pddserver.config.YJTConfig;
import org.ta.pddserver.mapper.YjtLogMapper;
import org.ta.pddserver.model.pddjy.request.JYBaseRequestModel;
import org.ta.pddserver.rabbit.RabbitYJTSender;
import org.ta.pddserver.utils.HttpRequestHandlerTool;
import org.ta.pddserver.utils.JsonResponse;
import org.ta.pddserver.utils.PddHttpTool;
import org.ta.pddserver.utils.PddSignTool;

import java.util.Date;

@RestController
@RequestMapping("/yjt")
@Slf4j
public class YJTController {

//    @Resource
    private RabbitYJTSender rabbitYJTSender;

    @Value("${pdd.jyt}")
    private Integer jyt;

    @PostMapping("/toPdd")
    public Object sendToPDD(HttpServletRequest request) {
        String body = HttpRequestHandlerTool.getStringFromRequest(request);
        log.info("Receive YJT Request:\n{}", body);

        JSONObject jsonObject = JSON.parseObject(body);
        if (!PddSignTool.verifySignFromBody(jsonObject.getString("request"), YJTConfig.CLIENT_SECRET, jsonObject.getString("sign"))) {
            log.error("验签失败");
            return JsonResponse.generateOpenCommonFailedResponse(-1, "验签失败");
        }
        if (this.jyt > 0) {
            // 通过rabbit保存数据
            rabbitYJTSender.mqSaveMsgFromYjt(body, HttpRequestHandlerTool.getClientIP(request));
        }

        JYBaseRequestModel requestModel = new JYBaseRequestModel();
        requestModel.setRequest(jsonObject.getString("request"));
        requestModel.setRequest_id("" + new Date().getTime());
        requestModel.setType(jsonObject.getString("type"));
        requestModel.setTarget_client_id(PddAPIConfig.CLIENT_ID);
        requestModel.setClient_id(PddAPIConfig.CLIENT_ID);
        long time = new Date().getTime() / 1000;
        requestModel.setTimestamp(time);
        requestModel.setSign(PddSignTool.generateSign(requestModel, PddAPIConfig.CLIENT_SECRET));
        String resp = PddHttpTool.sendJsonPost(requestModel);
        return resp;
    }
}

