package com.api.doc.detail.util;

import com.api.doc.detail.service.DocAccService;
import com.api.doc.search.util.DocSptm;
import com.engine.common.service.HrmCommonService;
import com.engine.common.service.impl.HrmCommonServiceImpl;
import com.engine.doc.util.DocRuleBaseUtil;
import com.wbi.util.Util;
import weaver.conn.RecordSet;
import weaver.docs.category.SecCategoryComInfo;
import weaver.docs.docs.*;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.hrm.User;
import weaver.soa.workflow.request.*;
import weaver.system.SysRemindWorkflow;
import weaver.system.code.CodeBuild;
import weaver.system.code.CoderBean;
import weaver.systeminfo.SystemEnv;

import java.sql.Timestamp;
import java.util.*;

/**
 * @Description TODO
 * @Author b-r
 * @Date 2023/5/15 9:34
 * @Version 1.0
 **/
public class DocWkUtil extends BaseBean {
    public RecordSet rs = new RecordSet();

    public boolean isWKSec(int docid){
        rs.executeQuery("select * from uf_docwksetting");
        if(rs.next()) {
            String wkId = Util.null2String(rs.getString("wkml"));

            writeLog("DocWkUtil---------->isWKSec----->wkId:" + wkId);
            String secids = getAllChildsSql(wkId, "docseccategory");
            writeLog("DocWkUtil---------->isWKSec----->所有的下级目录secids:" + secids);
            String strSql = "select seccategory from docdetail where id =" + docid;
            rs.executeQuery(strSql);
            if (rs.next()) {
                String secid = Util.null2String(rs.getString(1));
                if (("," + secids + "," + wkId + ",").contains("," + secid + ",")) {
                    return true;
                }
            }
        }
        return false;
    }
    /**
    * @Desc  判断文件是否可以被打开
     * 1.借阅到期后，借阅人不可打开
     * 2.被回收后，下发人员不可打开
     * 3.变更后，原下发人员不可打开，新下发人员才可打开。
     * 4.文件到期，文件不可打开
    * @Author b-r
    * @Date 2023/5/15 9:35
    **/
    public String judgeOpen(int docid, User user){
        rs.executeQuery("select * from uf_docwksetting");
        if(rs.next()) {
            String wkOpen = Util.null2String(rs.getString("wkopen"));
            writeLog("DocWkUtil---------->judgeOpen-------->wkOpen:" + wkOpen);
            if (!"1".equals(wkOpen)) {
                return "";
            }

            String wkId = Util.null2String(rs.getString("wkml"));

            writeLog("DocWkUtil---------->judgeOpen----->wkId:" + wkId);
            String secids = getAllChildsSql(wkId, "docseccategory");

            String strSql = "select seccategory from docdetail where id =" + docid;
            rs.executeQuery(strSql);
            if (rs.next()) {
                String secid = Util.null2String(rs.getString(1));
                if((","+secids+",").contains(","+secid+",")) {
                    writeLog("DocWkUtil---------->judgeOpen-------->docid:" + docid + "----->user:" + user.getUID());
                    /**文件走回收流程 || 文件到期自动回收  直接返回*/
//                    rs.executeQuery("select * from docdetail where id=? and wkstatus ='5' ", docid);
//                    if (rs.next()) {
//                        writeLog("DocWkUtil---------->judgeOpen-------->回收542993");
//                        return "542993";
//                    }

                    /**文件变更*/
                    rs.executeQuery("select * from uf_docwkshare where docid=? and type=? order by id desc", docid, "3");
                    if (rs.next()) {
                        String sharevalue = Util.null2String(rs.getString("sharevalue"));
                        writeLog("DocWkUtil---------->judgeOpen-------->变更--->sharevalue:"+sharevalue);
                        boolean share = judgeShare(sharevalue, docid, user);
                        if (!share) {
                            //变更后没有权限
                            writeLog("DocWkUtil---------->judgeOpen-------->变更后没有权限...");
                            /**借阅到期*/
                            rs.executeQuery("select * from uf_docwkBorrowing where docid =? and userid=?", docid, user.getUID());
                            if (rs.next()) {
                                writeLog("DocWkUtil---------->judgeOpen-------->有借阅");
                                String status = Util.null2String(rs.getString("status"));
                                if ("1".equals(status)) {
                                    writeLog("DocWkUtil---------->judgeOpen-------->借阅到期...");
                                    return "542992";
                                } else {
                                    return "";
                                }
                            }
                            return "542994";
                        }
                    } else {
                        writeLog("DocWkUtil---------->judgeOpen-------->借阅");
                        /**借阅到期*/
                        rs.executeQuery("select * from uf_docwkBorrowing where docid=? and userid=?", docid, user.getUID());
                        if (rs.next()) {
                            writeLog("DocWkUtil---------->judgeOpen-------->有借阅");
                            String status = Util.null2String(rs.getString("status"));
                            if ("1".equals(status)) {
                                writeLog("DocWkUtil---------->judgeOpen-------->借阅到期...");
                                return "542992";
                            } else {
                                return "";
                            }
                        }
                    }
                }
            }
        }
        return "";
    }

