package com.engine.bmj.utils;

import weaver.conn.RecordSet;
import weaver.docs.category.SecCategoryComInfo;
import weaver.docs.docs.*;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.hrm.resource.ResourceComInfo;


public class DocCreateUtil {

    public int createMaterialDoc(String docsubject,String attachfilename,String filepath,long attachlength,int creater,int seccategory,String tempcomids){

        BaseBean bb = new BaseBean();
        int docid = -1;
        try{
            String doccontent = "";
            docid = createDoc(docsubject,doccontent,creater,seccategory,tempcomids);
            if(docid > 0) {
                createImageFile(docid+"",attachfilename,filepath,attachlength,true);
            }
        }catch (Exception e){
            bb.writeLog("e:"+e);
        }

        return docid;
    }

    /**
     * 创建文档
     * @param title 文档标题
     * @param content 文档内容
     * @param creater 创建人
     * @param seccategory 子目录
     * @param tempcomids
     * @return
     * @throws Exception
     */
    public int createDoc(String title,String content,int creater,int seccategory,String tempcomids){
        RecordSet rs = new RecordSet();
        BaseBean bb = new BaseBean();
        try{

            String createdate = TimeUtil.getCurrentDateString();
            String createtime = TimeUtil.getOnlyCurrentTimeString();
            String modifieddate = createdate;
            String modifiedtime = createtime;
            String pubishdate = createdate;
            String publishtime = createtime;

            int docLanguage = 7 ;
            ResourceComInfo r = new ResourceComInfo();
            int departmentid = Integer.parseInt(r.getDepartmentID(creater+""));

            SecCategoryComInfo secCategoryComInfo = new SecCategoryComInfo();

            DocComInfo docComInfo=new DocComInfo();
            DocManager docManager=new DocManager();
            DocViewer docViewer=new DocViewer();

            RecordSet recordSet = new RecordSet();
            int newDocId = docManager.getNextDocId(recordSet);

            docManager.setId(newDocId);
            docManager.setDocsubject(title);
            docManager.setSeccategory(seccategory);
            docManager.setLanguageid(docLanguage);
            docManager.setDocstatus("1");

            docManager.setDoccreaterid(creater);
            docManager.setDocdepartmentid(departmentid);
            docManager.setDocCreaterType("1"); //内部用户
            docManager.setUsertype("1");
            docManager.setOwnerid(creater);
            docManager.setOwnerType("1");
            docManager.setDoclastmoduserid(creater);
            docManager.setDocLastModUserType("1");
            docManager.setDoccreatedate(createdate);
            docManager.setDoccreatetime(createtime);
            docManager.setDoclastmoddate(modifieddate);
            docManager.setDoclastmodtime(modifiedtime);
            docManager.setDocPubDate(pubishdate);
            docManager.setDocPubTime(publishtime);
            docManager.setDoclangurage(docLanguage);
            docManager.setKeyword(title);
            docManager.setIsapprover("0");
            docManager.setDocreplyable("1");
            docManager.setAccessorycount(0);
            docManager.setSecretLevel(3);
            docManager.setOrderable(secCategoryComInfo.getSecOrderable(seccategory)+"");
            docManager.setUserid(1);
            docManager.setIsreply("0");

            DocCoder docCoder = new DocCoder();
            docManager.setDocCode(docCoder.getDocCoder(""+seccategory));
            docManager.setDocEditionId(docManager.getNextEditionId(recordSet));
            docManager.setDocEdition(1);

            docManager.setDoccontent(content);
            docManager.setDocType(1);

            docManager.setDocextendname("html");
            docManager.setDocValidUserType("0");
            docManager.AddDocInfo();

            docComInfo.addDocInfoCache("" + newDocId);

            docViewer.setDocShareByDoc("" + newDocId);
            docManager.AddShareInfo();

            rs.execute("select subcompanyid1 from HrmResource where id="+creater);
            rs.next();
            String subcompanyid1 = com.weaver.general.Util.null2String(rs.getString("subcompanyid1"));

            rs.execute("update docshare set userid="+creater+"  where docid="+newDocId+"  and sharetype in (80,84)");

            String sharesql=" insert into ShareinnerDoc (sourceid,type,content,seclevel,sharelevel,srcfrom,opuser,sharesource,downloadlevel,SECLEVELMAX)" +
                    " values('"+newDocId+"',1,1,0,1,80,"+creater+",0,1,255)";
            rs.execute(sharesql);

            if(!"".equals(subcompanyid1)){
                sharesql="insert into ShareinnerDoc (sourceid,type,content,seclevel,sharelevel,srcfrom,opuser,sharesource,downloadlevel,SECLEVELMAX)" +
                        " values('"+newDocId+"',2,"+subcompanyid1+",0,1,2,"+subcompanyid1+",0,1,255)";
                rs.execute(sharesql);
            }

            if(!"".equals(tempcomids))
            {
                String[] tempcomidArray = tempcomids.split(",");
                for(int i=0;i<tempcomidArray.length;i++)
                {
                    int tempcomid = com.weaver.general.Util.getIntValue(tempcomidArray[i]);
                    if(tempcomid!=0)
                    {
                        sharesql=" insert into ShareinnerDoc (sourceid,type,content,seclevel,sharelevel,srcfrom,opuser,sharesource,downloadlevel,SECLEVELMAX)" +
                                " values('"+newDocId+"',2,"+tempcomid+",1,1,2,"+tempcomid+",0,0,255)";
                        rs.execute(sharesql);
                    }else
                    {
                        sharesql=" insert into ShareinnerDoc (sourceid,type,content,seclevel,sharelevel,srcfrom,opuser,sharesource,downloadlevel,SECLEVELMAX)" +
                                " values('"+newDocId+"',5,1,1,1,1,1,0,0,255)";
                        // bs.writeLog("sharesql:"+sharesql);
                        rs.execute(sharesql);
                    }
                }
            }
            bb.writeLog("newDocId:"+newDocId);
            return newDocId;
        }
        catch(Exception e){
            e.printStackTrace();
            return -1;
        }
    }
    public void createImageFile(String docid,String attachfilename,String filepath,long attachlength,boolean maindoc) {

        BaseBean bb = new BaseBean();
        RecordSet rs = new RecordSet();
        try {
            String doctype = getFileExt(attachfilename);
            String docfiletype = "";
            if (doctype.equalsIgnoreCase("doc")) {
                docfiletype = "3";
            } else if (doctype.equalsIgnoreCase("xls")) {
                docfiletype = "4";
            } else if (doctype.equalsIgnoreCase("ppt")) {
                docfiletype = "5";
            } else if (doctype.equalsIgnoreCase("wps")) {
                docfiletype = "6";
            } else if (doctype.equalsIgnoreCase("docx")) {
                docfiletype = "7";
            } else if (doctype.equalsIgnoreCase("xlsx")) {
                docfiletype = "8";
            } else if (doctype.equalsIgnoreCase("pptx")) {
                docfiletype = "9";
            } else {
                docfiletype = "2";
            }

            String imagefiletype = "";
            if (doctype.equalsIgnoreCase("doc")) {
                imagefiletype = "application/msword";
            } else if (doctype.equalsIgnoreCase("xls")) {
                imagefiletype = "application/vnd.ms-excel";
            } else if (doctype.equalsIgnoreCase("ppt")) {
                imagefiletype = "application/vnd.ms-powerpoint";
            } else if (doctype.equalsIgnoreCase("wps")) {
            } else if (doctype.equalsIgnoreCase("docx")) {
                imagefiletype = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
            } else if (doctype.equalsIgnoreCase("xlsx")) {
                imagefiletype = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            } else if (doctype.equalsIgnoreCase("pptx")) {
                imagefiletype = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
            } else if (doctype.equalsIgnoreCase("pdf")) {
                imagefiletype = "application/octet-stream";
            } else if ("jpg".equals(doctype) || "png".equals(doctype)) {
                imagefiletype = "image/jpeg";
            } else if (doctype.equalsIgnoreCase("zip")) {
                imagefiletype = "application/zip";
            } else {
                imagefiletype = "application/octet-stream";
            }

            ImageFileIdUpdate im = new ImageFileIdUpdate();
            int imagefileid = im.getImageFileNewId();

            String docSet = "";
            String mainimagefile = "null";
            if (maindoc) {
                mainimagefile = "1";
                docSet = ",maindoc=" + imagefileid;
            }

            String sql = " insert into ImageFile (imagefileid,imagefilename,imagefiletype,imagefileused,filerealpath,iszip,isencrypt,fileSize,secretlevel,mainimagefile) " +
                    " values(" + imagefileid + ",'" + attachfilename + "','" + imagefiletype + "',1,'" + filepath + "',0,0,'" + attachlength + "',3," + mainimagefile + ")";
            rs.executeUpdate(sql);

            DocImageManager dm = new DocImageManager();
            VersionIdUpdate versionIdUpdate = new VersionIdUpdate();

            int versionid = versionIdUpdate.getVersionNewId();

            sql = " insert into DocImageFile (id,docid,imagefileid,imagefilename,imagefilewidth,imagefileheight,imagefielsize,docfiletype,versionid)" +
                    " values(" + dm.getNextDocImageFileId() + "," + docid + "," + imagefileid + ",'" + attachfilename + "','0','0','0','" + docfiletype + "'," + versionid + ")";
            rs.executeUpdate(sql);

            sql = " select count(1) as cou from DocImageFile where docid=" + docid;
            rs.execute(sql);
            rs.next();
            int count = com.weaver.general.Util.getIntValue(com.weaver.general.Util.null2String(rs.getString("cou")));

            sql = " update docdetail set accessorycount=" + count + docSet + " where id=" + docid;
            bb.writeLog("sql:" + sql);
            rs.executeUpdate(sql);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 得到文件的扩展名
     *
     * @param file
     *            文件全名
     * @return 文件的扩展名
     */
    public static String getFileExt(String file) {
        if (file == null || file.trim().equals("")) {
            return "";
        } else {
            int idx = file.lastIndexOf(".");
            if (idx == -1) {
                return "";
            } else {
                if (idx + 1 >= file.length()) {
                    return "";
                } else {
                    return file.substring(idx + 1);
                }
            }
        }
    }



}
