package com.weaver.seconddev.njwebservice.util;

import com.weaver.common.hrm.util.Util;
import com.weaver.common.i18n.tool.util.I18nContextUtil;
import com.weaver.eteams.file.client.file.FileObj;
import com.weaver.eteams.file.client.param.RemoteUploadParam;
import com.weaver.file.ud.api.FileUploadService;
import com.weaver.teams.domain.EntityType;
import com.weaver.verupgrade.conn.CONN_TYPE;
import com.weaver.verupgrade.conn.RecordSet;
import org.apache.axis.encoding.Base64;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.ZipInputStream;

/**
 * createby jianyong.tang
 * createTime
 * version v1
 * desc
 */
@Component
public class DocUtil {
    /**
     * 16进制字符串获取文档id
     * @param filename
     * @param data16
     * @param seccategory
     * @param createrid
     * @return
     */
    private final Logger log = LoggerFactory.getLogger(DocUtil.class);

    public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                    + Character.digit(s.charAt(i + 1), 16));
        }
        return data;
    }

    public static String hexStringToString(String s) {
        if (s == null || s.equals("")) {
            return null;
        }
        s = s.replace(" ", "");
        byte[] baKeyword = new byte[s.length() / 2];
        for (int i = 0; i < baKeyword.length; i++) {
            try {
                baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            s = new String(baKeyword, StandardCharsets.UTF_8);
            // new String();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return s;
    }



    @Autowired
    private FileUploadService fileUploadService;
    public String  createdocByBase642(String filename,String base64Str,String seccategory,String createrid,String tenantKey){
        String docid = "";
        try {
            //DocAccService das = new DocAccService();
            RemoteUploadParam remoteUploadParam = new RemoteUploadParam(filename, "", EntityType.document.name());
            FileObj fileObj = fileUploadService.uploadLocalFileWithBase64(toSemiangle(base64Str.replace(" ","").replace("\r","")), Long.valueOf(createrid), "", remoteUploadParam);
            //long imagefileid = das.getFileByBase64(toSemiangle(base64Str), filename);
            long imagefileid = ObjectUtils.isEmpty(fileObj) ? -1L : fileObj.getFileid();
            docid=String.valueOf(imagefileid);
//            DocSaveService var22 = new DocSaveService();
//            if(imagefileid>0){
//                RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
//                String poolname = CONN_TYPE.hrm.getType();
//                rs.setTenantKey(tenantKey);
//                String departmentId="-1";
//                String sql="SELECT department FROM eteams.dbo.employee WHERE id = '"+createrid+"' AND delete_type = 0 AND tenant_key = '"+tenantKey+"'";
//                rs.executeSql(sql, poolname);
//                User user = new User();
//                if(rs.next()){
//                    departmentId = Util.null2String(rs.getString("department"));
//                }
//                user.setUid(Long.valueOf(createrid));
//                user.setUserDepartment(Long.valueOf(departmentId));
//                user.setLanguage(7);
//                user.setLogintype("1");
//                user.setLoginip("127.0.0.1");
//
//                log.error("seccategory:"+seccategory+"ten:"+HrmContextUtil.getCurrentTenantKey()+" imagefileid:"+imagefileid+" user:"+user.getUID());
//                docid=String.valueOf(var22.accForDoc(Long.valueOf(seccategory),imagefileid,user));
//            }
            //拿到附件id就可以更新到流程表字段

        }catch (Exception e){
            log.error("e",e);
        }
        return docid;
    }

    public  String toSemiangle(String src) {
        char[] c = src.toCharArray();
        for (int index = 0; index < c.length; index++) {
            if (c[index] == 12288) {// 全角空格
                c[index] = (char) 32;
            } else if (c[index] > 65280 && c[index] < 65375) {// 其他全角字符
                c[index] = (char) (c[index] - 65248);
            }
        }
        return String.valueOf(c);
    }




    public Map<String,String> getDocInfo(String docid,String tenantKey) throws Exception {
        RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
        String poolname = CONN_TYPE.document.getType();
        rs.setTenantKey(tenantKey);
        Map<String,String> docmap = new HashMap<>();
        String uploadBuffer="";//base64字符串
        String sql = " select c.file_path ,c.file_url ,b.id as imagefileid,b.size ,b.NAME  from e10_core_business.dbo.document a,e10_core_business.dbo.fileobj b,e10_core_business.dbo.file_storage_info c where a.id=b.REF_ID  and b.URL =c.file_url   " +
                "and a.ID ="+docid+" " +
                "AND a.delete_type = 0 " +
                "AND a.tenant_key = '"+tenantKey+"' " +
                "AND b.delete_type = 0 " +
                "AND b.tenant_key = '"+tenantKey+"' " +
                "AND c.delete_type = 0 " +
                "AND c.tenant_key = '"+tenantKey+"';";
        rs.executeSql(sql, poolname);
        if(rs.next()){
            String imagefileid = Util.null2String(rs.getString("imagefileid"));
            String filerealpath = Util.null2String(rs.getString("file_path"))+"/"+Util.null2String(rs.getString("file_url"));
            String iszip ="1";
            String filesize = Util.null2String(rs.getString("size"));
            String imagefilename = Util.null2String(rs.getString("NAME"));//文件名
            InputStream fi = getFile(filerealpath,iszip);
            docmap.put("imagefileid",imagefileid);
            docmap.put("filename",imagefilename);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int count = 0;
            while((count = fi.read(buffer)) >= 0){
                baos.write(buffer, 0, count);
            }
            uploadBuffer = Base64.encode(baos.toByteArray());
            docmap.put("base64str",uploadBuffer);
            docmap.put("filesize",filesize);
            baos.close();
            //这里就可以封装 文件名和文件内容 传给第三方系统
        }
        return  docmap;

    }

    public Map<String,String> getDocInfoWf(String fileid,String tenantKey) throws Exception {
        RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
        String poolname = CONN_TYPE.document.getType();
        rs.setTenantKey(tenantKey);
        Map<String,String> docmap = new HashMap<>();
        String uploadBuffer="";//base64字符串
        String sql = " select c.file_path ,c.file_url ,b.id as imagefileid,b.size ,b.NAME  from e10_core_business.dbo.fileobj b,e10_core_business.dbo.file_storage_info c where b.URL =c.file_url   " +
                "and b.ID ="+fileid+" " +
                "AND b.delete_type = 0 " +
                "AND b.tenant_key = '"+tenantKey+"' " +
                "AND c.delete_type = 0 " +
                "AND c.tenant_key = '"+tenantKey+"';";
        rs.executeSql(sql, poolname);
        if(rs.next()){
            String imagefileid = Util.null2String(rs.getString("imagefileid"));
            String filerealpath = Util.null2String(rs.getString("file_path"))+"/"+Util.null2String(rs.getString("file_url"));
            String iszip ="1";
            String filesize = Util.null2String(rs.getString("size"));
            String imagefilename = Util.null2String(rs.getString("NAME"));//文件名
            InputStream fi = getFile(filerealpath,iszip);
            docmap.put("imagefileid",imagefileid);
            docmap.put("filename",imagefilename);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int count = 0;
            while((count = fi.read(buffer)) >= 0){
                baos.write(buffer, 0, count);
            }
            uploadBuffer = Base64.encode(baos.toByteArray());
            docmap.put("base64str",uploadBuffer);
            docmap.put("filesize",filesize);
            baos.close();
            //这里就可以封装 文件名和文件内容 传给第三方系统
        }
        return  docmap;

    }
    /**
     * 根据系统文档存放路径 获取文档流
     * @param filerealpath 文档存放路径
     * @param iszip 是否压缩包
     * @return
     * @throws Exception
     */
    private InputStream getFile(String filerealpath, String iszip)
            throws Exception {
        ZipInputStream zin = null;
        InputStream imagefile = null;
        File thefile = new File(filerealpath);
        if (iszip.equals("1")) {
            zin = new ZipInputStream(new FileInputStream(thefile));
            if (zin.getNextEntry() != null)
                imagefile = new BufferedInputStream(zin);
        } else {
            imagefile = new BufferedInputStream(new FileInputStream(thefile));
        }
        return imagefile;
    }

    public String getShareRyids(String wdid,String tenantKey){
        StringBuffer ryids = new StringBuffer();
        if("".equals(wdid)){
            return "";
        }
        RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
        String poolname = CONN_TYPE.document.getType();
        rs.setTenantKey(tenantKey);
        RecordSet rs_dt = I18nContextUtil.getBean(RecordSet.class);
        rs_dt.setTenantKey(tenantKey);
        String typeids = "";
        String flag = "";
        String sql_dt = "";
        String sql = "select distinct target_type  from e10_core_business.dbo.document_ph_doc_s01 where source_id="+wdid+" and delete_type=0 and tenant_key ='"+tenantKey+"'";
        rs.executeSql(sql, poolname);
        while (rs.next()){
            String type = Util.null2String(rs.getString("target_type"));
            typeids = typeids + flag +type;
            flag = ",";
        }
        poolname = CONN_TYPE.hrm.getType();
        typeids = ","+typeids+",";
        log.error(typeids);
        flag = "";
        if(typeids.indexOf(",11,")>=0){//所有人
            String seclevel = "";
            String seclevelmax = "";
            sql = "select target_min_sec_level ,target_max_sec_level from e10_core_business.dbo.document_ph_doc_s01 where source_id="+wdid+" and delete_type=0 and tenant_key ='"+tenantKey+"' and target_type=11";
            rs.executeSql(sql, CONN_TYPE.document.getType());
            if(rs.next()){
                seclevel = Util.null2String(rs.getString("target_min_sec_level"));
                seclevelmax = Util.null2String(rs.getString("target_max_sec_level"));
            }
            sql = "select id from eteams.dbo.employee WHERE PERSONNEL_STATUS <6 and sec_level>="+seclevel+" and sec_level<="+seclevelmax +" AND delete_type = 0 AND tenant_key = '"+tenantKey+"'";
            rs.executeSql(sql, poolname);
            while (rs.next()){
                ryids.append(flag).append(rs.getString("id"));
                flag = ",";
            }

        }
        if(typeids.indexOf(",5,")>=0 || typeids.indexOf(",501,")>=0){//分部
            String seclevel = "";
            String seclevelmax = "";
            String subcomid = "";
            sql = "select target_min_sec_level ,target_max_sec_level,target_id from e10_core_business.dbo.document_ph_doc_s01 where source_id="+wdid+" and delete_type=0 and tenant_key ='"+tenantKey+"' and target_type in(5,501)";
            rs.executeSql(sql,CONN_TYPE.document.getType());
            while (rs.next()){
                seclevel = Util.null2String(rs.getString("target_min_sec_level"));
                seclevelmax = Util.null2String(rs.getString("target_max_sec_level"));
                subcomid = Util.null2String(rs.getString("target_id"));
                if("".equals(subcomid)){
                    continue;
                }
                sql_dt = "SELECT a.id FROM eteams.dbo.employee a,eteams.dbo.department b  WHERE a.DEPARTMENT =b.id and b.subcompanyid ='"+subcomid+"' and PERSONNEL_STATUS <6 and sec_level>="+seclevel+" and sec_level<="+seclevelmax +" AND a.delete_type = 0 AND a.tenant_key = '"+tenantKey+"'";
                rs_dt.executeSql(sql_dt,poolname);
                while (rs_dt.next()){
                    ryids.append(flag).append(rs_dt.getString("id"));
                    flag = ",";
                }
            }
        }
        if(typeids.indexOf(",6,")>=0 || typeids.indexOf(",502,")>=0){//分部下级
            String seclevel = "";
            String seclevelmax = "";
            String subcomid = "";
            sql = "select target_min_sec_level ,target_max_sec_level,target_id from e10_core_business.dbo.document_ph_doc_s01 where source_id="+wdid+" and delete_type=0 and tenant_key ='"+tenantKey+"' and target_type in(6,502)";
            rs.executeSql(sql,CONN_TYPE.document.getType());
            while (rs.next()){
                seclevel = Util.null2String(rs.getString("target_min_sec_level"));
                seclevelmax = Util.null2String(rs.getString("target_max_sec_level"));
                subcomid = Util.null2String(rs.getString("target_id"));
                if("".equals(subcomid)){
                    continue;
                }
                String comids = "";
                String flag1 = "";
                sql_dt = "WITH allsub(id,name,parent)  " +
                        "as (  " +
                        "SELECT id,name ,parent FROM eteams.dbo.department where id in("+subcomid+") and type = 'subcompany' AND virtualid = 1 and STATUS =1 AND delete_type = 0 AND tenant_key = '"+tenantKey+"' " +
                        " UNION ALL SELECT a.id,a.name,a.parent FROM eteams.dbo.department a,allsub b where a.parent = b.id and type = 'subcompany' AND virtualid = 1 and STATUS =1 AND delete_type = 0 AND tenant_key = '"+tenantKey+"' " +
                        ") select id from allsub";
                rs_dt.executeSql(sql_dt,poolname);
                while (rs_dt.next()){
                    comids = comids + flag1 +rs_dt.getString("id");
                    flag1 = ",";
                }
                sql_dt = "SELECT a.id FROM eteams.dbo.employee a,eteams.dbo.department b  WHERE a.DEPARTMENT =b.id and b.subcompanyid in("+comids+") and PERSONNEL_STATUS <6 and sec_level>="+seclevel+" and sec_level<="+seclevelmax +" AND a.delete_type = 0 AND a.tenant_key = '"+tenantKey+"'";
                rs_dt.executeSql(sql_dt,poolname);
                while (rs_dt.next()){
                    ryids.append(flag).append(rs_dt.getString("id"));
                    flag = ",";
                }
            }
        }

        if(typeids.indexOf(",2,")>=0||typeids.indexOf(",2002,")>=0){//部门
            String seclevel = "";
            String seclevelmax = "";
            String deptid = "";
            sql = "select target_min_sec_level ,target_max_sec_level,target_id from e10_core_business.dbo.document_ph_doc_s01 where source_id="+wdid+" and delete_type=0 and tenant_key ='"+tenantKey+"' and target_type in(2,2002)";
            rs.executeSql(sql,CONN_TYPE.document.getType());
            while (rs.next()){
                seclevel = Util.null2String(rs.getString("target_min_sec_level"));
                seclevelmax = Util.null2String(rs.getString("target_max_sec_level"));
                deptid = Util.null2String(rs.getString("target_id"));
                if("".equals(deptid)){
                    continue;
                }
                sql_dt = "SELECT a.id FROM eteams.dbo.employee a  WHERE a.DEPARTMENT ='"+deptid+"' and PERSONNEL_STATUS <6 and sec_level>="+seclevel+" and sec_level<="+seclevelmax +" AND delete_type = 0 AND tenant_key = '"+tenantKey+"'";
                rs_dt.executeSql(sql_dt,poolname);
                while (rs_dt.next()){
                    ryids.append(flag).append(rs_dt.getString("id"));
                    flag = ",";
                }
            }
        }

        if(typeids.indexOf(",3,")>=0 || typeids.indexOf(",3002,")>=0){//部门含下级
            String seclevel = "";
            String seclevelmax = "";
            String deptid = "";
            sql = "select target_min_sec_level ,target_max_sec_level,target_id from e10_core_business.dbo.document_ph_doc_s01 where source_id="+wdid+" and delete_type=0 and tenant_key ='"+tenantKey+"' and target_type in(3,3002)";
            rs.executeSql(sql,CONN_TYPE.document.getType());
            while (rs.next()){
                seclevel = Util.null2String(rs.getString("target_min_sec_level"));
                seclevelmax = Util.null2String(rs.getString("target_max_sec_level"));
                deptid = Util.null2String(rs.getString("target_id"));
                if("".equals(deptid)){
                    continue;
                }
                String deptids = "";
                String flag1 = "";
                sql_dt = "WITH allsub(id,name,parent)  " +
                        "as (  " +
                        "SELECT id,name ,parent FROM eteams.dbo.department where id in("+deptid+") and type = 'department' AND virtualid = 1 and STATUS =1 AND delete_type = 0 AND tenant_key = '"+tenantKey+"' " +
                        " UNION ALL SELECT a.id,a.name,a.parent FROM eteams.dbo.department a,allsub b where a.parent = b.id and type = 'department' AND virtualid = 1 and STATUS =1 AND delete_type = 0 AND tenant_key = '"+tenantKey+"' " +
                        ") select id from allsub";
                rs_dt.executeSql(sql_dt,poolname);
                while (rs_dt.next()){
                    deptids = deptids + flag1 +rs_dt.getString("id");
                    flag1 = ",";
                }
                sql_dt = "SELECT a.id FROM eteams.dbo.employee a  WHERE a.DEPARTMENT in("+deptids+") and PERSONNEL_STATUS <6 and sec_level>="+seclevel+" and sec_level<="+seclevelmax +" AND delete_type = 0 AND tenant_key = '"+tenantKey+"'";
                log.error(sql_dt);
                rs_dt.executeSql(sql_dt,poolname);
                while (rs_dt.next()){
                    ryids.append(flag).append(rs_dt.getString("id"));
                    flag = ",";
                }
            }
        }

        if(typeids.indexOf(",1,")>=0){//人员
            String ryid = "";
            sql = "select target_id from e10_core_business.dbo.document_ph_doc_s01 where source_id="+wdid+" and delete_type=0 and tenant_key ='"+tenantKey+"' and target_type in(1)";
            rs.executeSql(sql,CONN_TYPE.document.getType());
            while (rs.next()){
                ryid = Util.null2String(rs.getString("target_id"));
                if("".equals(ryid)){
                    continue;
                }
                ryids.append(flag).append(ryid);
                flag = ",";

            }
        }

        if(typeids.indexOf(",10,")>=0){//角色 人员
            String seclevel = "";
            String seclevelmax = "";
            String roleid = "";
            sql = "select target_min_sec_level ,target_max_sec_level,target_id from e10_core_business.dbo.document_ph_doc_s01 where source_id="+wdid+" and delete_type=0 and tenant_key ='"+tenantKey+"' and target_type in(10)";
            rs.executeSql(sql,CONN_TYPE.document.getType());
            while (rs.next()){
                seclevel = Util.null2String(rs.getString("target_min_sec_level"));
                seclevelmax = Util.null2String(rs.getString("target_max_sec_level"));
                roleid = Util.null2String(rs.getString("target_id"));
                if("".equals(roleid)){
                    continue;
                }
                sql_dt = "SELECT a.id FROM eteams.dbo.employee a where id in(SELECT user_id FROM eteams.dbo.auth_user_role WHERE role_id = "+roleid+" AND resource_type = 'RESOURCE' AND delete_type = 0 AND tenant_key = '"+tenantKey+"' )  and PERSONNEL_STATUS <6 and sec_level>="+seclevel+" and sec_level<="+seclevelmax;
                rs_dt.executeSql(sql_dt,poolname);
                while (rs_dt.next()){
                    ryids.append(flag).append(rs_dt.getString("id"));
                    flag = ",";
                }
            }
        }

        if(typeids.indexOf(",1411,")>=0){//群组
            String seclevel = "";
            String seclevelmax = "";
            String groupid = "";
            sql = "select target_min_sec_level ,target_max_sec_level,target_id from e10_core_business.dbo.document_ph_doc_s01 where source_id="+wdid+" and delete_type=0 and tenant_key ='"+tenantKey+"' and target_type in(1411)";
            rs.executeSql(sql,CONN_TYPE.document.getType());
            while (rs.next()){
                seclevel = Util.null2String(rs.getString("target_min_sec_level"));
                seclevelmax = Util.null2String(rs.getString("target_max_sec_level"));
                groupid = Util.null2String(rs.getString("target_id"));
                if("".equals(groupid)){
                    continue;
                }
                sql_dt = "SELECT a.id FROM eteams.dbo.employee a where id in(SELECT employee FROM eteams.dbo.channel_user_link  where channel="+groupid+" and delete_type=0)  and PERSONNEL_STATUS <6 and sec_level>="+seclevel+" and sec_level<="+seclevelmax;
                rs_dt.executeSql(sql_dt,poolname);
                while (rs_dt.next()){
                    ryids.append(flag).append(rs_dt.getString("id"));
                    flag = ",";
                }
            }
        }


        return ryids.toString();

    }

}