    /**
     * @Desc  删除文控赋权
     * @Author b-r
     * @Date 2023/4/25 18:02
     **/
    public void deleteShareFromWf(int docid){
        RecordSet rs = new RecordSet();
        rs.executeUpdate("delete from docshare where docid=? and sharelevel=1 and sharesource=6 and (issecdefaultshare ='' or issecdefaultshare is null)",docid);
        try{
            DocViewer dv = new DocViewer();
            dv.setDocShareByDoc(docid + "");
        }catch(Exception e){
            writeLog("WKDocDealShareAction-------->deleteShareFromWf----->同步共享详情表异常:"+e.getMessage());
        }
    }
    /**
     * @Desc  添加权限
     * @Author b-r
     * @Date 2023/4/25 17:49
     **/
    public void addShare(int docid,String shareValue,String _type){
        shareValue = weaver.general.Util.null2String(shareValue).trim();

        //将文档id和条件值记录到表中
        RecordSet rs = new RecordSet();
        rs.executeUpdate("insert into uf_docwkshare(docid,sharevalue,type) values(?,?,?)",docid,shareValue,_type);

        dealShare(shareValue,docid);
    }

    public void dealShare(String shareValue,int docid){
        if (!"".equals(shareValue)) {
            List<String> resourceConditions = weaver.general.Util.splitString2List(shareValue, "~");
            for (String conditionItem : resourceConditions) {
                String[] item = weaver.general.Util.splitString(conditionItem, "_");
                int type = -1;
                int objid = -1;
                int roleLevel = -1;
                if (item.length > 2) {
                    type = weaver.general.Util.getIntValue(item[0]);
                    objid = weaver.general.Util.getIntValue(item[1]);
                    roleLevel = weaver.general.Util.getIntValue(item[2]);
                }
                int seclevel1 = 0;
                int seclevel2 = 100;

                int joblevel = -1;
                int jobfield = -1;
                if (item.length > 3) {
                    String seclevelvalue = weaver.general.Util.null2String(item[3]);
                    if (seclevelvalue.indexOf("|@|") > -1) {
                        String[] arraylevel = seclevelvalue.split("\\|@\\|");
                        if (type == 2 || type == 3 || type == 4 || type == 5) {
                            seclevel1 = weaver.general.Util.getIntValue(arraylevel[0]);
                            seclevel2 = weaver.general.Util.getIntValue(arraylevel[1]);
                        } else if (type == 6) {
                            joblevel = weaver.general.Util.getIntValue(arraylevel[0]);
                            jobfield = weaver.general.Util.getIntValue(arraylevel[1]);
                        }
                    }
                }
                int download = 0;
                if(item.length > 4){
                    download = weaver.general.Util.getIntValue(item[4]);
                }

                if(type == 1){  //人员
                    addShareForUser(docid,objid,1,download);
                }else if(type == 2){  //分部
                    addShareForSubCompany(docid,objid,1,seclevel1,seclevel2,download);
                }else if(type == 3){   //部门
                    addShareForDepartment(docid,objid,1,seclevel1,seclevel2,download);
                }else if(type == 4){   //角色
                    addShareForRole(docid,objid,1,roleLevel,seclevel1,seclevel2,download);
                }else if(type == 5){   //所有人
                    addShareForAll(docid,1,seclevel1,seclevel2,download);
                }else if(type == 6){   //岗位
                    addShareForPost(docid,objid,1,joblevel,jobfield,download);
                }
            }
            try{
                DocViewer dv = new DocViewer();
                dv.setDocShareByDoc(docid + "");
            }catch(Exception e){
                writeLog("WKDocDealShareAction-------->addShare----->同步共享详情表异常:"+e.getMessage());
            }
        }
    }

