package com.engine.custom.archives.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.engine.core.impl.Service;
import com.engine.custom.archives.service.HtmlToPdfServiceCus;
import com.engine.custom.archives.util.ArchivesUtil;
import com.engine.custom.archives.workflow.cmd.requestLog.LoadRequestLogDataCusCmd;
import com.engine.workflow.biz.RequestLogBiz;
import com.engine.workflow.biz.requestForm.LayoutInfoBiz;
import com.engine.workflow.cmd.requestForm.*;
import com.engine.workflow.entity.requestForm.FieldValueBean;
import com.engine.workflow.entity.requestForm.TableInfo;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.company.DepartmentComInfo;
import weaver.workflow.request.RequestManagerForTipsinfo;
import weaver.workflow.request.WFLinkInfo;
import weaver.workflow.workflow.WorkflowBillComInfo;
import weaver.workflow.workflow.WorkflowComInfo;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

public class HtmlToPdfServiceCusImpl extends Service implements HtmlToPdfServiceCus {
    public static Logger log = LoggerFactory.getLogger("Archives");
    @Override
    public Map<String, Object> getHtml(Map<String, Object> reqpParams, User user) {
        return null;
    }

    @Override
    public Map<String, Object> getFormDatas(Map<String, Object> reqpParams) {
        Map<String, Object> apidatas = new HashMap<String, Object>();
        Map<String, Object> result =new HashMap<String, Object>();
        String requestid = Util.null2String(reqpParams.get("requestid"));
        String modeid = Util.null2String(reqpParams.get("modeid"));
        String workflowid = Util.null2String(reqpParams.get("workflowid"));
        //只需要转换html
        int onlyHtml = Util.getIntValue(Util.null2String(reqpParams.get("onlyHtml")),0);
        //用wktohtml转换
        int useWk = Util.getIntValue(Util.null2String(reqpParams.get("useWk")),0);
        int useItext7 = Util.getIntValue(Util.null2String(reqpParams.get("useItext7")),0);
        //底部签字意见列表显示的数量
        int pageSize = Util.getIntValue(Util.null2String(reqpParams.get("pageSize")),100);
        //pdf或html目录
        String path = Util.null2String(reqpParams.get("path"));
        String filename = Util.null2String(reqpParams.get("filename"));
        int isTest = Util.getIntValue(Util.null2String(reqpParams.get("isTest")));
        int keepsign =  Util.getIntValue(Util.null2String(reqpParams.get("keepsign")));
        boolean onlinehtml = reqpParams.containsKey("onlinehtml") && (boolean) reqpParams.get("onlinehtml");

        Map<String, Object>  requestMap = new HashMap<>();
        requestMap.put("requestid",requestid);
        requestMap.put("modeid",modeid);
        requestMap.put("limitauth",Util.null2String(reqpParams.get("limitauth")));
        requestMap.put("forceNoPaging",1);  //明细强制不分页
        log.error("HtmltoPdfServiceimpl ---requestid:"+requestid+"-----modeid:"+modeid);

        long start2 = System.currentTimeMillis();
        //第一步：获取基础信息参数
        Map<String, Object> params = commandExecutor.execute(new GetPdfParamsCmd(requestMap,user));
        apidatas.put("params",params);
        params.put("onlyHtml",onlyHtml);
        params.put("useWk",useWk);
        params.put("useItext7",useItext7);
        params.put("path",path);
        params.put("filename",filename);
        params.put("isTest",isTest);
        params.put("keepsign",keepsign);
        params.put("onlinehtml",onlinehtml);


        int ismode = Util.getIntValue(Util.null2String(params.get("ismode")), 0);
        int layoutversion = Util.getIntValue(Util.null2String(params.get("layoutversion")), 0);

        //生成普通模式模板布局信息
        Map<String, Object> commonLayout = new HashMap<String, Object>();
        if (ismode == 0) {
            commonLayout = commandExecutor.execute(new GenerateCommonLayoutCmd(params, user));
        }

        //加载表单信息，包括字段信息、明细信息等
        Map<String, Object> forminfo = commandExecutor.execute(new FormInfoCmd(requestMap, user, params, commonLayout));
        apidatas.putAll(forminfo);
        //联动配置
        apidatas.put("linkageCfg", commandExecutor.execute(new LinkageCfgCmd(params,user)));
        //加载主表数据
        Map<String, Object> maindata = commandExecutor.execute(new FormDataCmd(requestMap, user, params, (Map<String, TableInfo>) forminfo.get("tableInfo")));
        apidatas.put("maindata", maindata.get("datas"));

        //根据流程id获取是否需要协办
        RecordSet rs = new RecordSet();
        rs.executeQuery("select * from uf_ArchivesSet where mainwfid = ?",workflowid);
        //是否有协办流程
        //------------------------------start----------------------------
        try {


        boolean isCo = false;
        String cowfid = "";
        String cofield = "";
        String cofieldid = "";
        if (rs.next()){
            cowfid = Util.null2String(rs.getString("cowfid"));
            if (!StringUtils.isBlank(cowfid)){
                isCo = true;
                cofield = Util.null2String(rs.getString("cofield"));
                cofieldid = Util.null2String(rs.getString("cofieldid"));
            }
        }
        log.info("isCo:{};cowfid:{};cofield:{};cofieldid:{}",isCo,cowfid,cofield,cofieldid);


        if(isCo){
            ArrayList<String> CoSubRequest = new ArrayList<>();
            List<String> Cowfids = Arrays.asList(cowfid.split(","));
            Map<String, String> subRequest = ArchivesUtil.getSubRequest(requestid, 6);
            log.info("subRequest:{}",subRequest);
            for (Map.Entry<String, String> subRequestEntry : subRequest.entrySet()) {
                String subWFid = subRequestEntry.getValue();
                if (Cowfids.contains(subWFid)){
                    CoSubRequest.add(subRequestEntry.getKey());
                }
            }
            log.info("CoSubRequest.size:{}",CoSubRequest.size());
            if (CoSubRequest.size() != 0){
                WorkflowComInfo wf = new WorkflowComInfo();
                WorkflowBillComInfo wcInfo = new WorkflowBillComInfo();
                String formId = wf.getFormId(Cowfids.get(0));
                String tablename = wcInfo.getTablename(formId);
                String cosql = "select "+cofield+" from " + tablename + " where " +
                        " requestid in ( " + String.join(",",CoSubRequest) + " ) " +
                        " order by requestid asc ";
                log.info("cosql:{}",cosql);

                rs.executeQuery(cosql);
                log.info("rs.getExceptionMsg():{}",rs.getExceptionMsg());
                String fieldValue = "";
                String[] cofieldsplit = cofield.split(",");
                String codept = cofieldsplit[0]; //协办部门
                String corequirement = cofieldsplit[1]; //协办要求

                while (rs.next()){
                    String codeptValue = Util.null2String(rs.getString(codept));
                    String corequirementText = Util.null2String(rs.getString(corequirement));
                    log.info("codeptValue:{}",codeptValue);
                    log.info("corequirementText:{}",corequirementText);
                    String codeptText = "";
                    String[] split = codeptValue.split(",");
                    DepartmentComInfo deptCom = new DepartmentComInfo();
                    for (String item : split) {
                        try {
                            String departmentName = deptCom.getDepartmentName(item);
                            codeptText = codeptText + "," + departmentName;
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    log.info("codeptText:{}",codeptText);
                    if (codeptText.startsWith(",")){
                        codeptText = codeptText.substring(1);
                    }
                    if (!StringUtils.isBlank(codeptText)) {
                        fieldValue = fieldValue + "\n" + codeptText + " : " + corequirementText;
                    }
                }
                log.info("fieldValue:{}",fieldValue);
                if (fieldValue.startsWith("\n")){
                    fieldValue = fieldValue.substring(1);
                }
                log.info("fieldValue:{}",fieldValue);
                HashMap<String, Object> cofieldMap = new HashMap<>();
                cofieldMap.put("value",fieldValue);
                log.info("maindataold:{}",maindata);
                FieldValueBean fieldValueBean = new FieldValueBean();
                fieldValueBean.setValue(fieldValue);
                Map datas = (Map)maindata.get("datas");
                log.info("datas:{}",datas);
                log.info("datas:{}", datas.getClass().getName() );

                datas.put(cofieldid,fieldValueBean);
                log.info("maindatanew:{}",maindata);
            }
        }
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
        }
        //------------------------------end----------------------------
        //明细表数据
        Map<String, TableInfo> tableinfomap = (Map<String, TableInfo>)forminfo.get("tableInfo");
        List<String> detailmark = new ArrayList<String> ();
        for (String key:tableinfomap.keySet()){
            if (key.contains("detail_")){
                detailmark.add(key);
            }
        }
        if (detailmark.size()>0){
            String isprint = Util.null2String(params.get("isprint"));
            requestMap.put("reqParams",JSON.toJSONString(params));
            requestMap.put("ismode",ismode);
            requestMap.put("ismonitor","0");
            requestMap.put("isprint",isprint);
            requestMap.put("modeid",modeid);
            requestMap.put("detailmark", StringUtils.join(detailmark.toArray(), ","));
            Map<String, Object> detaildata = commandExecutor.execute(new FormDataCmd(requestMap, user));
            apidatas.put("detaildata", detaildata);
        }


        log.error("ismode:"+ismode);

        //第五步：模板布局
        if (ismode == 0 || (ismode == 2 && layoutversion == 2)) {
            String layoutStr = "";
            if (ismode == 0) {    //普通模式
                layoutStr = Util.null2String(commonLayout.get("layoutStr"));
            } else if (ismode == 2) {    //html模式

                int layoutid = Util.getIntValue(Util.null2String(params.get("modeid")), 0);
                log.error("layoutid:"+layoutid);
                layoutStr = new LayoutInfoBiz().getLayoutStr(layoutid);
            }
            apidatas.put("datajson",layoutStr);
        }else {
            result.put("unsupported",""+weaver.systeminfo.SystemEnv.getHtmlLabelName(10005682,weaver.general.ThreadVarLanguage.getLang())+"");
            return result;
        }
        RecordSet recordSet = new RecordSet();

        //获取签字意见可查看的nodeid
        String viewLogIdstr = RequestLogBiz.getViewLogIds(Util.getIntValue(requestid),user.getUID(),(int)params.get("workflowid"));
        String src = Util.null2String(reqpParams.get("src"));
        if ("intervenor".equals(src) ) {
            List <String> canViewIds = new ArrayList <String>();
            String tempNodeId = "-1";
            recordSet.executeSql("select nodeid from workflow_flownode where workflowid= " + params.get("workflowid") + " and exists(select 1 from workflow_nodebase where id=workflow_flownode.nodeid and (requestid is null or requestid=" + requestid + "))");
            while (recordSet.next()) {
                tempNodeId = recordSet.getString("nodeid");
                if (!canViewIds.contains(tempNodeId)) {
                    canViewIds.add(tempNodeId);
                }
            }
            viewLogIdstr = String.join(",", canViewIds);
        }
        //获取签字意见
        HttpServletRequest request = null;
        // int workflowid = (int) params.get("workflowid");
        int nodeid  =(int) params.get("nodeid");
        String isFormSignature = "";
        recordSet.executeSql("select isFormSignature from workflow_flownode where workflowId=" + workflowid + " and nodeId=" + nodeid);
        if (recordSet.next()) {
            isFormSignature = Util.null2String(recordSet.getString("isFormSignature"));
        }
        boolean isOldWf =false;
        RequestManagerForTipsinfo requestManagerForTipsinfo = new RequestManagerForTipsinfo();
        isOldWf = requestManagerForTipsinfo.isOldOrNewFlag(Util.getIntValue(requestid));
        String maxrequestlogid = "";
        params.put("requestid",requestid);
        params.put("viewLogIds",viewLogIdstr);
        params.put("creatorNodeId",WFLinkInfo.getCreatNodeId(workflowid+""));
        params.put("isHideInput","1");
        params.put("isFormSignature",isFormSignature);
        params.put("pgnumber",1);
        params.put("wfsignlddtcnt",pageSize); //底部签字意见一页的数量
        params.put("orderbytype","desc");
        params.put("isOldWf",isOldWf);
        params.put("maxrequestlogid",maxrequestlogid);
        params.put("isSubrequest",reqpParams.get("isSubrequest"));
        Map<String,Object> requestlog =commandExecutor.execute(new LoadRequestLogDataCusCmd(request, user, params,"topdf"));
        apidatas.put("requestLog",requestlog);
        log.error(JSONObject.toJSONString(apidatas));
        long end2 = System.currentTimeMillis()-start2;
        BaseBean baseBean = new BaseBean();
        log.error("loadform接口+底部签字意见+detail耗时："+end2);
        log.error("apidata"+JSONObject.toJSONString(apidatas));

        //是否开启水印
        apidatas.put("isOpenWaterMark",reqpParams.get("isOpenWaterMark"));

        //转html/pdf
        Map<String,Object> html = commandExecutor.execute(new HtmlToPdfCmd(apidatas,user));

        result.putAll(html);
        long end = System.currentTimeMillis()-start2;
        log.error("【pdf】 总耗时："+end);
        return html;

    }

    @Override
    public Map<String, Object> getFormInfoForWM(Map<String, Object> reqpParams) {
        Map<String, Object> apidatas = new HashMap<String, Object>();
        Map<String, Object> result =new HashMap<String, Object>();
        String requestid = Util.null2String(reqpParams.get("requestid"));
        String modeid = Util.null2String(reqpParams.get("modeid"));

        Map<String, Object>  requestMap = new HashMap<>();
        requestMap.put("requestid",requestid);
        requestMap.put("modeid",modeid);
        requestMap.put("limitauth",Util.null2String(reqpParams.get("limitauth")));
        requestMap.put("forceNoPaging",1);  //明细强制不分页

        long start2 = System.currentTimeMillis();
        //第一步：获取基础信息参数
        Map<String, Object> params = commandExecutor.execute(new GetPdfParamsCmd(requestMap,user));
        apidatas.put("params",params);

        int ismode = Util.getIntValue(Util.null2String(params.get("ismode")), 0);
        int layoutversion = Util.getIntValue(Util.null2String(params.get("layoutversion")), 0);

        //生成普通模式模板布局信息
        Map<String, Object> commonLayout = new HashMap<String, Object>();
        if (ismode == 0) {
            commonLayout = commandExecutor.execute(new GenerateCommonLayoutCmd(params, user));
        }

        //加载表单信息，包括字段信息、明细信息等
        Map<String, Object> forminfo = commandExecutor.execute(new FormInfoCmd(requestMap, user, params, commonLayout));
        apidatas.putAll(forminfo);

        //加载主表数据
        Map<String, Object> maindata = commandExecutor.execute(new FormDataCmd(requestMap, user, params, (Map<String, TableInfo>) forminfo.get("tableInfo")));
        apidatas.put("maindata", maindata.get("datas"));
        return apidatas;
    }

}
