package weaver.interfaces.htsc.payment.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.engine.htsc.meeting.util.Common;
import com.engine.htsc.payment.log.PaymentLogger;
import com.engine.htsc.payment.log.PaymentLoggerFactory;
import com.engine.htsc.payment.util.AssertUtil;
import com.engine.htsc.payment.util.CommonAPI;
import com.engine.htsc.payment.util.PayUtil;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import weaver.general.Util;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.htsc.cus.HTUtil;
import weaver.interfaces.htsc.cus.webservices.FileInfoEntity;
import weaver.interfaces.htsc.cus.webservices.UploadfileEntity;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import weaver.workflow.request.RequestManager;

import java.io.*;
import java.util.*;
import java.util.stream.Collectors;

public class LangChaoPdfToGalaxy implements Action {

    private static final PaymentLogger logger = PaymentLoggerFactory.getLogger(LangChaoPdfToGalaxy.class);
    private final HTUtil htUtil = new HTUtil();


    @Override
    public String execute(RequestInfo requestInfo) {

        try {
            new Thread(() -> {
                try {
                    logger.info("ToGalaxy开始延时");
//                    Thread.sleep(30*1000L);
                    logger.info("ToGalaxy延时结束");
                    String requestid = requestInfo.getRequestid();
                    RequestManager rm = requestInfo.getRequestManager();
                    String tableName = rm.getBillTableName();
                    int workflowid = Integer.parseInt(requestInfo.getWorkflowid());
                    String sql = "select t1.workflowid,t3.lcbh as requestmark ,t2.workcode from workflow_requestbase t1\n" +
                            "left join hrmresource t2 " +
                            "on t1.creater = t2.id " +
                            "left join " + tableName + " t3 " +
                            "on t1.requestid = t3.requestid " +
                            "where t1.requestid =?";
                    Map<String, String> paramsProtoType = CommonAPI.querySingleRow(sql, requestid);

                    Map<String, String> pdfParams = copy(paramsProtoType);
                    pdfParams.put("requestid", requestid);
                    pdfParams.put("modeid", printModeId(workflowid));
                    //sendPDF
                    sendPDF(pdfParams);

//                    Map<String, String> affixParams = copy(paramsProtoType);
//                    affixParams.put("appendices", getWorkflowAffixes(tableName, requestid));
//                    // sendAffix
//                    sendAffix(affixParams);
                } catch (Exception e) {
                    logger.error(String.format("网报流程办结后PdfToGalaxy出错 requestid: %s", requestInfo.getRequestid()),e);
                }
            }).start();
            return SUCCESS;
        } catch (Exception e) {
            logger.error(e);
            return SUCCESS;
        }
    }

    private void sendPDF(Map<String, String> params) throws Exception {
        logger.info("ToGalaxy开始同步审批单 params" + JSON.toJSONString(params));
        AssertUtil.isEmpty(params.get("requestmark"), "requestmark为空");
        AssertUtil.isEmpty(params.get("workcode"), "workcode为空");
        AssertUtil.isEmpty(params.get("modeid"), "modeid为空");
        AssertUtil.isEmpty(params.get("requestid"), "requestid为空");
        //生成审批单PDF
        String path = Common.saveProcessPDFWithReturnFilePath(params.get("modeid"), params.get("requestid"), params.get("requestmark"));
        logger.info("生成审批单PDF path" + path);
        //浪潮
//        Map<String, String> paras = new HashMap<>();
//        paras.put("billid", params.get("requestmark"));
//        paras.put("workcode", params.get("workcode"));
//        paras.put("filePath", path);
//        logger.info(String.format("sendPDF langChao in: %s", JSON.toJSONString(paras)));
//        String langChaoResponse = htUtil.SendImageWithInputStream(paras);
        String filetype = "0";//文件类型 0：非票据  1：票据
        UploadfileEntity uploadfileEntity = new UploadfileEntity();
        uploadfileEntity.setBillID(params.get("requestmark"));
        uploadfileEntity.setFileType(filetype);
        uploadfileEntity.setUserCode(params.get("workcode"));
        logger.info("send image request: " + JSON.toJSONString(uploadfileEntity));
        FileInfoEntity[] fileInfoEntities = new FileInfoEntity[1];
        String fileTypeID = Util.null2String(new PropBean().getPropName("cft.image.type.png"));
        int i = 0;
        InputStream inputstream = getInputStreamFromPath(path);
        FileInfoEntity fileInfoEntity = new FileInfoEntity();
        fileInfoEntity.setFileName(params.get("requestmark") + ".pdf"); //文件名称=流程编号.pdf
        fileInfoEntity.setContent(InputStream2Byte(inputstream));
        fileInfoEntity.setFileTypeID(fileTypeID);
        fileInfoEntities[i] = fileInfoEntity;
        uploadfileEntity.setFileInfoEntityArr(fileInfoEntities);
        Map<String, String> headers = new HashMap<String, String>();
        String url = Util.null2String(new PropBean().getPropName("toGalaxy"));
        String langChaoResponse = sendPostNew(url,JSONObject.toJSONString(uploadfileEntity),headers);;
        logger.info(String.format("sendPDF Galaxy out: %s", JSON.toJSONString(langChaoResponse)));
        logger.info("ToGalaxy开始审批单结束");
    }

