package com.seeyon.apps.src_hxinvoice.servlet;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.seeyon.apps.src_hxinvoice.service.IInvoiceService;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.SystemEnvironment;
import com.seeyon.v3x.dee.util.DateUtil;
import org.apache.commons.io.FileUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.Map;

public class PushOrderInfoAndInvoiceInfoServlet extends HttpServlet {

    private IInvoiceService invoiceService;


    public IInvoiceService getInvoiceService() {
        if (this.invoiceService == null) {
            this.invoiceService = ((IInvoiceService) AppContext.getBean("invoiceService"));
        }
        return invoiceService;
    }
    public void setInvoiceService(IInvoiceService invoiceService) {
        this.invoiceService = invoiceService;
    }



    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        System.out.println("进入票税系统回调方法");
//		获取请求参数
        ServletOutputStream servletout = response.getOutputStream();
        InputStream servletin = request.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(servletin, "UTF-8"));
        StringBuilder jsonData = new StringBuilder();
        String line;
        while ((line = reader.readLine())!= null) {
            jsonData.append(line);
        }
        ObjectMapper objectMapper = new ObjectMapper();
        // 将JSON字符串解析为Map（假设JSON数据是简单的键值对结构）
        Map<String, Object> parameterMap = objectMapper.readValue(jsonData.toString(), Map.class);

//        String decodedUrl = "";
//        JSONObject param = JSONObject.parseObject(decodedUrl);
        JSONObject res = null;
        try {
//            日志记录请求参数
            String str = SystemEnvironment.getApplicationFolder();
            String date = DateUtil.format(new Date(), "yyyyMMddHHmmss");
            FileUtils.writeStringToFile(new File(str+"/HxContractjson/"+date+"/HXFH_" + date + ".json"), jsonData.toString(), "UTF-8");
            res = getInvoiceService().pushOrderInfoAndInvoiceInfoService(parameterMap);
        } catch (Exception e) {
            e.printStackTrace();
        }

        String s = res.toString();

        byte[] bytes = new byte[request.getContentLength()];
        servletin.read(bytes);
        byte[] buf = s.getBytes("UTF-8");
        servletout.write(buf);
        servletout.flush();
        servletout.close();
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        doGet(request, response); }

}
