package com.engine.bmj.cmd;

import com.engine.bmj.utils.DocCreateUtil;
import com.engine.bmj.utils.WordTemplateUtil;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.secret.util.ConfigUtil;
import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;
import weaver.file.ImageFileManager;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import java.io.*;
import java.util.*;

public class MaterialCreateCmd extends AbstractCommonCommand<Map<String,Object>> {
    @Override
    public BizLogContext getLogContext() {
        return null;
    }

    public MaterialCreateCmd(Map<String,Object> params, User user) {
        this.params = params;
        this.user = user;
    }
    @Override
    public Map<String, Object> execute(CommandContext commandContext) {

        int newDocid = -1;
        Map<String, Object> apidatas = new HashMap<String, Object>();
        DocCreateUtil docCreateUtil = new DocCreateUtil();
        BaseBean bb = new BaseBean();
        String docid = Util.null2String(params.get("docid"));
        bb.writeLog("MaterialCreateCmd-client:"+docid);

        RecordSet rs = new RecordSet();
        if(StringUtils.isNotEmpty(docid)){

            String imagefileid = "";
            String imageFileName = "";
            String fileRealPath = "";
            String sql = " select t1.imagefileid,t1.imageFileName,t1.fileRealPath,t2.imagefilename as realname from ImageFile t1 inner join DocImageFile t2 on t1.imagefileid = t2.imagefileid where t1.docid =  " + docid;
            bb.writeLog("sql:"+sql);
            rs.execute(sql);
            if (rs.next())
            {
                imageFileName = Util.null2String(rs.getString("realname"));
                if (imageFileName.equals("")) {
                    imageFileName = Util.null2String(rs.getString("imageFileName"));
                }
                imagefileid = Util.null2String(rs.getString("imagefileid"));
                fileRealPath = Util.null2String(rs.getString("fileRealPath"));
            }

            if(StringUtils.isNotBlank(imagefileid) && StringUtils.isNotBlank(imageFileName) && StringUtils.isNotBlank(fileRealPath)){
                Map<String,Object> dataMap = new HashMap<String,Object>();
                String saveMaterialPath = "";
                if(StringUtils.isNotBlank(fileRealPath)){
                    saveMaterialPath = fileRealPath.substring(0,fileRealPath.indexOf("filesystem"))+File.separator+"material"+File.separator+System.currentTimeMillis();
                }

                boolean result = false;
                File parentFile = new File(saveMaterialPath);
                if (!parentFile.exists()) {
                    result = parentFile.mkdirs();
                }else{
                    result = true;
                }

                if(result){
                    InputStream inputstream = ImageFileManager.getInputStreamById(Util.getIntValue(imagefileid));

                    WordTemplateUtil wordTemplateUtil = null;
                    try {
                        wordTemplateUtil = new WordTemplateUtil(inputstream);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                    wordTemplateUtil.replaceDocument(dataMap);

                    String outpath = saveMaterialPath + File.separator + new File(imageFileName);
                    File outputFile = new File(outpath);

                    FileOutputStream fileOutputStream = null;
                    try {
                        fileOutputStream = new FileOutputStream(outputFile);
                        wordTemplateUtil.getDocument().write(fileOutputStream);

                        if(outputFile.exists()){

                            String docsubject = imageFileName;
                            String attachfilename = imageFileName;
                            String filepath = outputFile.getPath();
                            long attachlength  = outputFile.length();
                            int creater = user.getUID();
                            int seccategory = Util.getIntValue(ConfigUtil.getConfig("material.seccategory")) ;
                            String tempcomids = "";
                            newDocid = docCreateUtil.createMaterialDoc(docsubject,attachfilename,filepath,attachlength,creater,seccategory,tempcomids);
                        }

                        fileOutputStream.close();
                        inputstream.close();
                    } catch (FileNotFoundException e) {
                        bb.writeLog("e:"+e);
                        throw new RuntimeException(e);

                    }catch (IOException e) {
                        bb.writeLog("e:"+e);
                        throw new RuntimeException(e);
                    }finally {
                        if(fileOutputStream != null){
                            try {
                                fileOutputStream.close();
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            }
                        }
                        if(inputstream != null){
                            try {
                                inputstream.close();
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }
                }
            }
        }

        apidatas.put("docid",newDocid);
        return apidatas;
    }

    /***
     *
     * @return
     * @throws Exception
     */
    public Map<String,Object> getDocLabelData(String requestid,String shry) throws Exception
    {
        RecordSet rs = new RecordSet();

        Map<String, Object> wordDataMap = new HashMap<>();

        Map<String, Object> parametersMap = new HashMap<>();
        parametersMap.put("shry",shry);

        String formTable = "";
        String sql = " select abs(k.formid) as formid from workflow_requestbase t inner join workflow_base k on k.id = t.workflowid " +
                     " where t.requestid = "+requestid;
        rs.executeQuery(sql);
        if(rs.next()){
            formTable = "formtable_main_"+Util.null2String(rs.getString("formid"));
        }

        String mainid = "";
        if(StringUtils.isNotBlank(formTable)){
            sql = " select mainid from "+formTable+" where requestid = "+requestid;
            rs.executeQuery(sql);
            if (rs.next()){
                mainid = Util.null2String(rs.getString("mainid"));
            }
        }

        List<Map<String,Object>> table1List = new ArrayList<Map<String,Object>>();
        List<Map<String,Object>> table2List = new ArrayList<Map<String,Object>>();
        List<Map<String,Object>> table3List = new ArrayList<Map<String,Object>>();

        if(StringUtils.isNotBlank(mainid)){

            sql = " select * from "+formTable+"_dt1 where mainid = "+mainid;
            rs.executeQuery(sql);
            while(rs.next()){
                String glscx = Util.null2String(rs.getString("glscx"));
                String scx = Util.null2String(rs.getString("scx"));
                String scjg = Util.null2String(rs.getString("scjg"));
                String pdjg = Util.null2String(rs.getString("pdjg"));
                Map<String,Object> map = new HashMap<String,Object>();
                map.put("glscx",glscx);
                map.put("scx",scx);
                map.put("scjg",scjg);
                map.put("pdjg",pdjg);
                table1List.add(map);
            }

            sql = " select * from "+formTable+"_dt2 where mainid = "+mainid;
            rs.executeQuery(sql);
            while(rs.next()){
                String glscx = Util.null2String(rs.getString("glscx"));
                String scx = Util.null2String(rs.getString("scx"));
                String scjg = Util.null2String(rs.getString("scjg"));
                String pdjg = Util.null2String(rs.getString("pdjg"));
                Map<String,Object> map = new HashMap<String,Object>();
                map.put("glscx",glscx);
                map.put("scx",scx);
                map.put("scjg",scjg);
                map.put("pdjg",pdjg);
                table2List.add(map);
            }

            sql = " select * from "+formTable+"_dt3 where mainid = "+mainid;
            rs.executeQuery(sql);
            while(rs.next()){
                String glscx = Util.null2String(rs.getString("glscx"));
                String scx = Util.null2String(rs.getString("scx"));
                String scjg = Util.null2String(rs.getString("scjg"));
                String pdjg = Util.null2String(rs.getString("pdjg"));
                String pdbz = Util.null2String(rs.getString("pdbz"));
                Map<String,Object> map = new HashMap<String,Object>();
                map.put("glscx",glscx);
                map.put("scx",scx);
                map.put("scjg",scjg);
                map.put("pdjg",pdjg);
                table3List.add(map);
            }
        }

        wordDataMap.put("parametersMap", parametersMap);
        wordDataMap.put("table1", table1List);
        wordDataMap.put("table2", table2List);
        wordDataMap.put("table3", table3List);

        return wordDataMap;
    }
}
