package com.weaver.seconddev.interfaces.workflow.action;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.weaver.seconddev.interfaces.prop.ConfigProp;
import com.weaver.seconddev.interfaces.workflow.util.DocUtil;
import org.apache.axis.encoding.Base64;
import  com.weaver.seconddev.interfaces.swfa.BillFieldUtil;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipInputStream;
import com.weaver.common.i18n.tool.util.I18nContextUtil;
import com.weaver.verupgrade.conn.CONN_TYPE;
import org.springframework.core.env.Environment;
import java.lang.*;
import java.util.*;
import com.weaver.verupgrade.workflow.request.RequestManager;
import com.weaver.esb.api.rpc.EsbServerlessRpcRemoteInterface;
import com.weaver.common.base.entity.result.WeaResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.weaver.verupgrade.soa.workflow.request.RequestInfo;
import com.weaver.verupgrade.conn.RecordSet;
import com.weaver.verupgrade.docs.webservices.DocAttachment;
import com.weaver.verupgrade.docs.webservices.DocInfo;
import com.weaver.verupgrade.docs.webservices.DocServiceImpl;
import com.weaver.verupgrade.general.BaseBean;
import com.weaver.verupgrade.general.Util;
import com.weaver.verupgrade.hrm.resource.ResourceComInfo;
import com.weaver.verupgrade.soa.workflow.request.*;
import com.weaver.verupgrade.soa.workflow.request.Property;
import com.weaver.verupgrade.soa.workflow.request.DetailTable;
import com.weaver.verupgrade.soa.workflow.request.Row;
import com.weaver.verupgrade.soa.workflow.request.Cell;
import com.weaver.verupgrade.interfaces.workflow.action.Action;

/**
 * 接口账号密码：测试环境--hengtong/abc,,,123   正式环境--htefs/efs2@2@@9!@HT
 */
@org.springframework.stereotype.Service("workflow_action_ZZ_Ten_GDFileUploadAction")
public class ZZ_Ten_GDFileUploadAction extends BaseBean implements Action, EsbServerlessRpcRemoteInterface {

    // 对应E9的请求信息对象
    @Autowired
    private RequestInfo requestInfoTemp;
    @Autowired
    private ConfigProp configProp;

    @Autowired
    private DocUtil docUtil;
    private static final Logger logger_8ab26152 = LoggerFactory.getLogger(ZZ_Ten_GDFileUploadAction.class);

