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.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.file.Prop;
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.Property;
import com.weaver.verupgrade.interfaces.workflow.action.Action;

/**
 *  ZWZX-CG06-线下非常规供应商采购预制报账申请
 * 接口账号密码：测试环境--hengtong/abc,,,123   正式环境--htefs/efs2@2@@9!@HT
 */
@org.springframework.stereotype.Service("workflow_action_ZWZX_CG_FileUploadAction")
public class ZWZX_CG_FileUploadAction extends BaseBean implements Action, EsbServerlessRpcRemoteInterface {

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

    @Autowired
    private DocUtil docUtil;
    private static final Logger logger_323752e9 = LoggerFactory.getLogger(ZWZX_CG_FileUploadAction.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_323752e9.error("----- workflow_action_ZWZX_CG_FileUploadAction new -----");
        logger_323752e9.error("requestIdTemp -----"+ requestIdTemp);
        logger_323752e9.error("userIdTemp -----"+ userIdTemp);
        try {
            /**
             * 请求ID*
             */
            String requestID = "";
            /**
             * 系统标识*
             */
            String SYSID = "OA";
            /**
             * 接口ID*
             */
            String ITFID = "HTEFS001";
            // 接口账号
//            String USERNAME = I18nContextUtilcus.getBean(Environment.class).getProperty("htsysjcmt.efsaccount");
            String USERNAME = configProp.getEfsaccount();
            // 接口密码
//            String PASSWORD = I18nContextUtilcus.getBean(Environment.class).getProperty("htsysjcmt.efspassword");
            String PASSWORD = configProp.getEfspassword();
            // 业务属性 0-未分类
            String businessTag = "0";
            // //业务类型 1: 费用类 2; 采购类---1,2是针对报账系统的
            String businessType = "";
            // 单据类型  4--采购类
            String receiptType = "4";
            RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
            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_323752e9.error(String.valueOf("ZWZX_CG_FileUploadAction--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);
                    logger_323752e9.error(String.valueOf(name + ":" + value));
                }
                // 核算单位编码
                String companyCode = mMap.get("SQGSDM");
                logger_323752e9.error(String.valueOf(requestID + " 核算单位编码:" + companyCode));
                // 采购预制单号
                String cgyzdh = mMap.get("CGYZDH");
                logger_323752e9.error(String.valueOf(requestID + " 采购预制单号:" + cgyzdh));
                // 过账年份
                String gznf = mMap.get("GZNF");
                if ("".equals(gznf)) {
                    // 申请日期
                    String sqrq = mMap.get("SQRQ");
                    gznf = sqrq.substring(0, 4);
                }
                String receiptNO = gznf + companyCode + cgyzdh;
                logger_323752e9.error(String.valueOf(requestID + " receiptNO:" + receiptNO));
                // 申请人
                String sqr = mMap.get("SQR");
                String sqrcode = "";
                String sqrname = "";
                if (!sqr.equals("")) {
                    // 申请人工号
                    sqrcode = unit.getWorkcode(sqr);
                    // 申请人姓名
                    sqrname = hr.getResourcename(sqr);
                }
                // 附件ZOA_SL_GW_Action
                String fileIds = mMap.get("FJ");
                logger_323752e9.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", receiptNO);
                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);
                // 附件
                JSONArray fileVOListArr = new JSONArray();
                if (!"".equals(fileIds)) {
                    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_323752e9.error("sql -----"+ sql);
//                        String poolname = CONN_TYPE.workflow.getType();
//                        // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
//                        boolean b1 = rs.executeSql(sql, poolname);
//                        logger_323752e9.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_323752e9.error(String.valueOf(requestID + " 附件：" + imagefilename + " " + uploadBuffer.length()));
//                            fileItem.put("imgSeq", (i + 1) + "");
//                            fileItem.put("fileName", imagefilename);
//                            fileItem.put("fileContent", uploadBuffer);
//                            fileItem.put("invoiceNo", "");
//
//                            logger_323752e9.error(String.valueOf("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_323752e9.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(",");
                // 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);
                // writeLog(docInfo.getDocSubject()+" attach:"+docInfo.getAttachments().length);
                // 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("invoiceVOList", new JSONArray());
                mJson.put("snVOList", new JSONArray());
                logger_323752e9.error(requestID + " 调用总账归档附件上传接口请求数据(无附件)：=====" + mJson.toString());
                mJson.put("fileVOList", fileVOListArr);
                // writeLog(requestID+" 调用总账归档附件上传接口请求数据：=====" + 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_323752e9.error(String.valueOf(requestID + " 调用总账归档附件上传接口返回值：" + result));
                if (!"E".equals(result)) {
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    // 接口处理状态 S-成功，F-失败
                    String isTat = jsonObject.getString("status");
                    // 处理消息
                    String srMessage = jsonObject.getString("message");
                    logger_323752e9.error(requestID + " 报账系统返回数据：" + jsonObject.toString());
                    if (!"S".equals(isTat)) {
                        // 失败
                        logger_323752e9.error(String.valueOf(requestID + " 报账系统返回错误信息：" + srMessage));
                        requestInfo.getRequestManager().setMessageid("ERROR");
                        requestInfo.getRequestManager().setMessagecontent("报账系统返回错误信息：" + srMessage);
                        return  WeaResult.fail(500, "报账系统返回错误信息：" + srMessage, getResultMapForAction(weaverResultMap, "result",srMessage, requestInfo.getRequestManager()));

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

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

            }
            return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, requestInfo.getRequestManager()));
        } catch (Exception e) {
            e.printStackTrace();
            logger_323752e9.error("ZWZX_CG_FileUploadAction e: {}", e.getMessage());
            return  WeaResult.fail(500, "ZWZX_CG_FileUploadAction 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;
    }
}