    public boolean judgeShare(String shareValue,int docid,User user){
        boolean haveShare = false;
        if (!"".equals(shareValue)) {
            List<String> resourceConditions = weaver.general.Util.splitString2List(shareValue, "~");
            for (String conditionItem : resourceConditions) {
                String[] item = weaver.general.Util.splitString(conditionItem, "_");
                int type = -1;
                int objid = -1;
                int roleLevel = -1;
                if (item.length > 2) {
                    type = weaver.general.Util.getIntValue(item[0]);
                    objid = weaver.general.Util.getIntValue(item[1]);
                    roleLevel = weaver.general.Util.getIntValue(item[2]);
                }
                int seclevel1 = 0;
                int seclevel2 = 100;

                int joblevel = -1;
                int jobfield = -1;
                if (item.length > 3) {
                    String seclevelvalue = weaver.general.Util.null2String(item[3]);
                    if (seclevelvalue.indexOf("|@|") > -1) {
                        String[] arraylevel = seclevelvalue.split("\\|@\\|");
                        if (type == 2 || type == 3 || type == 4 || type == 5) {
                            seclevel1 = weaver.general.Util.getIntValue(arraylevel[0]);
                            seclevel2 = weaver.general.Util.getIntValue(arraylevel[1]);
                        } else if (type == 6) {
                            joblevel = weaver.general.Util.getIntValue(arraylevel[0]);
                            jobfield = weaver.general.Util.getIntValue(arraylevel[1]);
                        }
                    }
                }
                int download = 0;
                if(item.length > 4){
                    download = weaver.general.Util.getIntValue(item[4]);
                }

                if(type == 1){  //人员
                    objid = Util.getIntValue(user.getUID());
                    haveShare = judgeShareForUser(docid,objid,1,download);
                }else if(type == 2){  //分部
                    objid = Util.getIntValue(user.getUserSubCompany1());
                    int secLevel = Util.getIntValue(user.getSeclevel());
                    if(secLevel < seclevel1 || secLevel > seclevel2){
                        continue;   //安全级别小于最小，大于最大，继续下一个条件
                    }
                    haveShare = judgeShareForSubCompany(docid,objid,1,seclevel1,seclevel2,download);
                }else if(type == 3){   //部门
                    objid = Util.getIntValue(user.getUserDepartment());
                    int secLevel = Util.getIntValue(user.getSeclevel());
                    if(secLevel < seclevel1 || secLevel > seclevel2){
                        continue;   //安全级别小于最小，大于最大，继续下一个条件
                    }
                    haveShare = judgeShareForDepartment(docid,objid,1,seclevel1,seclevel2,download);
                }else if(type == 4){   //角色
                    int secLevel = Util.getIntValue(user.getSeclevel());
                    if(secLevel < seclevel1 || secLevel > seclevel2){
                        continue;   //安全级别小于最小，大于最大，继续下一个条件
                    }
                    HrmCommonService hrmCommonService = new HrmCommonServiceImpl();
                    List<Object> roleInfos = hrmCommonService.getRoleInfo(user.getUID());
                    for(Object ro : roleInfos) {
                        Map<String, Object> roleInfo  = (Map<String, Object>) ro;
                        int roleid = Util.getIntValue(Util.null2String(roleInfo.get("roleid")));
                        int rolelevel = Util.getIntValue(Util.null2String(roleInfo.get("rolelevel")));
                        if(roleid == objid && rolelevel == roleLevel){
                            haveShare = judgeShareForRole(docid,objid,1,roleLevel,seclevel1,seclevel2,download);
                        }
                    }

                }else if(type == 5){   //所有人
                    int secLevel = Util.getIntValue(user.getSeclevel());
                    if(secLevel < seclevel1 || secLevel > seclevel2){
                        continue;   //安全级别小于最小，大于最大，继续下一个条件
                    }
                    haveShare = judgeShareForAll(docid,1,seclevel1,seclevel2,download);
                }else if(type == 6){   //岗位

                    objid = Util.getIntValue(user.getJobtitle());
                    if(joblevel == 2) {
                        jobfield = Util.getIntValue(user.getUserSubCompany1());
                    }else {
                        jobfield = Util.getIntValue(user.getUserDepartment());
                    }
                    haveShare = judgeShareForPost(docid,objid,1,joblevel,jobfield,download);
                }

                if (haveShare){
                    break;
                }
            }
        }
        return haveShare;
    }

    /**
     * 人力资源
     * @params 	user-当前用户
     * 			docid-文档id
     * 			userids-用户id集合，逗号隔开（被赋予权限对象）
     *			seclevel-权限（1-查看；2-编辑，3-完全控制）
     *			download-是否可下载
     *		    sharesource	 6 文控
     * */
    public void addShareForUser(int docid, int userid, int sharelevel, int download){
        RecordSet rs = new RecordSet();
        String sql = "insert into DocShare(docid,sharetype,sharelevel,userid,downloadlevel,sharesource) values("+
                docid+","+1+","+sharelevel+","+userid+","+download+",6)";

        rs.execute(sql);
    }

    public boolean judgeShareForUser(int docid, int userid, int sharelevel, int download){
        RecordSet rs = new RecordSet();
        String sql = "select * from DocShare where docid=? and sharetype=1 and sharelevel=? and userid=? and downloadlevel=? and sharesource=1";
        rs.executeQuery(sql,docid,sharelevel,userid,download);
        if(rs.next()){
            return true;
        }
        return false;
    }
    /**
     * 分部
     * @params 	user-当前用户
     * 			docid-文档id
     * 			companyids-分部id集合，逗号隔开（被赋予权限对象）
     *			seclevel-权限（1-查看；2-编辑，3-完全控制）
     *			fromlevel-最低安全级别
     *			tolevel-最高安全级别
     *			containsSub-是否含下级
     *			download-是否可下载
     * */
    public void addShareForSubCompany(int docid,int companyid,int sharelevel,int fromlevel,int tolevel,int download){
        RecordSet rs = new RecordSet();
        String sql = "insert into DocShare(docid,sharetype,seclevel,sharelevel,subcompanyid,downloadlevel,seclevelmax,sharesource) values("+
                docid+","+2+","+fromlevel+","+sharelevel+"," + companyid + ","+download+","+tolevel+",6)";
        rs.execute(sql);

    }

    public boolean judgeShareForSubCompany(int docid,int companyid,int sharelevel,int fromlevel,int tolevel,int download){
        RecordSet rs = new RecordSet();
        String sql = "select * from  DocShare where docid=? and sharetype=2 and seclevel=? and sharelevel=? and subcompanyid=? and downloadlevel=? and seclevelmax=? and sharesource=1)";
        rs.executeQuery(sql,docid,fromlevel,sharelevel,companyid,download,tolevel);
        if(rs.next()){
            return true;
        }
        return false;
    }
    /**
     * 部门
     * @author wangqs
     * @params 	user-当前用户
     * 			docid-文档id
     * 			departmentids-部门id集合，逗号隔开（被赋予权限对象）
     *			seclevel-权限（1-查看；2-编辑，3-完全控制）
     *			fromlevel-最低安全级别
     *			tolevel-最高安全级别
     *			containsSub-是否含下级
     *			download-是否可下载
     * */
    public void addShareForDepartment(int docid,int departmentid,int sharelevel,int fromlevel,int tolevel,int download){
        RecordSet rs = new RecordSet();
        String sql = "insert into DocShare(docid,sharetype,seclevel,sharelevel,departmentid,downloadlevel,seclevelmax,sharesource) values("+
                docid+","+3+","+fromlevel+","+sharelevel+"," + departmentid + ","+download+","+tolevel+",6)";
        rs.execute(sql);
    }

