package com.malk.dongfangxinhua.controller;

/**
 * 错误抛出与拦截详见 CatchException
 */

import cn.hutool.core.util.XmlUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.XML;
import com.malk.server.common.McException;
import com.malk.server.common.McR;
import com.malk.utils.UtilMap;
import com.malk.utils.UtilServlet;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping
public class DFXHController {

    /// doc: http://47.111.179.216/interface/main.html#
    private static final String API = "http://27.115.15.66:8098/BisOutWeb/payCenter/dealReq.srv";

    /// xml请求
    private JSONObject _doPost(String tradeCode, Map condition) {

        // xml请求格式数据处理
        Map head = UtilMap.map("erpSysCode, custNo, tradeName", "XYYGLXT", "300200632", tradeCode);
        Map body = UtilMap.map("head, map", head, condition);
        String data = XmlUtil.mapToXmlStr(body, "body");
        log.info("请求入参, {}", XML.toJSONObject(data));

        /// prd 财资固定格式, xml头数据前需要添加类型code, 且不能换行
        data = "0000012001" + tradeCode + data;
        String rsp = HttpRequest.post(API).body(data).execute().body();
        JSONObject result = XML.toJSONObject(rsp);
        log.info("请求响应, {}", result);
        result = result.getJSONObject("body");

        // 错误拦截, 统一返回
        String message = result.getJSONObject("head").getStr("retMsg");
        McException.assertAccessException(!"查询成功".equals(message), message);

        return result;
    }

    /**
     * 查询联行号
     */
    @PostMapping("bank")
    McR bank(String name) {

        JSONObject rsp = _doPost("BY0004", UtilMap.map("bankTypeName, bankName", "银行", name));
        JSONArray list = rsp.getJSONObject("loopData").getJSONArray("row");

        return McR.success(list);
    }


    /**
     * 付款申请
     */
    @PostMapping("payment")
    McR payment(@RequestBody Map data) {

        // 付款: payerAccNo, payerCorpName; 领款: payeeAccNo, payeeAccName, payeeBankName, payeeBankCode; 金额: payMoney, payPurpose, erpReqNo
        JSONObject rsp = _doPost("BY0001", data);
        JSONObject state = rsp.getJSONObject("loopData").getJSONObject("row");

        return McR.success(state);
    }

    /**
     * 付款状态
     */
    @PostMapping("state")
    McR payment(String payNo) {

        JSONObject rsp = _doPost("BY0003", UtilMap.map("erpReqNo", payNo));
        JSONObject state = rsp.getJSONObject("loopData").getJSONObject("row");

        return McR.success(state);
    }


    /**
     * 付款账号同步
     */
    @PostMapping("sync")
    McR sync(HttpServletRequest request) {

        Map data = UtilServlet.getParamMap(request);
        log.info("付款账号同步, {}", data);

        // 查询付款账户


        // 更新付款信息
        

        return McR.success();
    }


    @PostMapping(value = "test")
    McR test(String name, HttpServletRequest request) {

//        XmlUtil.;

//        String rsp = UtilHttp.doPost(API, null, null, null, null);

//        String xmlData = "";
//        Document document = XmlUtil.parseXml(xmlData);

        StringBuffer reqXmlData = new StringBuffer();
        try {
            InputStream inputStream = request.getInputStream();
            String s;
            BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            while ((s = in.readLine()) != null) {
                reqXmlData.append(s);
            }
            in.close();
            inputStream.close();
        } catch (IOException e) {
            System.out.println("流解析xml数据异常!");
            e.printStackTrace();
        }
        //判断请求数据是否为空
        if (reqXmlData.length() <= 0) {
            System.out.println("请求数据为空!");
        }

        //json类型数据 [自动去掉标识]
        JSONObject jsonObject = XML.toJSONObject(reqXmlData.toString());
        log.info("xxxx,, {}", jsonObject);

        String data = reqXmlData.toString();
//        UtilHttp.doRequest(UtilHttp.METHOD.POST, API, null, null, jsonObject);

        log.info("xxx, {}", "0000012001BY0004<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\"" + jsonObject.toString());
        String rsp = HttpRequest.post(API).body(data).execute().body();
        log.info("xxx, {}", rsp);

        return McR.success(jsonObject.toString());
    }
}
