package com.engine.custom.sl.action;

import com.dcfs.fts.common.error.FtpException;
import com.engine.custom.hg.util.HgUtils;
import com.engine.custom.sl.entity.*;
import com.engine.util.SocketClientUtil;
import com.weaver.general.Util;
import weaver.conn.RecordSet;
import weaver.file.ImageFileManager;
import weaver.general.BaseBean;
import weaver.hrm.User;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 推送商旅节点后附加操作(推送商旅节点后附加操作
 */
public class OAtoCWAction extends BaseBean implements Action {
    /**
     * After selecting aciton after the process path node, this method will be executed after the node is submitted.
     */
    @Override
    public String execute(RequestInfo request) {
        // if(error) {
        // 	request.getRequestManager().setMessageid("90001");
        // 	request.getRequestManager().setMessagecontent("System Abnormal Termination Process Submission！");
        // }
        String requestId = request.getRequestid();
        String tablename = request.getRequestManager().getBillTableName();
        TravelToEsbBean toEsbBean = new TravelToEsbBean();
        //封装主表数据
        RecordSet rs = new RecordSet();
        String mainId = setMainForm(requestId, tablename, rs, toEsbBean);
        writeLog("toEsbBean1====>"+toEsbBean);
        writeLog("上传附件到ESB服务器====>");
        try {
            fileToEsb(toEsbBean,requestId);
        } catch (Exception e) {
            	request.getRequestManager().setMessageid("10001");
            	request.getRequestManager().setMessagecontent(e.getMessage());
            	return Action.FAILURE_AND_CONTINUE;
        }
        setFormDt1(mainId,tablename,rs,toEsbBean);
        writeLog("toEsbBean2====>"+toEsbBean);
        setFormDt2(mainId,tablename,rs,toEsbBean);
        writeLog("toEsbBean3====>"+toEsbBean);
        String Service_Body = "<Service_Body><request>"+ toEsbBean.toXMLString()+"</request></Service_Body>"  ;
        writeLog("toEsbBean4====>"+Service_Body);
        try{
        EsbRequestHeader esbRequestHeader = new EsbRequestHeader(Util.getIntValue(mainId));
        writeLog("esbRequestHeader====>"+esbRequestHeader);
        String Service_Header = TravelToEsbBean.convertObjectToXml(esbRequestHeader,"Service_Header");
        writeLog("esbRequestHeaderXML====>"+Service_Header);
        String serviceXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Service>";
        serviceXML = serviceXML +  Service_Header + Service_Body;
        serviceXML = serviceXML + "</Service>";
        String length = String.format("%08d", serviceXML.length());
        writeLog("XMLlength"+ length);
        serviceXML =  length + serviceXML;
        writeLog("serviceXML==="+ serviceXML);
        serviceXML = new String(serviceXML.getBytes(StandardCharsets.UTF_8));
        writeLog("UTF_8_serviceXML==="+ serviceXML);
        SocketClientUtil scketClient = new SocketClientUtil("14.1.76.116",10149);
        String send = scketClient.send(serviceXML);
        }catch (Exception e){
            e.printStackTrace();
            writeLog("构建XML异常"+e.getMessage());
            request.getRequestManager().setMessageid("10001");
            request.getRequestManager().setMessagecontent(e.getMessage());
            return Action.FAILURE_AND_CONTINUE;
        }
        // setFormDt1();
        return Action.SUCCESS;
    }

    private void fileToEsb(TravelToEsbBean toEsbBean, String requestId) throws Exception {
        // HashMap<String, String> filePathMap = new HashMap<>();
        List<acsryItem> acsryArray = toEsbBean.getAcsryArray();
        for (acsryItem acsryItem : acsryArray) {
            String acsryNm = acsryItem.getAcsryNm();
            writeLog("acsryNm"+acsryNm);
            ImageFileManager ifm = new ImageFileManager();
            ifm.getImageFileInfoById(Util.getIntValue(acsryNm,0));
            InputStream inputStream = ifm.getInputStream();
            String imageFileName = ifm.getImageFileName();
            writeLog("imageFileName"+imageFileName);
            String[] filename = imageFileName.split("\\.");
            String tempFilePath = "";
            try {
                File tempFile = File.createTempFile(filename[0],filename.length ==2 ?filename[1]:"");

                // 创建一个输出流，将数据写入临时文件
                OutputStream outputStream = new FileOutputStream(tempFile);

                // 将输入流中的数据复制到输出流（即临时文件）
                byte[] buffer = new byte[2048];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                tempFilePath = tempFile.getAbsolutePath();
                writeLog( "临时文件位置"+tempFilePath);
                // 关闭输入流和输出流
                inputStream.close();
                outputStream.close();
            }catch (Exception e){
                e.printStackTrace();
                writeLog( "创建本地文件异常"+e.getMessage());
                throw new Exception("创建本地文件异常");
            }
            //推送ESB服务器
            String ftpPath = "";
            try {
                 ftpPath = HgUtils.putFile(tempFilePath, requestId + File.separator + imageFileName);
            } catch (FtpException e) {
                e.printStackTrace();
                writeLog( "传输ESBftp异常"+e.getMessage());
                throw new Exception("传输ESBftp异常");
            } catch (IOException e) {
                e.printStackTrace();
                writeLog( "传输ESBIO异常"+e.getMessage());
                throw new Exception("传输ESBftp异常");
            }
            acsryItem.setAcsryNm(imageFileName);
            acsryItem.setSavePath(ftpPath);
        }

    }

    private String setMainForm(String requestId, String tablename, RecordSet rs ,TravelToEsbBean toEsbBean) {
        rs.execute("select * from " + tablename + " where requestid =  " + requestId);
        String mainid = "";
        String fj = "";
        //表单数据
        if (rs.next()) {
            mainid = rs.getString("id");
            //OA差旅报销单单据编号
            toEsbBean.setOaTrvlBnsExpnsAcctNo(rs.getString(Util.null2String("djbh")));
            //经办人工号
            toEsbBean.setOperatorNo(Util.null2String(rs.getString("jbrgh")));
            //经办人姓名  id
            toEsbBean.setOperatorName(Util.null2String(rs.getString("jbrxm")));
            String lastname = new User(Util.getIntValue(toEsbBean.getOperatorName())).getLastname();
            toEsbBean.setOperatorName(lastname);

            //附件张数
            toEsbBean.setAcsryNums(Util.null2String(rs.getString("fjzs")));
            //报销金额
            toEsbBean.setExpnsAmt(Util.null2String(rs.getString("bxjedwf")));
            //报销事由
            toEsbBean.setExpnsRsn(Util.null2String(rs.getString("bxsy")));
            //备注
            toEsbBean.setRemark(Util.null2String(rs.getString("bz")));
            fj = Util.null2String(rs.getString("fj"));
            // String formData = rs.getString("formData");
        }
        // 封装文件数组
        //现在是id
        List<String> fjids = Arrays.asList(fj.split(","));
        ArrayList<acsryItem> acsryArray = new ArrayList<>();
        for (String fjid : fjids) {
            acsryItem acsryItem = new acsryItem();
            acsryItem.setAcsryNm(getimgid(fjid,rs));
            acsryArray.add(acsryItem);
        }
        toEsbBean.setAcsryArray(acsryArray);
        return mainid;
    }


    private void setFormDt1(String mainid, String tablename, RecordSet rs , TravelToEsbBean toEsbBean) {
        rs.execute("select * from " + tablename + "_dt1 where mainid =  " + mainid);
        List<ExpenseItem> expenseArray = new ArrayList<>();
        while (rs.next()) {
            ExpenseItem expenseItem = new ExpenseItem();
            // 支出类型
            expenseItem.setExpndType(getpartyBuildCostCode(Util.getIntValue(rs.getString("zclx"),0)));
            //不含税金额
            expenseItem.setExclsvTaxAmt(Util.null2String(rs.getString("bhsjedwf")));
            // //不含税金额
            expenseItem.setTaxAmt(Util.null2String(rs.getString("sedwf")));
            //价税合计金额
            expenseItem.setPrcTotAmt(Util.null2String(rs.getString("jshjjedwf")));
            //记账摘要
            expenseItem.setAcctingAbstct("");
            expenseArray.add(expenseItem);
        }
        toEsbBean.setExpndArray(expenseArray);
    }


    private void setFormDt2(String mainid, String tablename, RecordSet rs , TravelToEsbBean toEsbBean) {
        rs.execute("select * from " + tablename + "_dt2 where mainid =  " + mainid);
        List<JourneyInfo> jrnyInfoArray = new ArrayList<>();
        while (rs.next()) {
            JourneyInfo journeyInfo = new JourneyInfo();
            // 开始日期
            journeyInfo.setStartDate(Util.null2String(rs.getString("ksrq")));
            // 结束日期
            journeyInfo.setEndDate(Util.null2String(rs.getString("jsrq")));
            // 出差天数
            journeyInfo.setBsnTrpDays(Util.null2String(rs.getString("ccts")));
            //行程路线
            journeyInfo.setJrnyPath(Util.null2String(rs.getString("hclx")));
            //行程说明
            journeyInfo.setJrnyExpln(Util.null2String(rs.getString("hcsm")));
            //记账摘要
            journeyInfo.setRemark(Util.null2String(rs.getString("bz")));
            jrnyInfoArray.add(journeyInfo);
        }
        toEsbBean.setJrnyInfoArray(jrnyInfoArray);
    }

//获取支出类型
    private String getpartyBuildCostCode(int index){
        if(index == 0){
            return "FEE_BUILD";
        }else if(index == 1){
            return "BIZ_FEE";
        }else if(index == 2){
            return "PARTY_BUILD_EXPENSE";
        }
        return "";
    }

    public  String getimgid(String docid, RecordSet rs){
        String sql = "select docid,df.imagefileid imgid  from   docimagefile df left join imagefile imf on df.imagefileid = imf.imagefileid where DOCID = ?";
        writeLog("getimgidsql"+sql+"===="+docid);
        rs.executeQuery(sql,docid);
        if (rs.next()){
            writeLog("imgid"+Util.null2String(rs.getString("imgid")));
            return  Util.null2String(rs.getString("imgid"));
        }
        return "";
    };
    //生成流水号
    public static String generateTimestamp() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        Date currentDate = new Date();
        return dateFormat.format(currentDate);
    }

    public static void main(String[] args) {
        //String s = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Service><Service_Header><service_sn>20230920132332000003</service_sn><system_id>0170</system_id><requester_id>0258</requester_id><branch_id>cwgl00001</branch_id><channel_id>01</channel_id><service_time>20230920132332</service_time><need_request></need_request><SvcCd>500120010</SvcCd><SvcScn>13</SvcScn><BnkSrlNo>025820230920132332000003</BnkSrlNo><FileFlg>0</FileFlg></Service_Header><Service_Body><request><oaTrvlBnsExpnsAcctNo>123123</oaTrvlBnsExpnsAcctNo><operatorNo>10110537</operatorNo><operatorName>测试_10110537</operatorName><acsryNums>1</acsryNums><expnsAmt>1,234.00</expnsAmt><expnsRsn>1234</expnsRsn><remark>的覅第v的v你你</remark><expndArray><expndType>BIZ_FEE</expndType><exclsvTaxAmt>11.00</exclsvTaxAmt><taxAmt>0.00</taxAmt><prcTotAmt>11.00</prcTotAmt><acctingAbstct></acctingAbstct></expndArray><jrnyInfoArray><startDate>2023-09-20</startDate><endDate>2023-09-20</endDate><bsnTrpDays>1</bsnTrpDays><jrnyPath>1111</jrnyPath><jrnyExpln>111</jrnyExpln><remark>11</remark></jrnyInfoArray><acsryArray><acsryNm>滴滴出行行程报销单 (1).pdf</acsryNm><savePath>/025801/YDBG/20230920/501502/滴滴出行行程报销单 (1).pdf</savePath></acsryArray></request></Service_Body></Service>";
        //  String s = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Service><Service_Header><service_sn>20230920142508000007</service_sn><system_id>0170</system_id><requester_id>0258</requester_id><branch_id>cwgl00001</branch_id><channel_id>01</channel_id><service_time>20230920142508</service_time><need_request></need_request><SvcCd>500120010</SvcCd><SvcScn>13</SvcScn><BnkSrlNo>025820230920142508000007</BnkSrlNo><FileFlg>0</FileFlg></Service_Header><Service_Body><request><oaTrvlBnsExpnsAcctNo></oaTrvlBnsExpnsAcctNo><operatorNo>10110537</operatorNo><operatorName>测试_10110537</operatorName><acsryNums>2</acsryNums><expnsAmt>180.00</expnsAmt><expnsRsn>测试ESb补贴报销单报销事由</expnsRsn><remark>测试ESb补贴报销单备注</remark><expndArray><expndType>BIZ_FEE</expndType><exclsvTaxAmt>180.00</exclsvTaxAmt><taxAmt>0.00</taxAmt><prcTotAmt>180.00</prcTotAmt><acctingAbstct></acctingAbstct></expndArray><jrnyInfoArray><startDate>2023-09-20</startDate><endDate>2023-09-20</endDate><bsnTrpDays>1</bsnTrpDays><jrnyPath>行程路线-天津北京</jrnyPath><jrnyExpln>行程说明-天津北京</jrnyExpln><remark>备注-天津北京</remark></jrnyInfoArray><acsryArray><acsryNm>公文功能相关接口.pdf</acsryNm><savePath>/025801/YDBG/20230920/502519/公文功能相关接口.pdf</savePath></acsryArray><acsryArray><acsryNm>滴滴电子发票.pdf</acsryNm><savePath>/025801/YDBG/20230920/502519/滴滴电子发票.pdf</savePath></acsryArray></request></Service_Body></Service>";
         String s = "00000667<?xml version=\"1.0\" encoding=\"UTF-8\"?><Service><Service_Header><service_sn>000000000004</service_sn><system_id>0258</system_id><requester_id>0170</requester_id><branch_id>951101</branch_id><channel_id>0170</channel_id><service_time>20230920195236</service_time><need_request>true</need_request><SvcCd>500120043</SvcCd><SvcScn>01</SvcScn><BnkSrlNo>017020230920000000000004</BnkSrlNo><FileFlg>0</FileFlg></Service_Header><Service_Body><request><oaTrvlBnsExpnsAcctNo>BTSQD-202309200007</oaTrvlBnsExpnsAcctNo><apprvrNo>111111</apprvrNo><apprvrName>测试审批人</apprvrName><flowStatus>0</flowStatus><sgntrOpn>驳回测试2</sgntrOpn></request></Service_Body></Service>";
         // byte[] bytes = s.getBytes(StandardCharsets.US_ASCII);
        // String s1 = new String(bytes);
        try {
             // Map<String, String> paramMap = XMLUtils.parseXMLToMap(s1);
             // System.out.println(paramMap);
            System.out.println(s.getBytes(StandardCharsets.UTF_8).length);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }



}
