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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.weaver.seconddev.interfaces.workflow.util.DocUtil;
import org.apache.axis.encoding.Base64;
import  com.weaver.seconddev.interfaces.pmoa.PMService;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.zip.ZipInputStream;
import com.weaver.common.i18n.tool.util.I18nContextUtil;
import com.weaver.verupgrade.conn.CONN_TYPE;
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 java.util.Map;
import java.util.HashMap;
import com.weaver.verupgrade.conn.RecordSet;
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;

// IT003-项目验收申请流程
@org.springframework.stereotype.Service("workflow_action_PMProjectAcceptanceAction")
public class PMProjectAcceptanceAction extends BaseBean implements Action, EsbServerlessRpcRemoteInterface {

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

    @Autowired
    private PMService pmService ;

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

    public WeaResult<Map<String, Object>> execute(Map<String, Object> requestInfoMap) {
        logger_f17f81aa.error("PMProjectAcceptanceAction start");
        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 request = requestInfoTemp.getRequestInfo(requestIdTemp, userIdTemp);
        try {
            String requestid = request.getRequestid();
            logger_f17f81aa.error(String.valueOf("PMProjectAcceptanceAction--start--" + requestid));
            String lcbh = "";
            String xmid = "";
            String yszj = "";
            String ysqk = "";
            String sfhpj = "";
            String fj = "";
            // 后评价周期(月)
            String hpjzqy = "";
            // 验收专家类型  0 信息系统类 1弱电工程类
            String zjlx = "";
            // 弱电验收专家
            String rdyszj = "";
            try {
                Property[] properties = request.getMainTableInfo().getProperty();
                for (int i = 0; i < properties.length; i++) {
                    String name = properties[i].getName().toUpperCase();
                    String value = Util.null2String(properties[i].getValue());
                    if (name.equals("LCBH")) {
                        lcbh = value;
                    }
                    if (name.equals("XMID")) {
                        xmid = value;
                    }
                    if (name.equals("ZJ")) {
                        yszj = value;
                    }
                    if (name.equals("ZJLX")) {
                        zjlx = value;
                    }
                    if (name.equals("RDYSZJ")) {
                        rdyszj = value;
                    }
                    if ("1".equals(zjlx)) {
                        yszj = rdyszj;
                    }
                    if (name.equals("YSQK")) {
                        ysqk = value;
                    }
                    if (name.equals("SFHPJ")) {
                        sfhpj = value;
                    }
                    if (name.equals("YSFJ")) {
                        fj = value;
                    }
                    if (name.equals("HPJZQY")) {
                        hpjzqy = value;
                    }
                }
                ResourceComInfo rc = I18nContextUtil.getBean(ResourceComInfo.class);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("requestId", requestid);
                jsonObject.put("workflowNo", lcbh);
                jsonObject.put("projectId", xmid);
                jsonObject.put("operateUserName", rc.getLastnames(yszj));
                jsonObject.put("operateDate", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
                jsonObject.put("content", ysqk);
                jsonObject.put("postEvaluation", sfhpj);
                jsonObject.put("hpjzqy", hpjzqy);

                RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
                JSONArray fileList = new JSONArray();
                if (!"".equals(fj)) {
                    String[] docs = fj.split(",");
                    for (int i = 0; i < docs.length; i++) {
                        String docid = docs[i];

                        Map<String, String> docInfoWf = docUtil.getDocInfoWf(docid );
                        String uploadBuffer = docInfoWf.get("base64str");
                        String imagefilename = docInfoWf.get("filename");
                        logger_f17f81aa.error(String.valueOf(requestIdTemp + " 附件：" + imagefilename + " " + uploadBuffer.length()));
                        JSONObject fileItem = new JSONObject();
                        fileItem.put("filename", imagefilename);
                        fileItem.put("context", uploadBuffer);
                        fileList.add(fileItem);
//                        String sql = " select b.filerealpath,b.iszip,b.name,b.imagefileid from  " + " e10_common.dbo.fileobj b  where b.imagefileid in(select max(imagefileid) " + "from e10_common.dbo.document_main_access as  docimagefile where docid in(" + docid + ") group by docid)";
//                        String poolname = CONN_TYPE.workflow.getType();
//                        // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
//                        boolean b = rs.executeSql(sql, poolname);
//                        logger_f17f81aa.error("b--" + b);
//                        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_f17f81aa.error(String.valueOf(requestid + " 附件：" + imagefilename + " " + uploadBuffer.length()));
//                            fileItem.put("filename", imagefilename);
//                            fileItem.put("context", uploadBuffer);
//                            fileList.add(fileItem);
//                            baos.close();
//                            fi.close();
//                            // 这里就可以封装 文件名和文件内容 传给第三方系统
//                        }
                    }
                }
                // 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 = fj.split(",");
                // JSONArray fileList = 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("filename", da.getFilename());
                // fileItem.put("context", da.getFilecontent());
                // fileList.add(fileItem);
                // }
                // }
                jsonObject.put("file", fileList);
//                PMService pmService = new PMService();

                logger_f17f81aa.error("jsonObject === "+jsonObject.toJSONString());
                String result = pmService.call(jsonObject.toString());
                logger_f17f81aa.error("result === "+  result);
                if (!result.equals("E")) {
                    JSONObject retobj = JSONObject.parseObject(result);
                    boolean flag = (boolean) retobj.get("success");
                    String message = (String) retobj.get("message");
                    logger_f17f81aa.error(String.valueOf(requestid + "--PMProjectAcceptanceAction--result--" + flag + "|" + message));
                    if (!flag) {
                        request.getRequestManager().setMessageid("ERROR");
                        request.getRequestManager().setMessagecontent("项目验收数据传项目管理系统失败：" + message);
                        return  WeaResult.fail(500, "项目验收数据传项目管理系统失败：" + message, getResultMapForAction(weaverResultMap, "result","项目验收数据传项目管理系统失败：" + message, request.getRequestManager()));

                    }
                    return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, request.getRequestManager()));
                }
            } catch (Exception e) {
                logger_f17f81aa.error(String.valueOf(requestid + "--PMProjectAcceptanceAction--error--" + e.toString()));
                return  WeaResult.fail(500, "PMProjectAcceptanceAction err"+ e, getResultMapForAction(weaverResultMap, "result",e.getMessage(), request.getRequestManager()));
            }
            request.getRequestManager().setMessageid("ERROR");
            request.getRequestManager().setMessagecontent("调用项目管理系统接口失败，请联系管理员！");
            return  WeaResult.fail(500, "调用项目管理系统接口失败，请联系管理员！", getResultMapForAction(weaverResultMap, "result","调用项目管理系统接口失败，请联系管理员！", request.getRequestManager()));
        } catch (Exception e) {
            e.printStackTrace();
            logger_f17f81aa.error("PMProjectAcceptanceAction e: {}", e.getMessage());
            return  WeaResult.fail(500, "PMProjectAcceptanceAction e: {}"+ e, getResultMapForAction(weaverResultMap, "result",e.getMessage(), request.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;
    }
}
