package com.jeequan.jeepay.mch.ctrl.paytest;

import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.db.entity.MchAppEntity;
import com.jeequan.jeepay.mch.ctrl.CommonCtrl;
import com.jeequan.jeepay.mch.websocket.server.WsPayOrderServer;
import com.jeequan.jeepay.service.impl.MchAppService;
import com.jeequan.jeepay.util.JeepayKit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Enumeration;

/*
* 支付测试 - 回调函数
*
* @author terrfly
*
* @date 2021/6/22 14:22
*/
@RestController
@RequestMapping("/api/anon/paytestNotify")
public class PaytestNotifyController extends CommonCtrl {

    @Autowired private MchAppService mchAppService;

    @RequestMapping("/payOrder")
    public void payOrderNotify() throws IOException {

//        // 本地调试！！！！！！
//        this.headerAndBodyPrint();

        //请求参数
        JSONObject params = getReqParamJSON();

        String mchNo = params.getString("mchNo");
        String appId = params.getString("appId");
        String sign = params.getString("sign");
        MchAppEntity mchAppEntity = mchAppService.getById(appId);
        if(mchAppEntity == null || !mchAppEntity.getMchNo().equals(mchNo)){
            response.getWriter().print("app is not exists");
            return;
        }

        params.remove("sign");
        if(!JeepayKit.getSign(params, mchAppEntity.getAppSecret()).equalsIgnoreCase(sign)){
            response.getWriter().print("sign fail");
            return;
        }

        JSONObject msg = new JSONObject();
        msg.put("state", params.getIntValue("state"));
        msg.put("errCode", params.getString("errCode"));
        msg.put("errMsg", params.getString("errMsg"));

        //推送到前端
        WsPayOrderServer.sendMsgByOrderId(params.getString("payOrderId"), msg.toJSONString());

        response.getWriter().print("SUCCESS");
    }

    // header和body打印， （用于测试）
    private void headerAndBodyPrint(){
        try {

            System.out.println("METHOD:" + request.getMethod());
            System.out.println("QUERYSTRING:" + request.getQueryString());

            // 查询到所有的header
            Enumeration<String> list = request.getHeaderNames();
            while (list.hasMoreElements()){
                String key = list.nextElement();
                System.out.println(key + ":" + request.getHeader(key));
            }

            String body = "";
            String str;
            while((str = request.getReader().readLine()) != null){
                body += str;
            }
            System.out.println("BODY: " + body);
        } catch (IOException e) {
            logger.error("error", e);
        }
    }



}