    public boolean judgeShareForDepartment(int docid,int departmentid,int sharelevel,int fromlevel,int tolevel,int download){
        RecordSet rs = new RecordSet();
        String sql = "select * from DocShare where docid=? and sharetype=3 and seclevel=? and sharelevel=? and departmentid=? and  downloadlevel=? and seclevelmax=? and sharesource=1";
        rs.executeQuery(sql,docid,fromlevel,sharelevel,departmentid,download,tolevel);
        if(rs.next()){
            return true;
        }
        return false;
    }
    /**
     * 岗位
     * @params 	user-当前用户
     * 			docid-文档id
     * 			postids-岗位id集合，逗号隔开（被赋予权限对象）
     *			seclevel-权限（1-查看；2-编辑，3-完全控制）
     *			level-岗位级别（2-总部，1-指定分部，0-指定部门）
     *			tagetids-指定分部（部门）id集合
     *			download-是否可下载
     * */
    public void addShareForPost(int docid,int jobid,int sharelevel,int level,int targetid,int download){
        RecordSet rs = new RecordSet();
        String columns = "docid,sharetype,sharelevel,downloadlevel,jobids,joblevel,sharesource";
        String values = docid+","+10+","+sharelevel+","+download+",'"+jobid+"','" + level + "'," + 6;

        if(level == 1){
            columns += ",jobsubcompany";
        }else if(level == 0){
            columns += ",jobdepartment";
        }

        if(level == 1){
            rs.execute("insert into DocShare(" + columns + ") values(" + values + ")");
        }else{
            rs.execute("insert into DocShare(" + columns + ") values(" + values + ",'" + targetid + "')");
        }
    }

    public boolean judgeShareForPost(int docid,int jobid,int sharelevel,int level,int targetid,int download){
        RecordSet rs = new RecordSet();
        String whereSql = " where docid=? and sharetype=10 and sharelevel=? and downloadlevel=? and jobids=? and joblevel=? and sharesource=1";

        if(level == 2){
            whereSql += " and jobsubcompany=?";
        }else if(level == 3){
            whereSql += " and jobdepartment=?";
        }

        if(level == 1){
            rs.executeQuery("select * from  DocShare "+whereSql,docid,sharelevel,download,jobid,level);
        }else{
            rs.executeQuery("select * from  DocShare "+whereSql,docid,sharelevel,download,jobid,level,targetid);
        }
        if(rs.next()){
            return true;
        }
        return false;
    }

    /**
     * 角色
     * @params 	user-当前用户
     * 			docid-文档id
     * 			roleids-角色id集合，逗号隔开（被赋予权限对象）
     *			seclevel-权限（1-查看；2-编辑，3-完全控制）
     *			level-级别（2-总部，1-分部，0-部门）
     *			fromlevel-最低安全级别
     *			tolevel-最高安全级别
     *			download-是否可下载
     * */
    public void addShareForRole(int docid,int roleid,int sharelevel,int level,int fromlevel,int tolevel,int download){
        RecordSet rs = new RecordSet();
        String sql = "insert into DocShare(docid,sharetype,seclevel,sharelevel,roleid,downloadlevel,seclevelmax,rolelevel,sharesource) values("+
                docid+","+4+","+fromlevel+","+sharelevel+"," + roleid + ","+download+","+tolevel+"," + level + ",6)";
        rs.execute(sql);
    }

    public boolean judgeShareForRole(int docid,int roleid,int sharelevel,int level,int fromlevel,int tolevel,int download){
        RecordSet rs = new RecordSet();
        String sql = "select * from DocShare where docid=? and sharetype=4 and seclevel=? and sharelevel=? and roleid=? and downloadlevel=? and seclevelmax=? and rolelevel=? and sharesource=1";
        rs.executeQuery(sql,docid,fromlevel,sharelevel,roleid,download,tolevel,level);
        if(rs.next()){
            return true;
        }
        return false;
    }


    /**
     * 所有人
     * @params 	user-当前用户
     * 			docid-文档id
     *			seclevel-权限（1-查看；2-编辑，3-完全控制）
     *			fromlevel-最低安全级别
     *			tolevel-最高安全级别
     *			download-是否可下载
     * */
    public void addShareForAll(int docid,int sharelevel,int fromlevel,int tolevel,int download){
        RecordSet rs = new RecordSet();
        String sql = "insert into DocShare(docid,sharetype,seclevel,sharelevel,downloadlevel,seclevelmax,foralluser,sharesource) values("+
                docid+","+5+","+fromlevel+","+sharelevel+","+download+","+tolevel+",1,6)";
        rs.execute(sql);
    }

