package com.api.doc.detail.service;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.api.doc.detail.util.*;
import com.api.doc.mobile.systemDoc.util.SystemDocUtil;
import com.api.doc.search.bean.RightMenu;
import com.api.doc.search.util.DocSptm;
import com.api.doc.search.util.DocTableType;
import com.api.doc.search.util.RightMenuType;
import com.api.networkdisk.util.DocIconUtil;
import com.cloudstore.dev.api.util.Util_TableMap;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import weaver.conn.RecordSet;
import weaver.docs.docs.DocImageManager;
import weaver.docs.docs.DocManager;
import weaver.docs.docs.util.DesUtils;
import weaver.general.GCONST;
import weaver.general.ThreadVarLanguage;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.resource.ResourceComInfo;
import weaver.systeminfo.SystemEnv;
import weaver.wps.WebOfficeUtil;
import weaver.wps.doccenter.utils.Config;

import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DocShareOutService {

    private HttpServletRequest request;

    public void setRequest(HttpServletRequest request){
        this.request = request;
    }



    /**
     * 获取附件列表(登录前门户)
     * */
    public Map<String,Object> getDocShareOutList(User user) throws Exception{
        Map<String,Object> apidatas = new HashMap<String,Object>();
        int language = user.getLanguage();
        String sqlFrom = " docshareoutrecord d1,docdetail d2 ";
        String sqlWhere =" d1.docid=d2.id and d1.urlcreateor="+ user.getUID();
        String backFields = " d1.id,d1.docid,d1.startdate,d2.docextendname,d2.docsubject ";
        String orderBy = " d1.id desc, d1.docid desc ";
        String tabletype = "none";
        DocTableType docTableType = DocTableType.DOC_SHARE;

        String tableString=""+
                "<table pageUid=\"" + docTableType.getPageUid() + "\" pageId=\"" + docTableType.getPageUid() + "\" pagesize=\"" + docTableType.getPageSize() + "\" tabletype=\""+tabletype+"\">"+
                " <checkboxpopedom showmethod=\"true\"   id=\"checkbox\" />"+
                "<sql backfields=\"" + backFields + "\" sqlform=\""+Util.toHtmlForSplitPage(sqlFrom)+"\" sqlorderby=\""+orderBy+"\"  sqlprimarykey=\"d1.id\" sqlsortway=\"Desc\" sqlwhere=\""+Util.toHtmlForSplitPage(sqlWhere)+"\" sqldistinct=\"true\"  />";

        tableString += "<operates width=\"20%\">";
        tableString += "<popedom async=\"false\" transmethod=\"com.api.doc.search.util.DocSptm.isDownLoad2Version\" otherpara=\"" +true+ "+" +true+ "\"></popedom> ";
        tableString += "     <operate href=\"javascript:cancelShare()\"  text=\""+SystemEnv.getHtmlLabelName(129158,user.getLanguage())+"\" index=\"0\"/>";
        tableString += "     <operate href=\"javascript:editShare()\"  text=\""+SystemEnv.getHtmlLabelName(539360,user.getLanguage())+"\" index=\"1\"/>";
        tableString += "</operates>"+
                "<head>"+
                "<col  width=\"5%\" text=\""+SystemEnv.getHtmlLabelName(33234,language)+"\" column=\"docextendname\"  orderkey=\"docextendname\" transmethod=\"com.api.doc.search.util.DocSptm.getDocType\"/>"+
                "<col  width=\"60%\"  text=\""+SystemEnv.getHtmlLabelName(58,language)+"\" column=\"id\"  orderkey=\"id\" transmethod=\"com.api.doc.search.util.DocSptm.getShareOutDocName\"/>"+
                "<col  width=\"30%\"  text=\""+SystemEnv.getHtmlLabelName(391245,language)+"\" column=\"startdate\"  orderkey=\"startdate\" />"+
                "<col  width=\"5%\"  hide=\"true\" text=\""+SystemEnv.getHtmlLabelName(58,language)+"\" column=\"docsubject\"  orderkey=\"docsubject\" />"+
                "</head>" +
                "</table>";

        String sessionkey = docTableType.getPageUid() + "_" + Util.getEncrypt(Util.getRandom());
        Util_TableMap.setVal(sessionkey, tableString);


        apidatas.put("sessionkey", sessionkey);

        return apidatas;
    }

    /**
     * 创建外部人员
     * @param user
     * @param paramMap
     * @return
     * @throws Exception
     */
    public Map<String, Object> createHrmResourceOut(User user, Map<String, String> paramMap) throws Exception {
        Map<String,Object> apidatas = new HashMap<String,Object>();
        String name = Util.null2String(paramMap.get("name"));
        String createor = user.getUID()+"";
        String phonenumber = Util.null2String(paramMap.get("phonenumber"));
        String email = Util.null2String(paramMap.get("email"));
        if(StringUtils.isEmpty(name)){
            apidatas.put("api_status",false);
            apidatas.put("msg",SystemEnv.getHtmlLabelName( 388858, user
                    .getLanguage()));
            return apidatas;
        }
        int wbryid = DocShareOutOperateUtil.insertIntoWbry(name, createor, phonenumber, email);
        apidatas.put("api_status",true);
        apidatas.put("id",wbryid);
        apidatas.put("name",name);
        return apidatas;
    }

    /**
     * 获取系统设置验证方式
     * @param user
     * @return
     * @throws Exception
     */
    public Map<String, Object> getSysVerifymode(User user) throws Exception {
        Map<String,Object> apidatas = new HashMap<String,Object>();
        RecordSet rs = new RecordSet();
        String sql = "select outsharemethod from docapplysetting where settingtype='doccontentinfoset'";
        rs.executeSql(sql);
        String outsharemethod = "";
        if(rs.next()){
            outsharemethod = Util.null2String(rs.getString("outsharemethod"));
        }
        apidatas.put("api_status",true);
        apidatas.put("outsharemethod",outsharemethod);
        return apidatas;
    }

    /**
     * 获取文档外部链接
     * @author wangqs
     * */
    public Map<String,Object> getDocShareOut(int id,User user) throws Exception {
        Map<String,Object> apidatas = new HashMap<String,Object>();
        if(id == 0){
            apidatas.put("status",-1);
            apidatas.put("msg",SystemEnv.getHtmlLabelName(388858,user.getLanguage()));
            return apidatas;
        }
        RecordSet rs = new RecordSet();
        String select_sql = "  select * from docshareoutrecord where id=? ";
        rs.executeQuery(select_sql,id);
        if(rs.next()){
            String docid = Util.null2String(rs.getString("docid"));
            String shareouturllink = Util.null2String(rs.getString("shareouturllink"));
            String validdatetype = Util.null2String(rs.getString("validdatetype"));
            String enddate = Util.null2String(rs.getString("enddate"));
            String righttype = Util.null2String(rs.getString("righttype"));
            String downcount = Util.null2String(rs.getString("downcount"));
            String sharetype = Util.null2String(rs.getString("sharetype"));
            String shareobj = Util.null2String(rs.getString("shareobj"));
            JSONArray shareobjarray = new JSONArray();
            if("2".equals(sharetype) && StringUtils.isNotEmpty(shareobj)){
                ResourceComInfo rci = new ResourceComInfo();
                for (String uid:shareobj.split(",")){
                    String lastname = rci.getLastname(uid);
                    JSONObject obj = new JSONObject();
                    obj.put("id",uid);
                    obj.put("name",lastname);
                    shareobjarray.add(obj);
                }
            }else if("3".equals(sharetype) && StringUtils.isNotEmpty(shareobj)){
                for (String uid:shareobj.split(",")){
                    JSONObject obj = new JSONObject();
                    obj.put("id",uid);
                    obj.put("name", DocShareOutOperateUtil.getOutNameById(uid));
                    shareobjarray.add(obj);
                }
            }
            String isopenverify = Util.null2String(rs.getString("isopenverify"));
            String verifymode = Util.null2String(rs.getString("verifymode"));
            String[] verifymodeArr = verifymode.split(",");
            String randomchar = Util.null2String(rs.getString("randomchar"));
            String phonenumber = Util.null2String(rs.getString("phonenumber"));
            String email = Util.null2String(rs.getString("email"));
            apidatas.put("id",id);
            apidatas.put("docid",docid);
            apidatas.put("shareouturllink",shareouturllink);
            apidatas.put("validdatetype",validdatetype);
            apidatas.put("enddate",enddate);
            apidatas.put("righttype",righttype);
            apidatas.put("downcount",downcount);
            apidatas.put("sharetype",sharetype);
            apidatas.put("shareobj",shareobjarray);
            apidatas.put("isopenverify",isopenverify);
            apidatas.put("verifymode",verifymode);
            if(StringUtils.isNotEmpty(randomchar) &&  verifymode.contains("1")){
                apidatas.put("randomchar",randomchar);
            }
            apidatas.put("phonenumber",phonenumber);
            apidatas.put("email",email);
        }
        apidatas.put("api_status",true);
        return apidatas;
    }

    /**
     *
     * @param verifymode
     * @return
     */
    private String judgeOutShareObj(String verifymode,String shareobj){
        RecordSet rs = new RecordSet();
        rs.executeSql(" select ID,PHONENUMBER,EMAIL from uf_wbry where id in("+shareobj+")");
        String phonenumber = "";
        String id = "";
        String email = "";
        String returnObj = "";
        while(rs.next()){
            id = rs.getString("ID");
            phonenumber = rs.getString("PHONENUMBER");
            email = rs.getString("EMAIL");
            returnObj = "2".equals(verifymode)?(StringUtils.isNotEmpty(phonenumber)?returnObj:returnObj+","+id):(StringUtils.isNotEmpty(email)?returnObj:returnObj+","+id);
        }
        returnObj = returnObj.length()>0?returnObj.substring(1):returnObj;
        String names = DocShareOutOperateUtil.getOutNameById(returnObj);
        return names;
    }


    /**
     * 创建文档外部链接
     * @author wangqs
     * */
    public Map<String,Object> createLinkURL(int docid, User user, Map<String, String> paramMap){
        Map<String,Object> apidatas = new HashMap<String,Object>();
        if(docid == 0){
            apidatas.put("status",-1);
            apidatas.put("msg",SystemEnv.getHtmlLabelName(19711,user.getLanguage()));
            return apidatas;
        }
        String randomchar = "";
        String oaurl = Util.null2String(paramMap.get("oa_url"));
        DocSptm ds = new DocSptm();
        String shareouturllink = oaurl + DocSptm.OUT_DOC_LINK + "#/main/document/outShareDetail" + "?id=" + ds.getOutDocId2(docid+"");
        int validdatetype = Util.getIntValue(paramMap.get("validdatetype"),1);
        String enddate = Util.null2String(paramMap.get("enddate"));
        String righttype = Util.null2String(paramMap.get("righttype"));
        String downcount = Util.null2String(paramMap.get("downcount"));
        String sharetype = Util.null2String(paramMap.get("sharetype"));
        String shareobj = Util.null2String(paramMap.get("shareobj"));
        String isopenverify = Util.null2String(paramMap.get("isopenverify"));
        String verifymode = Util.null2String(paramMap.get("verifymode"));
        if(verifymode.contains("1") && "2".equals(isopenverify)){
            randomchar = DocShareOutOperateUtil.getRandomChar(docid);
        }
        String[] verifymodeArr = verifymode.split(",");
        if("2".equals(righttype) &&verifymodeArr.length == 1){
            String names =  judgeOutShareObj(verifymode, shareobj);
            if(StringUtils.isNotEmpty(names)){
                String verifytype = "2".equals(verifymode)?SystemEnv.getHtmlLabelName(125238,user.getLanguage()):SystemEnv.getHtmlLabelName(20869,user.getLanguage());
                String msg = StrUtil.format(SystemEnv.getHtmlLabelName(539399, user.getLanguage()), names, verifytype);
                apidatas.put("msg",msg);
            }
        }
        String phonenumber = Util.null2String(paramMap.get("phonenumber"));
        String email = Util.null2String(paramMap.get("email"));
        shareouturllink = DocShareOutOperateUtil.insertIntoDocoutshare(docid, user.getUID(), shareouturllink, validdatetype, enddate, righttype, downcount,sharetype, shareobj, isopenverify, verifymode, randomchar, phonenumber, email);
        if(StringUtils.isNotEmpty(shareouturllink)){
            shareouturllink = StringUtils.isNotEmpty(randomchar) && verifymode.contains("1")?shareouturllink+"&randomchar="+randomchar:shareouturllink;
            BufferedImage qrCodeImage = DocShareOutOperateUtil.createQRCodeImage(shareouturllink);
            int qrimgid = DocShareOutOperateUtil.save2Image(qrCodeImage, "jpg");
            apidatas.put("qrlink", oaurl + GCONST.getContextPath() + DocSptm.FILE_DOWNLOAD + "?fileid=" + qrimgid);
            apidatas.put("qrimgid", qrimgid);
        }
        apidatas.put("api_status",true);
        apidatas.put("docid",docid);
        if(StringUtils.isNotEmpty(randomchar) &&  verifymode.contains("1")){
            apidatas.put("randomchar",randomchar);
        }
        apidatas.put("shareouturllink",shareouturllink);
        return apidatas;
    }

    /**
     * 修改文档外部链接
     * @author wangqs
     * */
    public Map<String,Object> updateLinkURL(int id, User user, Map<String, String> paramMap){
        Map<String,Object> apidatas = new HashMap<String,Object>();
        if(id == 0){
            apidatas.put("status",-1);
            apidatas.put("msg",SystemEnv.getHtmlLabelName(388858,user.getLanguage()));
            return apidatas;
        }
        int docid = Util.getIntValue(paramMap.get("docid"));
        int validdatetype = Util.getIntValue(paramMap.get("validdatetype"),1);
        String enddate = Util.null2String(paramMap.get("enddate"));
        String righttype = Util.null2String(paramMap.get("righttype"));
        String downcount = Util.null2String(paramMap.get("downcount"));
        String sharetype = Util.null2String(paramMap.get("sharetype"));
        String shareobj = Util.null2String(paramMap.get("shareobj"));
        String isopenverify = Util.null2String(paramMap.get("isopenverify"));
        String verifymode = Util.null2String(paramMap.get("verifymode"));
        String phonenumber = Util.null2String(paramMap.get("phonenumber"));
        String email = Util.null2String(paramMap.get("email"));
        String oaurl = Util.null2String(paramMap.get("oa_url"));
        DocShareOutOperateUtil.updateDocoutshare(id,user.getUID(),validdatetype,enddate,righttype,downcount,sharetype,shareobj,isopenverify,verifymode,phonenumber,email);
        apidatas.put("api_status",true);
        apidatas.put("docid",docid);
        String[] verifymodeArr = verifymode.split(",");
        if("2".equals(righttype) &&verifymodeArr.length == 1){
            String names =  judgeOutShareObj(verifymode, shareobj);
            if(StringUtils.isNotEmpty(names)){
                String verifytype = "2".equals(verifymode)?SystemEnv.getHtmlLabelName(125238,user.getLanguage()):SystemEnv.getHtmlLabelName(20869,user.getLanguage());
                String msg = StrUtil.format(SystemEnv.getHtmlLabelName(539399, user.getLanguage()), names, verifytype);
                apidatas.put("msg",msg);
            }
        }
        RecordSet rs = new RecordSet();
        rs.executeSql(" select shareouturllink,randomchar from docshareoutrecord where id="+id);
        String shareouturllink = "";
        String randomchar = "";
        if(rs.next()){
            shareouturllink = Util.null2String(rs.getString("shareouturllink"));
            randomchar = Util.null2String(rs.getString("randomchar"));
        }
        if(StringUtils.isEmpty(randomchar) && "2".equals(isopenverify) && verifymode.contains("1")){
            randomchar = DocShareOutOperateUtil.getRandomChar(docid);
            rs.executeUpdate(" update docshareoutrecord set randomchar=? where id=? ",randomchar,id);
        }else if("1".equals(isopenverify) || !verifymode.contains("1")){
            randomchar = "";
        }
        apidatas.put("randomchar",randomchar);
        if(StringUtils.isNotEmpty(shareouturllink)){
            shareouturllink = StringUtils.isNotEmpty(randomchar) && verifymode.contains("1")?shareouturllink+"&randomchar="+randomchar:shareouturllink;
            BufferedImage qrCodeImage = DocShareOutOperateUtil.createQRCodeImage(shareouturllink);
            int qrimgid = DocShareOutOperateUtil.save2Image(qrCodeImage, "jpg");
            apidatas.put("qrlink", oaurl + GCONST.getContextPath() + DocSptm.FILE_DOWNLOAD + "?fileid=" + qrimgid);
        }
        apidatas.put("shareouturllink",shareouturllink);
        return apidatas;
    }

    /**
     * 创建外部人员
     * @param ids
     * @param user
     * @return
     * @throws Exception
     */
    public Map<String, Object> cancelDocShareOut(String ids,User user) throws Exception {
        Map<String,Object> apidatas = new HashMap<String,Object>();
        if(StringUtils.isEmpty(ids)){
            apidatas.put("api_status",false);
            apidatas.put("msg",SystemEnv.getHtmlLabelName( 388858, user
                    .getLanguage()));
            return apidatas;
        }

        RecordSet rs = new RecordSet();
        String delSql = " delete from docshareoutrecord where urlcreateor="+user.getUID()+" and id in ("+ids+")";
        rs.executeSql(delSql);
        apidatas.put("api_status",true);
        return apidatas;
    }

    /**
     * 校验文件是否开启密码,连接是否存在
     * @param docid
     * @param idshareout
     * @param randomchar
     * @return
     * @throws Exception
     */
    public Map<String, Object> checkIsopenverify(int docid, int idshareout, String randomchar) throws Exception {
        Map<String,Object> apidatas = new HashMap<String,Object>();
        RecordSet rs = new RecordSet();
        rs.executeQuery(" SELECT ISOPENVERIFY,VERIFYMODE FROM docshareoutrecord WHERE id=? and docid=?",idshareout,docid);
        String isopenverify = "";
        String verifymode = "";
        if(rs.next()){
            apidatas.put("api_status",true);
            isopenverify = rs.getString("ISOPENVERIFY");
            verifymode = rs.getString("VERIFYMODE");
        }else {
            apidatas.put("api_status",false);
            apidatas.put("msg",SystemEnv.getHtmlLabelName( 539922, ThreadVarLanguage.getDefaultLang()));
        }
        //判断分享是否超时
        boolean flag = DocShareOutOperateUtil.judgeIsOvertime(docid,idshareout);
        if(!flag){
            apidatas.put("api_status",false);
            apidatas.put("msg",SystemEnv.getHtmlLabelName( 539923, ThreadVarLanguage.getDefaultLang()));
        }
        if(StringUtils.isNotEmpty(randomchar)){
            flag = DocShareOutOperateUtil.judegeRandomChar(docid, idshareout, "1", randomchar, "", "");
            isopenverify = flag?"1":isopenverify;
        }
        apidatas.put("isopenverify",isopenverify);
        apidatas.put("verifymode",verifymode);
        return apidatas;
    }

    /**
     * 获取右键菜单及顶部按钮
     * @param docid
     * @param idshareout
     * @return
     * @throws Exception
     */
    public List<RightMenu> getRightMenus(int docid,int idshareout) throws Exception {
        List<RightMenu> rightMenus = new ArrayList<RightMenu>();
        RecordSet rs = new RecordSet();
        rs.executeQuery(" SELECT DOWNCOUNT,RIGHTTYPE FROM docshareoutrecord WHERE id=? and docid=?",idshareout,docid);
        int downcount = 0;
        int righttype = 1;
        if(rs.next()){
            downcount = Util.getIntValue(Util.null2String(rs.getString("DOWNCOUNT")), 0);
            righttype = Util.getIntValue(Util.null2String(rs.getString("RIGHTTYPE")), 1);
        }
        rs.executeSql("select doctype from DOCDETAIL  where ID=" + docid);
        int doctype = 1;
        if (rs.next()) {
            doctype = Util.getIntValue(rs.getString("doctype"), 1);
        }
        DocSptm ds = new DocSptm();
        String shareoutDocId = ds.getOutDocId2(docid + "");
        if((downcount>0 || downcount == -1) && doctype==2){
            RightMenu rightMenu = new RightMenu(7, RightMenuType.BTN_DOWNLOAD,"",true);

            String mw = DocSptm.getMW(docid + "");

//            rightMenu.setParams("docid="+shareoutDocId+"&idshareout="+idshareout);
            rightMenu.setParams("docid="+ mw +"&idshareout="+idshareout);
            rightMenus.add(rightMenu);
        }
        if(doctype==1&&righttype == 2){
            RightMenu rightMenu = new RightMenu(7, RightMenuType.BTN_SAVE,"",true);
            rightMenu.setParams("docid="+shareoutDocId+"&idshareout="+idshareout);
            rightMenus.add(rightMenu);
        }
        return rightMenus;
    }

    /**
     * 校验文件是否开启密码,连接是否存在
     * @param docid
     * @param idshareout
     * @param verifymodeGive
     * @param phonenumber
     * @param email
     * @return
     * @throws Exception
     */
    public Map<String, Object> judgeVerifymode(int docid, int idshareout, String verifymodeGive, String randomcharGive, String phonenumber, String email) throws Exception {
        Map<String,Object> apidatas = new HashMap<String,Object>();
        RecordSet rs = new RecordSet();
        rs.executeQuery(" SELECT ISOPENVERIFY,VERIFYMODE,SHARETYPE,RANDOMCHAR FROM docshareoutrecord WHERE id=? and docid=?",idshareout,docid);
        String isopenverify = "";
        String verifymode = "";
        if(rs.next()){
            apidatas.put("api_status",true);
            isopenverify = rs.getString("ISOPENVERIFY");
            verifymode = rs.getString("VERIFYMODE");
        }else {
            apidatas.put("api_status",false);
            apidatas.put("msg",SystemEnv.getHtmlLabelName( 388858,ThreadVarLanguage.getDefaultLang()));
            return apidatas;
        }
        boolean flag = false;
        if("2".equals(isopenverify) && verifymode.contains(verifymodeGive)){
            //判断手机号或者邮箱是否在分享范围之内
            flag = DocShareOutOperateUtil.judgeShareType(idshareout,phonenumber,email);
            if(flag){
                //判断验证码是否正确
                flag = DocShareOutOperateUtil.judegeRandomChar(docid,idshareout,verifymodeGive,randomcharGive,phonenumber,email);
                if(flag){
                    //判断分享是否超时
                    flag = DocShareOutOperateUtil.judgeIsOvertime(docid,idshareout);
                    if(flag){
                        apidatas.put("api_status",true);
                        apidatas.put("msg",SystemEnv.getHtmlLabelName(539924, ThreadVarLanguage.getDefaultLang()));
                    }else {
                        apidatas.put("api_status",false);
                        apidatas.put("msg",SystemEnv.getHtmlLabelName(539923, ThreadVarLanguage.getDefaultLang()));
                    }
                }else {
                    apidatas.put("api_status",false);
                    apidatas.put("msg",SystemEnv.getHtmlLabelName(528025, ThreadVarLanguage.getDefaultLang()));
                }
            }else {
                apidatas.put("api_status",false);
                apidatas.put("msg",SystemEnv.getHtmlLabelName(539925, ThreadVarLanguage.getDefaultLang()));
            }
        }
        return apidatas;
    }

    /**
     * 判断是预览还是编辑,文档正文页。
     * @param docid
     * @param idshareout
     * @param phonenumber
     * @param email
     * @return
     * @throws Exception
     */
    public Map<String, Object> getContentForShareOut(int docid, int idshareout, String phonenumber, String email, User user) throws Exception {
        Map<String,Object> apidatas = new HashMap<String,Object>();
        boolean isedit = false;
        RecordSet rs = new RecordSet();
        rs.executeSql("select doctype from DOCDETAIL  where ID=" + docid);
        int doctype = 1;
        if (rs.next()) {
            doctype = Util.getIntValue(rs.getString("doctype"), 1);
        }
        int imagefileId = 0;
        String imageFileName = "";
        int docFileType = 0;
        String extname = "";
        if (doctype == 2 || doctype == 12) {  // office文件
            String sql = "select a.imagefileid,a.imagefilename,a.docfiletype,a.versionId,b.filesize,b.comefrom from DocImageFile a,Imagefile b " +
                    " where a.imagefileid=b.imagefileid and a.docid=" + docid + " and (a.isextfile <> '1' or a.isextfile is null) order by a.versionId desc";
            rs.executeSql(sql);
            if (rs.next()) {
                imagefileId = Util.getIntValue(Util.null2String(rs.getString("imagefileid"), ""));
                imageFileName = Util.null2String(rs.getString("imagefilename"), "");
                docFileType = Util.getIntValue(rs.getString("docfiletype"), 0);
            }
        }
        if(imagefileId <= 0){
            boolean isOpenAcc = false; // 是否单附件打开
            rs.executeSql("select d1.isOpenAttachment,d1.isAutoExtendInfo from docseccategory d1,DOCDETAIL d2 WHERE d2.ID="+docid+" and d1.id=d2.SECCATEGORY ");
            if(rs.next()){
                if("1".equals(rs.getString("isOpenAttachment")) && doctype == 1){ //目录是否开启单附件打开
                    isOpenAcc = true;
                }
            }
            String mainimagefileid = DocDetailUtil.getMainImagefile(docid+"");
            Map<String,String> mainFileMap = new HashMap<String,String>();
            if("".equals(mainimagefileid)){
                mainFileMap = DocDetailUtil.getDocFirstfile(docid+"");
            }else{
                mainFileMap = DocDetailUtil.getFirstfileInfo(mainimagefileid);
            }
            if(isOpenAcc && !"".equals(Util.null2s(mainFileMap.get("imagefileid"),""))) {
                imagefileId = Util.getIntValue(mainFileMap.get("imagefileid"));
                imageFileName = Util.null2String(mainFileMap.get("imagefilename"));
            }
        }
        extname = imageFileName.indexOf(".") > -1 ? imageFileName.substring(imageFileName.lastIndexOf(".") + 1) : "";
        extname = extname.toLowerCase();
        String mFileType = "";
        boolean useWpsView = Config.isWpsDocCenterOpen();
        if (docFileType == 3) {
            mFileType = ".doc";
        } else if (docFileType == 7) {
            mFileType = ".docx";
        } else if (docFileType == 4) {
            mFileType = ".xls";
        } else if (docFileType == 8) {
            mFileType = ".xlsx";
        } else if (extname.equals("wps") || extname.equals("ppt") || extname.equals("pptx") || extname.equals("et") || extname.equals("pdf")) {
            mFileType = "." + extname;
        }else if(doctype == 1){
            mFileType = "." + extname;
        }
        String wdsql = " SELECT RIGHTTYPE FROM docshareoutrecord WHERE id=? and docid=? ";
        rs.executeQuery(wdsql,idshareout,docid);
        int righttype = 1;
        if(rs.next()){
            righttype = Util.getIntValue(Util.null2String(rs.getString("RIGHTTYPE")), 1);
        }
        DocDetailService dcs = new DocDetailService();
        String content = dcs.getDocContent(docid, user);
        if(doctype == 2 || DocDetailService.ifContentEmpty(content)){
            if(righttype == 1){
                if (useWpsView &&
                        (mFileType.equals(".doc") ||
                                mFileType.equals(".docx") ||
                                mFileType.equals(".xls") ||
                                mFileType.equals(".xlsx") ||
                                mFileType.equals(".pdf") ||
                                mFileType.equals(".ppt") ||
                                mFileType.equals(".pptx"))) {    //在线预览office文档
                    if (useWpsView) {
                        Map<String,String> params = new HashMap<String,String>();
                        params.put("userAgent",request.getHeader("user-agent"));
                        params.put("fromMould","shareout");
                        params.put("fromOutDoc","1");
                        if(user == null){
                            user = new User(1);
                        }
                        Map<String, Object> convert = WebOfficeUtil.convert(imagefileId, user, params);
                        List<Map<String,String>> dataList = (List<Map<String, String>>) convert.get("data");
                        String path = Util.null2String(dataList.get(0).get("path"));
                        content = "<iframe id=\"webOffice\" src=\""+path+"\" style=\"display: block;width: 100%;height: 100%; border:0\"></iframe>";
                    }
                }
            }else if(righttype == 2 && doctype == 2){
                if(user == null){
                    user = new User(1);
                }
                content = "<iframe id=\"webOffice\" src=\"/docs/e9/weboffice_wps_shareout.jsp?fileid=" + imagefileId + "&idshareout="+idshareout+"&phonenumber="+phonenumber+"&email="+email+"&isEdit=1&fromMould=shareout&mFileType=" + mFileType + "\" style=\"display: block;width: 100%;height: 100%; border:0\"></iframe>";
            }else if(ImageConvertUtil.canConvertType(extname)){
                Map<String,String> params = new HashMap<String,String>();
                params.put("userAgent",request.getHeader("user-agent"));
                params.put("fromMould","shareout");
				params.put("fromOutDoc","1");
                if(user == null){
                    user = new User(1);
                }
                Map<String, Object> convert = WebOfficeUtil.convert(imagefileId, user, params);
                List<Map<String,String>> dataList = (List<Map<String, String>>) convert.get("data");
                String path = Util.null2String(dataList.get(0).get("path"));
                content = "<iframe id=\"webOffice\" src=\""+path+"\" style=\"display: block;width: 100%;height: 100%; border:0\"></iframe>";
            }
        }else {
            if(content != null && !content.isEmpty()){
                int tmppos = content.indexOf("/weaver/weaver.file.FileDownload?fileid=");
                DocSptm ds = new DocSptm();
                while (tmppos != -1) {
                    int startpos = content.indexOf("\"", tmppos);
                    if (startpos >=0 && startpos >= 0) {
                        String loadStr = content.substring(tmppos,startpos);
                        String fileStr = loadStr.replace(GCONST.getContextPath()+"/weaver/weaver.file.FileDownload?fileid=","").replace("/weaver/weaver.file.FileDownload?fileid=", "");
                        String fileid = "";
                        if(Util.getIntValue(fileStr) >=0){
                            fileid = fileStr;
                        }else{
                            fileid = DocDownloadCheckUtil.DncodeFileid(fileStr);
                        }
                        //增加参数isFromOutDoc，表示来源于登录前门户的文档
                        //content = content.replace(loadStr,DocSptm.OUT_FILE_DOWNLOAD + "?fileid=" + ds.getOutDocId2(fileid));
                        content = content.replace(loadStr,DocSptm.OUT_FILE_DOWNLOAD + "?fileid=" + ds.getOutDocId2(fileid)+"&isFromOutDoc=1");
                        tmppos = content.indexOf("/weaver/weaver.file.FileDownload?fileid=",tmppos + 1);
                    }
                }
            }
        }
        isedit = righttype == 2;
        apidatas.put("isedit",isedit);
        apidatas.put("content",content);
        apidatas.put("doctype",doctype);
        apidatas.put("api_status",true);
        return apidatas;
    }

    /**
     * 获取附件列表(外部分享)
     * */
    public Map<String,Object> getDocAcc(int docid,String imageFileName,int language) throws Exception{
        Map<String,Object> apidatas = new HashMap<String,Object>();
        if(docid == 0){
            apidatas.put("api_status",false);
            apidatas.put("msg",SystemEnv.getHtmlLabelName(19711,language));
            return apidatas;
        }

        String sqlFrom = "imagefile d1,DocImageFile d2,(select id,max(versionid) versionid from DocImageFile " +
                " where docid= " + docid +
                " and docfiletype<>'1'  and docfiletype<>'11' and isextfile = '1' group by id) t3";
        String sqlWhere ="d2.imagefileid=d1.imagefileid and d2.versionId=t3.versionid and t3.id = d2.id and d2.docid="+ docid;
        String backFields = "d2.imagefileid,d2.docid as id,d2.versionId,d2.imagefilename,d2.docfiletype,d1.filesize";
        String orderBy = "d2.id, d2.versionId";
        String tabletype = "none";
        DocTableType docTableType = DocTableType.IMAGEFILE;

        if(imageFileName != null && !imageFileName.equals("")){
            sqlWhere += " and d2.imagefilename like '%" + imageFileName.replace("'", "''") + "%'";
        }


        String strOperation = "";
        //判断后台是否开启禁止office文件下载，如果开启，就不能下载。
        boolean canDownload = OutDocUtil.isDownload(docid);
        if(canDownload){
            strOperation = "<operates width=\"15%\">" +
                    "<operate href=\"javascript:doDownload()\" index=\"1\" text=\""+SystemEnv.getHtmlLabelName(258,7)+"\" />"+
                    "</operates>";
        }


        String tableString=""+
                "<table pageUid=\"" + docTableType.getPageUid() + "\" pageId=\"" + docTableType.getPageUid() + "\" pagesize=\"" + docTableType.getPageSize() + "\" tabletype=\""+tabletype+"\"  loginFree=\"true\" >"+
                "<sql backfields=\"" + backFields + "\" sqlform=\""+Util.toHtmlForSplitPage(sqlFrom)+"\" sqlorderby=\""+orderBy+"\"  sqlprimarykey=\"d1.imagefileid\" sqlsortway=\"Desc\" sqlwhere=\""+Util.toHtmlForSplitPage(sqlWhere)+"\" sqldistinct=\"true\"  />"+
                "<head>"+
                "<col  width=\"5%\" text=\""+SystemEnv.getHtmlLabelName(33234,language)+"\" column=\"docfiletype\" otherpara=\"column:imagefilename\" orderkey=\"docfiletype\" transmethod=\"com.api.doc.search.util.DocSptm.getFileType\"/>"+
                "<col  width=\"65%\"  text=\""+SystemEnv.getHtmlLabelName(23752,language)+"\" column=\"imagefilename\" otherpara=\"column:imagefileid+column:id\"  orderkey=\"imagefilename\" transmethod=\"com.api.doc.search.util.DocSptm.getLoadFilename3\"/>"+
                "<col width=\"30%\"  text=\""+SystemEnv.getHtmlLabelName(19998,language)+"\" column=\"filesize\" orderkey=\"filesize\"   transmethod=\"com.api.doc.search.util.DocSptm.getFileSize\" />"+
                "<col width=\"5%\" column=\"imagefileid\" display=\"none\"  transMethodForce=\"true\" transmethod=\"com.api.doc.search.util.DocSptm.getEncrpFileid\" />"+
                "</head>" +strOperation+
                "</table>";

        String sessionkey = docTableType.getPageUid() + "_" + Util.getEncrypt(Util.getRandom());
        Util_TableMap.setVal(sessionkey, tableString);


        apidatas.put("sessionkey", sessionkey);
        apidatas.put("api_status",true);
        return apidatas;
    }

    public Map<String, Object> sendMsg(int docid, int idshareout, int verifymode, String phonenumber, String email) {
        Map<String,Object> apidatas = new HashMap<String,Object>();
        boolean shareFlag = DocShareOutOperateUtil.judgeShareType(idshareout,phonenumber,email);
        if(shareFlag){
            String randomchar = DocShareOutOperateUtil.getRandomChar(docid);
            boolean sendflag = false;
            if(verifymode == 2){
                sendflag = DocShareOutOperateUtil.sendSms(randomchar, phonenumber);
            }else if(verifymode == 3){
                sendflag = DocShareOutOperateUtil.sendEmail(randomchar,email);
            }
            String sendtype= verifymode ==2?SystemEnv.getHtmlLabelName(22825, ThreadVarLanguage.getDefaultLang()):SystemEnv.getHtmlLabelName(34077, ThreadVarLanguage.getDefaultLang());
            if(sendflag){
                RecordSet rs = new RecordSet();
                if(verifymode == 2){
                    rs.executeSql(" delete from  HRMRESOURCESENDINFO WHERE  IDSHAREOUT="+idshareout+" AND PHONENUMBER='"+phonenumber+"'");
                }else if(verifymode == 3){
                    rs.executeSql(" delete from  HRMRESOURCESENDINFO WHERE  IDSHAREOUT="+idshareout+" AND EMAIL='"+email+"'");
                }
                rs.executeSql(" SELECT max(ID) AS MID FROM HRMRESOURCESENDINFO ");
                int mid =0;
                if(rs.next()){
                    mid = rs.getInt("MID")>0?rs.getInt("MID"):0;
                }
                mid += 1;
                int shareType = DocShareOutOperateUtil.judegeShareType(idshareout);
                String insertSql = " insert into HRMRESOURCESENDINFO(id,idshareout,sharetype,docid,phonenumber,email,verificationcode) values(?,?,?,?,?,?,?) ";
                rs.executeUpdate(insertSql,mid,idshareout,shareType,docid,phonenumber,email,randomchar);
                apidatas.put("api_status",true);
                apidatas.put("msg",sendtype+SystemEnv.getHtmlLabelName(516179, ThreadVarLanguage.getDefaultLang()));
            }else {
                apidatas.put("api_status",false);
                apidatas.put("msg",sendtype+SystemEnv.getHtmlLabelName(125974, ThreadVarLanguage.getDefaultLang()));
            }
        }else {
            apidatas.put("api_status",false);
            apidatas.put("msg",SystemEnv.getHtmlLabelName(539925, ThreadVarLanguage.getDefaultLang()));
        }
        return apidatas;
    }

    public Map<String, Object> getDocDetail(int docid, int idshareout, String phonenumberGiven, String emailGiven) {
        Map<String,Object> apidatas = new HashMap<String,Object>();
        User user = new User(1);
        boolean canReader = true;
        apidatas.put("canReader",canReader);

        try {
            RecordSet rs = new RecordSet();
            RecordSet rsversion = new RecordSet();
            rs.executeQuery(" SELECT DOWNCOUNT,PHONENUMBER,EMAIL FROM docshareoutrecord WHERE id=? and docid=?",idshareout,docid);
            int downcount = 0;
            if(rs.next()){
                downcount = Util.getIntValue(Util.null2String(rs.getString("DOWNCOUNT")), 0);
            }
            Map<String, Object> contentMap = getContentForShareOut(docid, idshareout, phonenumberGiven, emailGiven,user);
            String doccontent = Util.null2String(contentMap.get("content"));
            int doctype = Util.getIntValue(Util.null2String(contentMap.get("doctype")),1);
            Map<String,Object> docInfo = new HashMap<String,Object>();
            docInfo.put("doccontent",doccontent);  //文档内容
            DocManager docManager = new DocManager();
            ResourceComInfo resourceComInfo = new ResourceComInfo();
            DocImageManager docImageManager = new DocImageManager();
            ImageConvertUtil icu = new ImageConvertUtil();
            Map<String,String> onlineParams = new HashMap<>();
            onlineParams.put("checkPic","1");
            docManager.resetParameter();
            docManager.setId(docid);
            docManager.getDocInfoById();
            docInfo.put("updateUser",resourceComInfo.getLastname(docManager.getDoclastmoduserid() + "")); //最后更新人
            docInfo.put("updateTime",docManager.getDoclastmoddate() + " " + docManager.getDoclastmodtime());  //最后更新时间
            docImageManager.resetParameter();
            docImageManager.setDocid(docid);
            docImageManager.selectDocImageInfo();
            List<Map<String,Object>> docAttrs = new ArrayList<Map<String,Object>>();
            docInfo.put("docAttrs",docAttrs); //附件列表
            boolean ismainFile = false;
            String mainFileid = DocDetailUtil.getMainImagefile(docid+"");
            int accessorycount = docManager.getAccessorycount();
            //获取主附件在附件集合中的位置
            int mainFilePosition = -1;
            int docImageId = 0;

            while (docImageManager.next()) {
                int temdiid = docImageManager.getId();
                if (temdiid == docImageId) {
                    continue;
                }
                docImageId = temdiid;
                Map<String,Object> docAttr = new HashMap<String,Object>();
                docAttrs.add(docAttr);
                String filename = Util.null2String(docImageManager.getImagefilename());
                int filesize = docImageManager.getImageFileSize(Util.getIntValue(docImageManager.getImagefileid()));
                String extName = filename.contains(".")? filename.substring(filename.lastIndexOf(".") + 1) : "";
                Map<String, String> iconMap = DocIconUtil.getDocIconDetail(extName);
                boolean tooLarge = icu.isTooLarge(extName,filesize + "");
                if(tooLarge && "pdf".equals(extName.toLowerCase())){
                    tooLarge = false;
                }
                onlineParams.put("docid",docid+"");
                boolean readOnLine = ImageConvertUtil.readOnlineForMobile(extName,onlineParams);//是否支持在线查看
                if(tooLarge){
                    readOnLine = false;
                }
                if(filename.endsWith(".html")||filename.endsWith(".htm")){
                    RecordSet rs_tmp = new RecordSet();
                    String worflowhtmlSql = " select comefrom from imagefile where imagefileid = ?";
                    rs_tmp.executeQuery(worflowhtmlSql,""+docImageManager.getImagefileid());
                    if(rs_tmp.next()){
                        String htmlcomefrom = Util.null2String(rs_tmp.getString("comefrom"));
                        if("WorkflowToDoc".equals(htmlcomefrom)){
                            readOnLine = true;
                        }
                    }
                }
                String fileSizeStr = "";
                if(filesize / (1024 * 1024) > 0) {
                    fileSizeStr = (filesize / 1024 / 1024) + "M";
                } else if(filesize / 1024 > 0) {
                    fileSizeStr = (filesize / 1024) + "K";
                } else {
                    fileSizeStr = filesize + "B";
                }
                String fileidvalue = Util.null2String(docImageManager.getImagefileid());
                String idsql = "(select max(id) maxid from DocImageFile where imagefileid=" + fileidvalue + ")";
                String sqlversion="select * from DocImageFile where id="+idsql+" order by versionid desc";
                rsversion.executeQuery(sqlversion);
                int versionnum=rsversion.getCounts();
                docAttr.put("tooLarge",tooLarge ? "1" : "0");
                DocSptm docSptm = new DocSptm();
                docAttr.put("imagefileid",docSptm.getEncrpFileid(fileidvalue));
                docAttr.put("versionnum",versionnum);
                docAttr.put("docid",docid+"");
                docAttr.put("filename",StringEscapeUtils.unescapeHtml(filename));
                docAttr.put("ficon",iconMap);
                docAttr.put("fileSizeStr",fileSizeStr);
                docAttr.put("readOnLine",readOnLine ? "1" : "0");
                docAttr.putAll(DocSecretLevelUtil.takeSecretInfobyID(fileidvalue,user));
                ismainFile = mainFileid.equals(fileidvalue);
                if(accessorycount == 1 && readOnLine){
                    ismainFile = true;
                }
                docAttr.put("mainFile",ismainFile?SystemEnv.getHtmlLabelName(514544,user.getLanguage()):"");
                if(SystemDocUtil.canEditForMobile(extName,user)){
                    docAttr.put("canEditAcc",true);
                }
                docAttr.put("ddcode","");
            }
            docInfo.put("docTitle",StringEscapeUtils.unescapeHtml(docManager.getDocsubject())); // 文档标题
            docInfo.put("readCount","0");  //阅读数量
            rs.executeSql("select count(1) num from DocDetailLog where docid="+docid+" and operatetype = 0");
            if(rs.next()){
                docInfo.put("readCount",rs.getString("num"));
            }
            if(downcount>0 || downcount == -1) {
                docInfo.put("candownload",true);
            }else{
                docInfo.put("candownload",false);
            }
            String officeTypesql = "select a.imagefileid,a.imagefilename,a.docfiletype,a.versionId,b.filesize from DocImageFile a,Imagefile b " +
                    " where a.imagefileid=b.imagefileid and a.docid=? and (a.isextfile <> '1' or a.isextfile is null) order by a.versionId desc ";
            RecordSet officeTypeRs = new RecordSet();
            officeTypeRs.executeQuery(officeTypesql,docid);
            String officeImagefileid = "";
            if(officeTypeRs.next()){
                officeImagefileid = Util.null2String(officeTypeRs.getString("imagefileid"));
            }
            docInfo.put("officeImagefileid",officeImagefileid);
            apidatas.put("doctype",doctype);
            apidatas.put("docInfo",docInfo);
            apidatas.put("api_status", true);
        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("api_status", false);
        }
        return apidatas;
    }

    /**
     * 创建外部人员
     * @return
     * @throws Exception
     */
    public Map<String, Object> saveHtmlContent(int docid,String doccontent) throws Exception {
        Map<String,Object> apidatas = new HashMap<String,Object>();
        RecordSet rs = new RecordSet();
        String dbType = rs.getDBType();
        rs.executeSql("select doctype from DOCDETAIL  where ID=" + docid);
        int doctype = 1;
        if (rs.next()) {
            doctype = Util.getIntValue(rs.getString("doctype"), 1);
        }
        if(doctype == 2){
            doccontent="";
        }
        String sql = "";
        if("oracle".equals(dbType) || "mysql".equals(dbType)||"postgresql".equals(dbType)){
            sql = "select c.doccontent,d.docpublishtype from docdetailcontent c,DocDetail d where d.id=c.docid and docid=" + docid;
        }else{
            sql = "select doccontent,docpublishtype from Docdetail where id=" + docid;
        }
        String olddoccontent = "";
        rs.executeQuery(sql);
        if(!rs.next()){
            olddoccontent = "";
        }

        String docpublishtype = rs.getString("docpublishtype");
        olddoccontent = rs.getString("doccontent");
        String docMain = "";
        int tmppos = olddoccontent.indexOf("!@#$%^&*");
        if (tmppos != -1) {
            docMain = olddoccontent.substring(0, tmppos);
        }

        if(doccontent != null && !doccontent.isEmpty()){
            int tmppos2 = doccontent.indexOf("/weaver/weaver.file.FileDownloadForOutDoc?fileid=");
            while (tmppos2 != -1) {
                int startpos = doccontent.indexOf("\"", tmppos2);
                if (startpos >= 0 && startpos >= 0) {
                    String loadStr = doccontent.substring(tmppos2, startpos);
                    String fileStr = loadStr.replace(GCONST.getContextPath()+"/weaver/weaver.file.FileDownloadForOutDoc?fileid=","").replace("/weaver/weaver.file.FileDownloadForOutDoc?fileid=", "");
                    int tmppos3 = fileStr.indexOf("&");
                    fileStr = fileStr.substring(0,tmppos3);
                    String fileid = "";
                    weaver.docs.docs.util.DesUtils des = new weaver.docs.docs.util.DesUtils();
                    fileid = des.decrypt(fileStr);
                    String encodeFileid = DocDownloadCheckUtil.EncodeFileid(fileid, null);
                    doccontent = doccontent.replace(loadStr, "/weaver/weaver.file.FileDownload?fileid=" + encodeFileid);
                    tmppos2 = doccontent.indexOf("/weaver/weaver.file.FileDownloadForOutDoc?fileid=", tmppos2 + 1);
                }
            }
        }

        DocSaveService docSaveService = new DocSaveService();
        doccontent = docSaveService.replaceContent(docid, doccontent, false);
        if ("2".equals(docpublishtype)) {
            doccontent = docMain + "!@#$%^&*"
                    + doccontent;
        }
        RecordSet rsContent = new RecordSet();
        if ("oracle".equals(dbType) || "mysql".equals(dbType)||"postgresql".equals(dbType)) {
            rsContent.executeUpdate("update DocDetailContent set doccontent=? where docid=?", doccontent,docid);

        } else {
            doccontent = doccontent.replace("'", "''");
            rsContent.executeUpdate("update DocDetail set doccontent=? where id=?", doccontent,docid);
        }
        apidatas.put("api_status", true);
        apidatas.put("msg",SystemEnv.getHtmlLabelName( 83551, ThreadVarLanguage.getDefaultLang()));
        return apidatas;
    }
}