    @Override
    public WeaResult<Map<String, Object>> execute(Map<String, Object> requestInfoMap) {
        Map<String, Object> weaverResultMap = new HashMap<>();
        Long requestIdTemp = Long.parseLong(String.valueOf(requestInfoMap.getOrDefault("requestid", -1)));
        Long userIdTemp = Long.parseLong(String.valueOf(requestInfoMap.getOrDefault("userid", -1)));
        RequestInfo requestInfo = requestInfoTemp.getRequestInfo(requestIdTemp, userIdTemp);
        logger_8ab26152.error("----- workflow_action_ZZ_Ten_GDFileUploadAction new -----");
        logger_8ab26152.error("requestIdTemp -----"+ requestIdTemp);
        logger_8ab26152.error("userIdTemp -----"+ userIdTemp);
        try {
            /**
             * 请求ID*
             */
            String requestID = "";
            /**
             * 系统标识*
             */
            String SYSID = "OA";
            /**
             * 接口ID*
             */
            String ITFID = "HTEFS001";
            // 接口账号
//            String USERNAME = "htefs";
            String USERNAME = configProp.getEfsaccount();

            // 接口密码
//            String PASSWORD = "efs2@2@@9!@HT";
            String PASSWORD = configProp.getEfspassword();
            // 业务属性 6-总账
            String businessTag = "6";
            // //业务类型 1: 费用类 2; 采购类---1,2是针对报账系统的
            String businessType = "";
            // 单据类型  3--总帐类
            String receiptType = "3";
            try {
                ResourceComInfo hr = I18nContextUtil.getBean(ResourceComInfo.class);
                BillFieldUtil unit = new BillFieldUtil();
                // 工作流ID
                String workFlowId = requestInfo.getWorkflowid();
                Property[] properties = requestInfo.getMainTableInfo().getProperty();
                requestID = requestInfo.getRequestid();
                logger_8ab26152.error(String.valueOf("ZZ_Ten_GDFileUploadAction--start--" + requestID));
                Map<String, String> mMap = new HashMap<String, String>();
                for (int i = 0; i < properties.length; i++) {
                    String name = properties[i].getName().toUpperCase();
                    String value = Util.null2String(properties[i].getValue());
                    mMap.put(name, value);
                }
                // 核算单位编码
                String companyCode = mMap.get("SQGSDM");
                logger_8ab26152.error(String.valueOf("核算单位编码:" + companyCode));
                // 记账期间止
                String acctPeriod = mMap.get("JZQJZ");
                // if(acctPeriod!=null&&!acctPeriod.equals("")){
                // acctPeriod = acctPeriod.replaceAll("-","");
                // }
                // 核算系统
                String hsxt = mMap.get("HSXT");
                // getHSXTName(hsxt);
                String hsxtName = unit.getselectNameByCol("hsxt", workFlowId, hsxt);
                // 申请人
                String sqr = mMap.get("SQR");
                String sqrcode = "";
                String sqrname = "";
                if (!sqr.equals("")) {
                    // 申请人工号
                    sqrcode = unit.getWorkcode(sqr);
                    // 申请人姓名
                    sqrname = hr.getResourcename(sqr);
                }
                // 申请类型
                String sqlx = mMap.get("SQLX");
                String fileIds = "";
                if ("0".equals(sqlx)) {
                    // 微信
                    // 附件
                    fileIds = mMap.get("WXMXTZ");
                } else if ("1".equals(sqlx)) {
                    // 融支付
                    // 附件
                    fileIds = mMap.get("RZFMXTZ");
                } else {
                    // 京东刷单
                    // 附件
                    fileIds = mMap.get("JDSDMXTZ");
                }
                logger_8ab26152.error(String.valueOf("附件ids=" + fileIds));
                JSONObject mJson = new JSONObject();
                mJson.put("USERNAME", USERNAME);
                mJson.put("PASSWORD", PASSWORD);
                // 系统标识接收MesWLPS_SY接口返回值开始
                mJson.put("ITFID", ITFID);
                mJson.put("receiptNO", requestID);
                mJson.put("SYSID", SYSID);
                mJson.put("businessTag", businessTag);
                // 核算单位编码
                mJson.put("companyCode", companyCode);
                // 上传者工号
                mJson.put("uploadBy", sqrcode);
                // 单据类型  3--总帐类EASIntermediarySyncService
                mJson.put("receiptType", receiptType);
                // 业务类型
                mJson.put("businessType", businessType);
                // 附件
                RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
                JSONArray fileVOListArr = new JSONArray();
                if (!"".equals(fileIds) && !"100003460000004814".equals(workFlowId)) {
                    String[] docs = fileIds.split(",");
                    for (int i = 0; i < docs.length; i++) {
                        String docid = docs[i];
//                        String sql = " select b.filerealpath,b.iszip,b.name,b.imagefileid from  " + "  e10_core_business.dbo.fileobj b  where b.imagefileid in(select max(imagefileid) " + "from e10_core_business.dbo.document_main_access as  docimagefile where docid in(" + docid + ") group by docid)";
//                        logger_8ab26152.error("sql -----"+ sql);
//                        String poolname = CONN_TYPE.workflow.getType();
//                        // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
//                        boolean b1 = rs.executeSql(sql, poolname);
//                        logger_8ab26152.error("sql flag-----"+ b1);
//                        if (rs.next()) {
//
//                            JSONObject fileItem = new JSONObject();
//                            String imagefileid = Util.null2String(rs.getString("imagefileid"));
//                            String filerealpath = Util.null2String(rs.getString("filerealpath"));
//                            String iszip = Util.null2String(rs.getString("iszip"));
//                            // 文件名
//                            String imagefilename = Util.null2String(rs.getString("imagefilename"));
//                            InputStream fi = getFile(filerealpath, iszip);
//                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
//                            byte[] buffer = new byte[1024];
//                            int count = 0;
//                            while ((count = fi.read(buffer)) >= 0) {
//                                baos.write(buffer, 0, count);
//                            }
//                            String uploadBuffer = Base64.encode(baos.toByteArray());
//                            logger_8ab26152.error(String.valueOf(requestID + " 附件：" + imagefilename + " " + uploadBuffer.length()));
//                            fileItem.put("imgSeq", (i + 1) + "");
//                            fileItem.put("fileName", imagefilename);
//                            fileItem.put("fileContent", uploadBuffer);
//                            fileItem.put("invoiceNo", "");
//
//                            logger_8ab26152.error("fileItem == "+fileItem);
//                            fileVOListArr.add(fileItem);
//                            baos.close();
//                            fi.close();
//                            // 这里就可以封装 文件名和文件内容 传给第三方系统
//                        }
                        Map<String, String> docInfoWf = docUtil.getDocInfoWf(docid);
                        String uploadBuffer = docInfoWf.get("base64str");
                        String imagefilename = docInfoWf.get("filename");
                        logger_8ab26152.error(String.valueOf(requestID + " 附件：" + imagefilename + " " + uploadBuffer.length()));
                        JSONObject fileItem = new JSONObject();
                        fileItem.put("imgSeq", (i + 1) + "");
                        fileItem.put("fileName", imagefilename);
                        fileItem.put("fileContent", uploadBuffer);
                        fileItem.put("invoiceNo", "");
                        fileVOListArr.add(fileItem);
                    }
                }
                // DocServiceImpl service = new DocServiceImpl();
                // String password = Util.null2String(getPropValue("wsaccount", "sysadminPassword")).trim();
                // String session = service.login("sysadmin",password,0,"127.0.0.1");
                // String[] docs = fileIds.split(",");
                // JSONArray fileVOListArr = new JSONArray();
                // if(docs.length>0) {
                // for (int i=0;i<docs.length;i++) {
                // JSONObject fileItem = new JSONObject();
                // DocInfo docInfo = service.getDoc(Integer.parseInt(docs[i]), session);
                // DocAttachment da = docInfo.getAttachments()[0];
                // fileItem.put("imgSeq", (i+1)+"");
                // fileItem.put("fileName", da.getFilename());
                // fileItem.put("fileContent", da.getFilecontent());
                // fileItem.put("invoiceNo", "");
                // fileVOListArr.add(fileItem);
                // }
                // } else {
                // writeLog("获取附件失败！");
                // requestInfo.getRequestManager().setMessageid("ERROR");
                // requestInfo.getRequestManager().setMessagecontent("获取附件失败，请联系管理员！");
                // }
                mJson.put("fileVOList", fileVOListArr);
                String errorMsg = "";
                logger_8ab26152.error(String.valueOf("明细表开始取值"));
                DetailTable[] detailtable = requestInfo.getDetailTableInfo().getDetailTable();
                // ===========凭证明细==============//
                DetailTable dtq = detailtable[0];
                Row[] sq = dtq.getRow();
                JSONArray invoiceVOListArr = new JSONArray();
                float totalScale = 0;
                for (int j = 0; j < sq.length; j++) {
                    // 指定行
                    Row rq = sq[j];
                    // 每行数据再按列存储
                    Cell[] cq = rq.getCell();
                    JSONObject item = new JSONObject();
                    Map<String, String> mDetailMap = new HashMap<String, String>();
                    for (int k = 0; k < cq.length; k++) {
                        // 指定列
                        Cell cq1 = cq[k];
                        // 明细字段名称
                        String nameq = cq1.getName().toUpperCase();
                        String valueq = Util.null2String(cq1.getValue());
                        mDetailMap.put(nameq, valueq);
                    }
                    // 会计凭证号
                    item.put("voucherNo", mDetailMap.get("KJPZH"));
                    // 凭证会计期间----记账日期
                    item.put("acctPeriod", acctPeriod.replaceAll("-", ""));
                    // 从哪个系统同步凭证  K3/K3CLOUD/K3EAS/SAP
                    item.put("voucherSysFrom", hsxtName);
                    invoiceVOListArr.add(item);
                }
                mJson.put("invoiceVOList", invoiceVOListArr);
                logger_8ab26152.error(String.valueOf("获取明细表数据结束"));
                // 
                mJson.put("snVOList", new JSONArray());
                logger_8ab26152.error("调用总账归档附件上传接口请求数据：=====" + mJson.toString());
                // 调用接口
//                String url = Util.null2String(I18nContextUtilcus.getBean(Environment.class).getProperty("hteasoasync.uploadZZInfoUrl")).trim();
                String url = configProp.getUploadZZInfoUrl();
                ZZ_SendPostRequest mGetResult = new ZZ_SendPostRequest();
                String result = mGetResult.getResult(mJson, url);
                logger_8ab26152.error(String.valueOf("调用总账归档附件上传接口返回值：" + result));
                if (!"E".equals(result)) {
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    // 接口处理状态 S-成功，F-失败
                    String isTat = jsonObject.getString("status");
                    // 处理消息
                    String srMessage = jsonObject.getString("message");
                    logger_8ab26152.error("报账系统返回数据：" + jsonObject.toString());
                    if (!"S".equals(isTat)) {
                        // 失败
                        logger_8ab26152.error(String.valueOf("报账系统返回错误信息：" + srMessage));
                        requestInfo.getRequestManager().setMessageid("ERROR");
                        requestInfo.getRequestManager().setMessagecontent("报账系统返回错误信息：" + srMessage);
                        return  WeaResult.fail(500, "报账系统返回错误信息：" + srMessage, getResultMapForAction(weaverResultMap, "result",srMessage, requestInfo.getRequestManager()));

                    }
                } else {
                    logger_8ab26152.error(String.valueOf("调用总账归档附件上传接口返回失败，请联系报账系统管理员！"));
                    requestInfo.getRequestManager().setMessageid("ERROR");
                    requestInfo.getRequestManager().setMessagecontent("调用总账归档附件上传接口返回失败，请联系报账系统管理员！");
                    return  WeaResult.fail(500, "调用总账归档附件上传接口返回失败，请联系报账系统管理员！mJson:"+mJson, getResultMapForAction(weaverResultMap, "result","调用总账归档附件上传接口返回失败，请联系报账系统管理员！", requestInfo.getRequestManager()));

                }
            } catch (Exception e) {
                logger_8ab26152.error(String.valueOf("提交失败！"));
                logger_8ab26152.error(String.valueOf("Error======" + e.getMessage()));
                requestInfo.getRequestManager().setMessageid("ERROR");
                requestInfo.getRequestManager().setMessagecontent("提交失败！");
                return  WeaResult.fail(500, "ZZ_Ten_GDFileUploadAction 提交失败"+ e, getResultMapForAction(weaverResultMap, "result", e.getMessage(), requestInfo.getRequestManager()));

            }
            return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, requestInfo.getRequestManager()));
        } catch (Exception e) {
            e.printStackTrace();
            logger_8ab26152.error("ZZ_Ten_GDFileUploadAction e: {}", e.getMessage());
            return  WeaResult.fail(500, "ZZ_Ten_GDFileUploadAction e: {}"+ e, getResultMapForAction(weaverResultMap, "result", e.getMessage(), requestInfo.getRequestManager()));
        }
    }
    
    private InputStream getFile(String filerealpath, String iszip) throws Exception {
        ZipInputStream zin = null;
        InputStream imagefile = null;
        File thefile = new File(filerealpath);
        if (iszip.equals("1")) {
            zin = new ZipInputStream(new FileInputStream(thefile));
            if (zin.getNextEntry() != null) {
                imagefile = new BufferedInputStream(zin);
            }
        } else {
            imagefile = new BufferedInputStream(new FileInputStream(thefile));
        }
        return imagefile;
    }

    Map<String, Object> getResultMapForAction(Map<String, Object> map, String key, Object value, RequestManager requestManager) {
        if (key != null && !key.isEmpty()) {
            map.put(key, value);
        }
        String msgContent = requestManager.getMessagecontent();
        if (msgContent != null && !msgContent.isEmpty()) {
            map.put("msgContent", msgContent);
        }
        String msgId = requestManager.getMessageid();
        if (msgId != null && !msgId.isEmpty()) {
            map.put("msgId", msgId);
        }
        return map;
    }
}