    public boolean judgeShareForAll(int docid,int sharelevel,int fromlevel,int tolevel,int download){
        RecordSet rs = new RecordSet();
        String sql = "select * from DocShare where docid=? and sharetype=5 and seclevel=? and sharelevel=? and downloadlevel=? and seclevelmax=? and  foralluser=1 and sharesource=1";
        rs.executeQuery(sql,docid,fromlevel,sharelevel,download,tolevel);
        if(rs.next()){
            return true;
        }
        return false;
    }

    /**
    * @Desc  获取当前节点的所有下级节点，包含当前id
    * @Author b-r
    * @Date 2023/5/16 13:46
    **/
    public String getAllChildsSql(String ids,String tableName){
        String[] idList = ids.split(",");
        RecordSet rs = new RecordSet();
        String sql = "select id from "+tableName+" start with parentid = ? connect by prior id = parentid";
        if("sqlserver".equals(rs.getDBType())){
            sql = "with cte as " +
                    "(" +
                    "select * from "+tableName+" where parentid = ? " +
                    "union all " +
                    "select  a.* from "+tableName+" as a,cte as b where a.parentid = b.id " +
                    ")" +
                    "select id from cte ";
        }else if("mysql".equals(rs.getDBType())){
            sql = " select DISTINCT t.id from ("+
                    " select @id idlist, @lv:=@lv+1 lv,"+
                    " (select @id:=group_concat(id separator ',') from "+tableName+" where find_in_set(parentid,@id)) sub "+
                    " from "+tableName+" ,(select @id:= ? ,@lv:=0) vars "+
                    " where @id is not null) tl, "+tableName+" t "+
                    " where find_in_set(t.id,tl.idlist) "+
                    " order by lv asc";
        }else if("postgresql".equals(rs.getDBType())) {
            sql = "with RECURSIVE  cte as " +
                    "(" +
                    "select * from "+tableName+" where parentid = ? " +
                    "union all " +
                    "select  a.* from "+tableName+" as a,cte as b where a.parentid = b.id " +
                    ")" +
                    "select id from cte ";
        }
        if(idList.length>0){
            ids = ids+",";
        }
        for(int i=0,j=idList.length;i<j;i++){
            rs.executeQuery(sql,idList[i]);
            while(rs.next()){
                String idChild = rs.getString("id");
                ids = ids+idChild+",";
            }
            if(i==j-1){
                ids  = ids.substring(0,ids.length()-1);
            }
        }
        return ids;
    }

    /** 本来是想 在判断借阅是否可以打开时，获取该文档的所有版本是否在借阅表中，但是还牵扯 新版本是否是借阅有效期内生成的。
     * 所以采用 生成新版本时，将新文档id插入到借阅表中
    * @Desc
    * @Author b-r
    * @Date 2023/5/17 9:56
    **/
    public void wkDocNewEdition(int oldId,int newId){
        writeLog("DocWkUtil----->wkDocNewEdition---->oldId:"+oldId+"---->newId:"+newId);
        rs.executeQuery("select * from uf_docwkBorrowing where docid =? and status ='0' ",oldId);  //获取旧文档所有没有到期的
        List<Map<String, Object>> list = new ArrayList<>();
        while (rs.next()){
            Map<String, Object> map = new HashMap<>();
            int userid = Util.getIntValue(rs.getString("userid"));
            String invalidate = Util.null2String(rs.getString("invalidate"));

            map.put("userid",userid);
            map.put("invalidate",invalidate);
            list.add(map);
        }
        for (Map<String, Object> map : list) {
            int userid = Util.getIntValue(Util.null2String(map.get("userid")));
            String invalidate = Util.null2String(map.get("invalidate"));
            rs.executeUpdate("insert into uf_docwkBorrowing(invalidate,docid,userid,status) values(?,?,?,'0')",invalidate,newId,userid);
        }
    }

    /**设置 关联文档的主文档为文件文稿*/
    public void setMainDoc(RequestInfo requestInfo,String _glwd,int wd){
        writeLog("DocWkUtil---------->setMainDoc------->_glwd:"+_glwd+"---->wd:"+wd);
        DetailTableInfo detailTableInfo = requestInfo.getDetailTableInfo();
        DetailTable[] detailTables = detailTableInfo.getDetailTable();
        if(detailTables.length == 0){
            return;
        }
        writeLog("DocWkUtil---------->获取明细表");
        Map<String, Object> wkSetting = getWkSetting();
        int glIndex = Util.getIntValue(Util.null2String(wkSetting.get("glwd")),1);
        DetailTable detailTable = detailTableInfo.getDetailTable(glIndex-1);  //默认第一个明细表，使用索引，0代表第一个
        Row[] row = detailTable.getRow();
        Set<String> set = new HashSet<>();

        String glwd = "";
        for (Row r : row) {
            Cell[] cell = r.getCell();
            for (Cell c : cell) {
                String name = Util.null2String(c.getName());
                if (name.equalsIgnoreCase(_glwd)) {
                    glwd = Util.null2String(c.getValue());  //关联的文档id
                    set.add(glwd);
                }
            }
        }
        writeLog("DocWkUtil---------->关联的文档ids："+set.toString());
        if(set.size() > 0) {
            RecordSet rs = new RecordSet();
            rs.executeUpdate("update docdetail set maindoc=? where id in (" + String.join(",", set) + ")", wd);
        }
    }

