package weaver.interfaces.workflow.action.javacode;

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.engine.util.SocketClientUtil;
import com.engine.util.XMLUtils;
import com.weaver.general.Util;
import org.jsoup.Jsoup;
import weaver.conn.RecordSet;
import weaver.file.ImageFileManager;
import weaver.general.StringUtil;
import weaver.hrm.User;
import weaver.interfaces.workflow.action.Action;
import weaver.general.BaseBean;
import weaver.soa.workflow.request.RequestInfo;

import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 推送商旅节点后附加操作(推送商旅节点后附加操作
 * 测试环境
 */
public class Action20230911062023 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) {
        writeLog("推送商旅节点后附加操作====>");
        // 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>";
            writeLog("esbRequestHeaderXML====>"+serviceXML);
            int byteArray = serviceXML.getBytes("UTF-8").length;

            // Calculate the length of the byte array
            // int bytelength = byteArray.length;
            String length = String.format("%08d", byteArray);
            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.78.197",10149);
            String send = scketClient.send(serviceXML);
            String substring = send.substring(0, 8);
            String substring1 = send.substring(8);
            Map<String, String> map = XMLUtils.parseXMLToMap(substring1);
            String retCd = map.get("retCd");
            String retCdDsc = map.get("retCdDsc");
            if ("9999".equals(retCd)){
                request.getRequestManager().setMessageid("9999");
                request.getRequestManager().setMessagecontent(retCdDsc);
                return Action.FAILURE_AND_CONTINUE;
            }
        }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("\\.");
            int lastIndex = imageFileName.lastIndexOf('.');
            String part1 = "";
            String part2 = "";
            if (lastIndex != -1) {
                part1 = imageFileName.substring(0, lastIndex);
                part2 = imageFileName.substring(lastIndex + 1);
            }else {
                part1 = imageFileName;
            }
            String tempFilePath = "";
            try {
                File tempFile = File.createTempFile(part1,part2.length() == 0 ? "" :part2);

                // 创建一个输出流，将数据写入临时文件
                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("创建"+imageFileName+"文件异常"+e.getMessage());
            }
            //推送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 = "";
        String spdfj = "";
        String spwhscpdfwj = "";
        //表单数据
        if (rs.next()) {
            mainid = rs.getString("id");
            //OA差旅报销单单据编号
            toEsbBean.setOaTrvlBnsExpnsAcctNo(rs.getString(Util.null2String("djbh")));
            //经办人工号
            toEsbBean.setOperatorNo(processString(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(multiply100(Util.null2String(rs.getString("bxjedwf"))));
            toEsbBean.setCostDeptCode((Util.null2String(rs.getString("cbzxbm"))));
            toEsbBean.setCostDeptName((Util.null2String(rs.getString("cbzxmc"))));
            //报销事由  Jsoup.parse(htmlContent).text()
            String  expnsRsn = Util.null2String(rs.getString("bxsy"));
            String text = Jsoup.parse(expnsRsn).text();
            toEsbBean.setExpnsRsn(text);
            //备注
            toEsbBean.setRemark(Util.null2String(rs.getString("bz")));
            fj = Util.null2String(rs.getString("fj"));
            spdfj = Util.null2String(rs.getString("spdfj"));
            // spwhscpdfwj = Util.null2String(rs.getString("clspdpdffj"));
            spwhscpdfwj = Util.null2String(rs.getString("spdfj"));
            // String formData = rs.getString("formData");
        }
        // 封装文件数组
        //现在是id
        List<String> fjids;
        if(!StringUtil.isEmpty(fj)){
            fjids = new ArrayList<>( Arrays.asList(fj.split(",")));
        }else {
            fjids = new ArrayList<>();
        }
        //
        writeLog("fjids"+fjids);
        try {
            if (!StringUtil.isEmpty(spdfj)){
                fjids.add(spdfj);
            }
            if (!StringUtil.isEmpty(spwhscpdfwj)){
                fjids.add(spwhscpdfwj);
            }
            ArrayList<acsryItem> acsryArray = new ArrayList<>();
            for (String fjid : fjids) {
                acsryItem acsryItem = new acsryItem();
                acsryItem.setAcsryNm(getimgid(fjid,rs));
                acsryArray.add(acsryItem);
            }
            toEsbBean.setAcsryArray(acsryArray);
            //重新设置下附件张数为数组长度
            toEsbBean.setAcsryNums(acsryArray.size()+"");
        }catch (Exception e){
            e.printStackTrace();
            writeLog("fjidsException"+e);
        }

        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(multiply100(Util.null2String(rs.getString("bhsjedwf"))));
            // //不含税金额
            expenseItem.setTaxAmt(multiply100(Util.null2String(rs.getString("sedwf"))));
            //价税合计金额
            expenseItem.setPrcTotAmt(multiply100(Util.null2String(rs.getString("jshjjedwf"))));
            //记账摘要  Jsoup.parse(expnsRsn).text()
            String jzzy = Util.null2String(rs.getString("jzzy"));
            String text = Jsoup.parse(jzzy).text();
            expenseItem.setAcctingAbstct(text);
            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(formatDate(Util.null2String(rs.getString("ksrq"))));
            // 结束日期
            journeyInfo.setEndDate(formatDate(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 String multiply100(String s) {
        s = s.replace(",", ""); // 移除逗号
        if (StringUtil.isEmpty(s)){
            return "0";
        }
        BigDecimal value = new BigDecimal(s);
        BigDecimal multipliedValue = value.multiply(new BigDecimal("100"));
        int result = multipliedValue.intValue();
        System.out.println(result); // 输出：123456
        return String.valueOf(result); // 输出：123456
    }

    public static String formatDate(String input) {
        // String input = "2023-09-20 19:29";
        try {
            SimpleDateFormat datetimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            // 使用SimpleDateFormat解析输入字符串
            if (!input.contains(" ")){
                datetimeFormat = new SimpleDateFormat("yyyy-MM-dd");
            }

            Date date = datetimeFormat.parse(input);
            // 使用另一个SimpleDateFormat对象格式化Date为所需的输出格式
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String output = dateFormat.format(date);

            return output;  // 输出: 2023-09-20
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String processString(String input) {
        // 检查字符串长度是否大于8
        if (input.length() > 8) {
            // 如果是，截取前八位
            return input.substring(0, 8);
        } else {
            // 否则，返回原字符串
            return input;
        }
    }


    public static void main(String[] args) {
        String imageFileName =  "11.16天津-成都去程机票 (1).jpg";
        int lastIndex = imageFileName.lastIndexOf('.');
        String part1 = imageFileName.substring(0, lastIndex);
        String part2 = imageFileName.substring(lastIndex + 1);
        System.out.println(part1);
        System.out.println(part2);
    }





}