    private void sendAffix(Map<String, String> params) throws Exception {
        logger.info("开始同步附件 params" + JSON.toJSONString(params));
        AssertUtil.isEmpty(params.get("requestmark"), "requestmark为空");
        AssertUtil.isEmpty(params.get("workcode"), "workcode为空");
        if (AssertUtil.isEmpty(params.get("appendices"))) {
            logger.info("sendAffix 附件为空");
            return;
        }
        //附件
        Map<String, Object> paras = new HashMap<>();
        paras.put("billid", params.get("requestmark"));
        paras.put("workcode", params.get("workcode"));
        paras.put("fileids", params.get("appendices"));
        logger.info(String.format("sendAffix appendices langChao in: %s", JSON.toJSONString(paras)));
        String langChaoResponse = htUtil.SendImageWithAffix(paras);
        logger.info(String.format("sendAffix appendices langChao out: %s", JSON.toJSONString(langChaoResponse)));
    }

    private Map<String, String> copy(Map<String, String> prototype) {
        return new HashMap<>(prototype);
    }

    private String printModeId(int workflowid) throws Exception {
        String sql = " select t2.unnumber,t1.modeid from workflow_printset t1\n" +
                "    left join workflow_nodebase t2\n" +
                "    on t1.nodeid = t2.id\n" +
                "    where type =1\n" +
                "    and printenable =1\n" +
                "    and t2.nodename = '办结'\n" +
                "    and t1.isactive = 1\n" +
                "    and t1.orderid = 0\n" +
                "    and t2.unnumber = ?";
        try {
            Map<String, String> pa = CommonAPI.querySingleRow(sql,
                    PayUtil.getUnNumberByWorkFlowId(workflowid) + "_bj");
            return pa.get("modeid");
        } catch (Exception e) {
            throw new IllegalArgumentException(String.format("workflowid:%s,没有对应的办结打印模板 ", workflowid));
        }

    }

    private String getWorkflowAffixes(String tableName, String requestid) throws Exception {
        String billid = tableName.substring(tableName.lastIndexOf("_")).replace("_", "-");
        String sql = "select wm_concat_old(FIELDNAME) field from workflow_billfield b where b.fieldhtmltype=6 and b.billid=?";
        String field = CommonAPI.querySingleFieldWithPlaceholder(sql, "field", billid);
        if (AssertUtil.isEmpty(field)) {
            return "";
        }
        String need = "fjsc1,fjsc2,fjsc3,fj1";
        List<String> ready = new ArrayList<>();
        String[] split = field.split(",");
        List<String> needDel = Arrays.asList(need.split(","));
        for (String s : split) {
            if (!needDel.contains(s)) {
                ready.add(s);
            }
        }
        field = String.join(",",ready);
        sql = String.format("select %s from %s where requestid = ?", field, tableName);
        Map<String, String> fjResult = CommonAPI
                .querySingleRow(sql, requestid);
        //附件数据汇总
        return fjResult.values().stream()
                .filter(AssertUtil::isNotEmpty)
                .collect(Collectors.joining(","));
    }

    /**
     * 获取文件流, by path
     *
     * @param filePath
     * @return
     * @throws FileNotFoundException
     */
    private InputStream getInputStreamFromPath(String filePath) throws FileNotFoundException {
        try {
            File thefile = new File(filePath);
            return new BufferedInputStream(new FileInputStream(thefile));
        } catch (FileNotFoundException e) {
            logger.info(String.format("filePath:%s, file not  found", filePath));
            throw new FileNotFoundException(String.format("filePath:%s, file not  found", filePath));
        }
    }

    /**
     * 转换成 byte []
     *
     * @param inputStream 附件转的流
     * @return byte
     */
    public byte[]  InputStream2Byte(InputStream inputStream) {
        byte[] result;
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
            inputStream.close();
            bos.flush();
            result = bos.toByteArray();
        } catch (Exception e) {
            logger.info("字节流转换出错！");
            return null;
        }
        return result;
    }
    /***
     *
     * @param url
     * @param params
     * @param headsMap
     * @return
     */
    public String sendPostNew(String url, String params, Map<String,String> headsMap)
    {
        //BaseBean bb = new BaseBean();
        String body = "";
        String encoding = "UTF-8";
        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        //创建post方式请求对象
        HttpPost httpPost = new HttpPost(url);


        //设置参数到请求对象中
        StringEntity strEntity = new StringEntity(params,encoding);//解决中文乱码问题
        strEntity.setContentEncoding(encoding);
        strEntity.setContentType("application/json");
        httpPost.setEntity(strEntity);

        //设置header信息
        //指定报文头【Content-type】、【User-Agent】
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        if (headsMap != null && !headsMap.isEmpty()) {
            headsMap.forEach((key, value) -> {
                //bb.writeLog("key:"+key+" value:"+value);
                httpPost.addHeader(key, value);
            });
        }
        //执行请求操作，并拿到结果（同步阻塞）
        CloseableHttpResponse response = null;
        try {
            response = client.execute(httpPost);
            //获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                body = EntityUtils.toString(entity, encoding);
            }
            EntityUtils.consume(entity);
            //释放链接
            response.close();
        } catch (IOException e) {
            System.out.println("OrganizationSyn-e:"+e);
            e.printStackTrace();
        }
        return body;
    }


}