    /**获取文控设置*/
    public Map<String,Object> getWkSetting(){
        rs.executeQuery("select * from uf_docwksetting");
        Map<String, Object> map = new HashMap<>();
        if(rs.next()){
            map.put("glwd",Util.getIntValue(rs.getString("glwd"),1));  //关联文档
            map.put("jywd",Util.getIntValue(rs.getString("jywd"),1));  //借阅文档
        }
        return map;
    }

    /**
    * @Desc  生成word文件的新版本
    * @Author b-r
    * @Date 2023/6/29 14:10
    **/
    public Map<String,Object> getNewDoc(User user,Map<String,String> params){
        int oldDocid = Util.getIntValue(params.get("id"));
        int wfid = Util.getIntValue(params.get("wfid"));
        int uploadId = Util.getIntValue(params.get("uploadId"),-1);
        String isExtFile = Util.null2String(params.get("isExtFile"),"0");
        Map<String, Object> map = new HashMap<>();
        DocComInfo dci = new DocComInfo();
        //根据流程路径id和文档id判断 是否已生成了新版本
//        rs.executeQuery("select newid from uf_wkwfdoc where wfid=? and docid=?",wfid,oldDocid);
//        if(rs.next()) {
//            int newId = Util.getIntValue(rs.getString(1));
//            String docName = dci.getDocname(newId + "");
//            map.put("id", newId);
//            map.put("name", docName);
//            return map;
//        }else {
        rs.executeUpdate("delete from uf_wkwfdoc where wfid=? and docid=?",wfid,oldDocid);
            DocAccService accService = new DocAccService();
            rs.executeQuery("select d.docstatus,d.seccategory,d.docEditionId,d.docEdition,d.docdepartmentid,d.ishistory," +
                    "d.doccreaterid,d.docsubject,d.versionruleid from DocDetail d where d.id=" + oldDocid);
            if (rs.next()) {
                int secid = Util.getIntValue(rs.getInt("seccategory"));
                String docsubject = Util.null2String(rs.getString("docsubject"));
                int versionruleid = Util.getIntValue(rs.getString("versionruleid"));
                DocManager dm = new DocManager();
                DocIdUpdate docIdUpdate = new DocIdUpdate();
                int docid = docIdUpdate.getDocNewId();

                String fileid = "";
                rs.executeQuery("select imagefileid from docimagefile where (isextfile = '0' or isextfile ='' or isextfile is null) and docid="+docid + " order by versionid desc");
                if(rs.next()){
                    fileid = Util.null2String(rs.getString(1));
                }
                dm.resetParameter();
                dm.setId(docid);
                dm.setSeccategory(secid);
                //dm.setDocEdition(docEdition);
                //dm.setDocEditionId(docEditionId);
                dm.setDocsubject(docsubject);
                dm.setUserid(user.getUID());
                dm.setUsertype(user.getLogintype());
                dm.setDoccreaterid(user.getUID());
                dm.setDocCreaterType(user.getLogintype());
                //dm.setDocstatus("0");  //置为草稿
                try {
                    dm.addNewDocForEdition(oldDocid, fileid);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if(uploadId > 0){
                    String where = " isextfile = 1";
                    if("0".equals(isExtFile)){
                        where = " (isextfile = '0' or isextfile ='' or isextfile is null)";
                    }
                    rs.executeQuery("select imagefileid from docimagefile where "+where+" and docid=? order by versionid desc",uploadId);
                    if(rs.next()){
                        int uploadFileid = Util.getIntValue(rs.getString(1));
                        accService.buildRelForDoc(uploadFileid, docid, "1".equals(isExtFile));
                    }
                }else {

                //为新文档绑定原word
                rs.executeQuery("select wordid from uf_wkwordpdf where docid=?",oldDocid);
                if(rs.next()){
                    int wordid = Util.getIntValue(rs.getString(1));
                    accService.buildRelForDoc(wordid, docid, false);
                }
                }
                String date = "'" + TimeUtil.getCurrentDateString() + "'";
                String time = "'" + TimeUtil.getOnlyCurrentTimeString() + "'";
                rs.executeUpdate("update docdetail set DOCLASTMODUSERID=" + user.getUID() + ",DOCLASTMODUSERTYPE=" + user.getLogintype() + ",DOCLASTMODDATE=" + date + "," +
                        "DOCLASTMODTIME=" + time + ",docstatus=0,doceditionid=-1,seccategory="+secid+",versionruleid="+versionruleid+" where id=?", docid);

//                DocWkUtil dwu = new DocWkUtil();
//                String wkStatus = dwu.getWKStatus();
//                rs.executeUpdate("update cus_fielddata set "+wkStatus+"=0 where id ="+docid);  //wjzt-文件状态
//                rs.executeUpdate("update uf_wjxxztz set wjzt=0 where wjgj="+docid);  //wjgj-文件文稿

                rs.executeUpdate("insert into uf_wkwfdoc(wfid,docid,newid) values(?,?,?)",wfid,oldDocid,docid);
                map.put("id", docid);
                map.put("name", docsubject);
            }
            return map;
//        }
    }

    /**
    * @Desc  文控编号，根据规则库走一套流水
    * @Author b-r
    * @Date 2023/6/30 18:19
    **/
    public String getWKCoder(String secId, int docid, int codeId, User user,Property[] property) {
        DocRuleBaseUtil dbu = new DocRuleBaseUtil();
        String docCoder = "";
        SecCategoryComInfo scc = new SecCategoryComInfo();
        RecordSet rs = new RecordSet();
        int subId = 0,mainId = 0;

        Date newdate = new Date() ;
        long datetime = newdate.getTime() ;
        Timestamp timestamp = new Timestamp(datetime) ;
        String year = (timestamp.toString()).substring(0,4);
        String month = (timestamp.toString()).substring(5,7);
        String day = (timestamp.toString()).substring(8,10);

        List<Object> memberList = new ArrayList<>();
        rs.executeQuery("select showname,showtype,value from docruledetail  where ruleid=? order by codeorder asc",codeId);
        while (rs.next()){
            String[] tArrays = new String[3];
            tArrays[0]= weaver.general.Util.null2String(rs.getString("showname"));
            tArrays[1]= weaver.general.Util.null2String(rs.getString("value"));
            tArrays[2]= weaver.general.Util.null2String(rs.getString("showtype"));
            memberList.add(tArrays);
        }

        boolean letter = false;
        int digit = 4;
        String letterType = "1";
        rs.executeQuery("select showname,showtype,value from docruledetail  where ruleid=? and showtype=8 order by codeorder asc",codeId);
        if (rs.next()){
            String value = weaver.general.Util.null2String(rs.getString("value"));
            value = value.replaceAll("\\[","").replaceAll("]","").replaceAll("\"","");
            String[] split = value.split(",");
            letter = "1".equals(split[0]);
            if(split.length == 2){
                if(letter) {
                    letterType = Util.null2String(split[1], "1");
                }else {
                    digit = Util.getIntValue(split[1], 4);
                }
            }
        }

        for (int i=0;i<memberList.size();i++){
            String[] members = (String[])memberList.get(i);
            String text = members[0];
            String value = members[1];
            String type = members[2];

            if("5".equals(type)){  //字符串
                docCoder += value;
            }else if("6".equals(type)){  //目录分类，也就是目录名称
                docCoder += scc.getSecCategoryname(secId);
            }else if("7".equals(type)){   //创建人机构  0-部门  1-分部
                docCoder += dbu.getOrgValue(user,value);
            }else if("8".equals(type)){   //流水类别
                int sequence = 0;
                rs.executeSql("select * from docrulebase where id="+codeId);
                while(rs.next()){
                    sequence = Util.getIntValue(rs.getString("sequence"),0);
                    sequence++;
                }
                rs.executeSql("update docrulebase set sequence="+sequence+" where id="+codeId);
                if(letter){
                    if("1".equals(letterType)) {
                        docCoder += dbu.numberToLetter(sequence);
                    }else {
                        docCoder += dbu.numberToSmallLetter(sequence);
                    }
                }else {
                    if (weaver.general.Util.getIntValue(digit) <= ("" + sequence).length()) {
                        docCoder += sequence;   //流水号的长度 超过 流水号位数，继续升
                    } else {
                        for (int j = 0; j < (weaver.general.Util.getIntValue(digit) - ("" + sequence).length()); j++) {
                            docCoder += "0";   //不超过，补0
                        }
                        docCoder += sequence;
                    }
                }

            }else if("9".equals(type)){    //自定义字段  value-数据库名
                if(docid > 0) {
                    docCoder += dbu.getCusValue(value, docid);
                }else {
                    if(property != null) {
                        for (Property pro : property) {
                            if (value.equalsIgnoreCase(pro.getName())) {
                                docCoder += Util.null2String(pro.getValue());
                                break;
                            }
                        }
                    }
                }
            }else if("10".equals(type)){   //表单字段
                if(property != null) {
                    for (Property pro : property) {
                        if (value.equalsIgnoreCase(pro.getName())) {
                            docCoder += Util.null2String(pro.getValue());
                            break;
                        }
                    }
                }
            }else if ("18807".equals(text)){//编码前缀
                docCoder += value;
            }else if ("81537".equals(text)){//顶级目录编码
                if ("1".equals(value)) {
                    String mainCategoryCoder = "";
                    mainId = weaver.general.Util.getIntValue(scc.getTopId(secId),0);
                    if(mainId<=0)continue;
                    rs.executeSql("select coder from DocSecCategory where id="+mainId);
                    while(rs.next()){
                        mainCategoryCoder = weaver.general.Util.null2String(rs.getString("coder"));
                    }
                    docCoder += mainCategoryCoder;
                }
            }else if ("81538".equals(text)){//上级目录编码
                if ("1".equals(value)) {
                    String subCategoryCoder = "";
                    subId = weaver.general.Util.getIntValue(scc.getParentId(secId),0);
                    if(subId<=0)continue;
                    rs.executeSql("select coder from DocSecCategory where id="+subId);
                    while(rs.next()){
                        subCategoryCoder = weaver.general.Util.null2String(rs.getString("coder"));
                    }
                    docCoder += subCategoryCoder;
                }
            }else if ("81539".equals(text)){//本级目录编码
                if ("1".equals(value)) {
                    String secCategoryCoder = "";
                    rs.executeSql("select coder from DocSecCategory where id="+secId);
                    while(rs.next()){
                        secCategoryCoder = weaver.general.Util.null2String(rs.getString("coder"));
                    }
                    docCoder += secCategoryCoder;
                }
            }else if ("81540".equals(text)){//所有上级目录编码
                if ("1".equals(value)) {
                    String secCategoryCoder = "";
                    secCategoryCoder = scc.getAllCoder(secId);
                    docCoder += secCategoryCoder;
                }
            }else if ("445".equals(text)){//年
                if ("1".equals(value)) {
                    docCoder += year;
                }
            }else if ("6076".equals(text)){//月
                if ("1".equals(value)) {
                    docCoder += month;
                }
            }else if ("16889".equals(text)){//日
                if ("1".equals(value)) {
                    docCoder += day;
                }
            }
        }
        return docCoder;
    }

    /** 更新表单字段
     * @Desc
     * @Author b-r
     * @Date 2023/6/21 11:30
     **/
    public void updateFieldValue(int requestId, String fields,int workflowId) {
        writeLog("DocWkUtil---------->updateFieldValue--->requestId:"+requestId+"---->fields:"+fields+"---->workflowId:"+workflowId);
        RecordSet rs = new RecordSet();
        rs.executeQuery("select formid from workflow_base where id=?",workflowId);
        if(rs.next()) {
            int formid = weaver.general.Util.getIntValue(rs.getString(1));
            String tableName = "formtable_main_" + (-formid);
            String sql = "update " + tableName + " set " + fields + " where requestid=" + requestId;
            writeLog("DocWkUtil---------->updateFieldValue--->sql:"+sql);
            rs.executeUpdate(sql);
        }
    }

    /**
    * @Desc  文档属性页自定义字段-文件状态
    * @Author b-r
    * @Date 2023/7/4 16:14
    **/
    public String getWKStatus(){
        String wjzt = Util.null2String(getPropValue("doc_wk_cusfield", "wjzt"));
        if("".equals(wjzt)){
            return "wjzt";
        }
        return wjzt;
    }

    /**
     * @Desc  文档属性页自定义字段-生效日期
     * @Author b-r
     * @Date 2023/7/4 16:14
     **/
    public String getWKsxrq(){
        String sxrq = Util.null2String(getPropValue("doc_wk_cusfield", "sxrq"));
        if("".equals(sxrq)){
            return "sxrq";
        }
        return sxrq;
    }

    /**
     * @Desc  文档属性页自定义字段-作废日期
     * @Author b-r
     * @Date 2023/7/4 16:14
     **/
    public String getWKzfrq(){
        String zfrq = Util.null2String(getPropValue("doc_wk_cusfield", "zfrq"));
        if("".equals(zfrq)){
            return "zfrq";
        }
        return zfrq;
    }

    /**
    * @Desc  根据被更新的文件 找到他的主文档，给主文档的文件责任人发送系统默认提醒
    * @Author b-r
    * @Date 2023/7/6 10:26
    **/
    public void sendSysRemind(User user,int docid,String type) {
        SysRemindWorkflow sysRemindWorkflow = new SysRemindWorkflow();
        DocComInfo dci = new DocComInfo();
        RecordSet rs = new RecordSet();
        String docname = dci.getDocname(docid+"");
        if("".equals(docname)){
            rs.executeQuery("select docsubject from docdetail where id=?",docid);
            if(rs.next()){
                docname = Util.null2String(rs.getString(1));
            }
        }
        //根据更新的的文档找到主文档

        rs.executeQuery("select wjgj,wjmc,wjzrr from uf_wjxxztz where id in (select mainid from uf_wjxxztz_dt1 where glwj=?)",docid);
        while (rs.next()) {
            String wjgj = Util.null2String(rs.getString("wjgj"));
            String wjmc = Util.null2String(rs.getString("wjmc"));
            String wjzrr = Util.null2String(rs.getString("wjzrr"));
            //发送流程
            String zhref = DocSptm.DOC_DETAIL_LINK + "?id="+wjgj+ DocSptm.DOC_ROOT_FLAG_VALUE + DocSptm.DOC_DETAIL_ROUT;
            String glhref = DocSptm.DOC_DETAIL_LINK + "?id="+docid+ DocSptm.DOC_ROOT_FLAG_VALUE + DocSptm.DOC_DETAIL_ROUT;

            String requestname = SystemEnv.getHtmlLabelName(543902, user.getLanguage()) + "【" + docname + "】";
            String remark = SystemEnv.getHtmlLabelName(84017, user.getLanguage()) + SystemEnv.getHtmlLabelName(58, user.getLanguage()) + "&nbsp;<a target=_blank href=\"" + zhref + "\">" + wjmc + "</a>&nbsp;"
                    + SystemEnv.getHtmlLabelName(543955, user.getLanguage()) + "&nbsp;<a target=_blank href=\"" + glhref + "\">" + docname + "</a>&nbsp;";
            if("3".equals(type)) {
                //关联文件xxx已变更
                requestname += SystemEnv.getHtmlLabelName(543956, user.getLanguage());
                //您的文档 xxx 关联的 zzz 已变更
                remark += SystemEnv.getHtmlLabelName(543956, user.getLanguage()) + "! ";
            }else if("6".equals(type)){
                //关联文件xxx已作废
                requestname += SystemEnv.getHtmlLabelName(27774, user.getLanguage());
                //您的文档 xxx 关联的 zzz 已作废
                remark += SystemEnv.getHtmlLabelName(27774, user.getLanguage()) + "! ";
            }
            try {
                //标题，表单字段的文档，提醒发起人，提醒to某某，备注。
                sysRemindWorkflow.setDocSysRemind(requestname, docid, user.getUID(), wjzrr, remark);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}