package weaver.interfaces.htsc.cus;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tools.ant.taskdefs.Tstamp;
import weaver.common.util.string.StringUtil;
import weaver.conn.RecordSet;
import weaver.file.ImageFileManager;
import weaver.general.BaseBean;
import weaver.general.GCONST;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.company.DepartmentComInfo;
import weaver.interfaces.htsc.GlobatTools.MessageDetailLog;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestInfo;
import weaver.workflow.request.RequestManager;
import weaver.docs.docs.util.DocImagefileToPdfUseWps;
import weaver.wps.officed.ConvertToPdf;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 手动签章流程接口
 */
public class ManualSignAction extends BaseBean implements Action {

    private Log log = LogFactory.getLog(this.getClass());

    @Override
    public String execute(RequestInfo requestInfo) {
        HTUtil htUtil = new HTUtil();


        String requestid = Util.null2String(requestInfo.getRequestid());//流程请求ID
        //流程标题
        String requestName = Util.null2String(requestInfo.getRequestManager().getRequestname());
        String tableName = Util.null2String(requestInfo.getRequestManager().getBillTableName());
        //当前操作人（印章管理员）
        MessageDetailLog messageDetailLog=new MessageDetailLog(tableName);
        User user = requestInfo.getRequestManager().getUser();
        log.info("手动签章流程接口-----START-----" + requestid);
        try {
            PropBean pb = new PropBean();
            //应用ID
            String appid = Util.null2String(pb.getPropName("AutoSign.appId"));
            //秘钥
            String secret = Util.null2String(pb.getPropName("AutoSign.secret"));
            //统一信用代码
            String code = Util.null2String(pb.getPropName("AutoSign.code"));


            String sql = "  select  * from "+tableName+"  where requestid = "+requestid;



           // new DocImagefileToPdfUseWps().convertToPdfEncrypt


            RecordSet rs = new RecordSet();
            rs.execute(sql);
            if(rs.getArray().size()<=0){
                requestInfo.getRequestManager().setMessageid("500");
                requestInfo.getRequestManager().setMessagecontent("数据查询为空");
                return Action.FAILURE_AND_CONTINUE;
            }
            rs.next();
            //String yywj = Util.null2String(rs.getString("yywj"));
          String datetimes= new  SimpleDateFormat("_yyyyMMddmmssdd").format(new Date()).toString();
           // String flowNum = Util.null2String(rs.getString("id")+datetimes);
            String flowNum = Util.null2String(rs.getString("id"));

       /*     if("".equals(yywj)){
                requestInfo.getRequestManager().setMessageid("111111");
                requestInfo.getRequestManager().setMessagecontent("请进行【定稿】操作！");
                return Action.FAILURE_AND_CONTINUE;
            }*/
            String yz = Util.null2String(rs.getString("yz"));

            if(!"".equals(flowNum)){  //id不能为空
                if("".equals(yz)){
                    requestInfo.getRequestManager().setMessageid("111111");
                    requestInfo.getRequestManager().setMessagecontent("请选择印章后提交！");
                    return Action.FAILURE_AND_CONTINUE;
                }else{//判断只有有且仅有一个印章的时候才会调用手动印章
                    JSONObject obj = new JSONObject();
                    obj.put("appId",appid);
                    obj.put("secret",secret);
                    obj.put("flowName",requestName);
                    obj.put("flowNum",requestid);//这里流程编号修改成requestid
                 //   obj.put("needWatermark","ENABLE");//水印
                    JSONObject flowOwnerObj = new JSONObject();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    flowOwnerObj.put("flowSendTime",sdf.format(new Date()));
                    DepartmentComInfo dc = new DepartmentComInfo();
                    //部门编码
                    String orgId = Util.null2String(dc.getDepartmentCode(user.getUserDepartment()+""));
                    flowOwnerObj.put("orgId",orgId);
                    //部门编码
                    String orgName = Util.null2String(dc.getDepartmentName(user.getUserDepartment()+""));
                    flowOwnerObj.put("orgName",orgName);
                    //姓名
                    String personName = user.getLastname();
                    //工号
                    String personNum = user.getLoginid();
                    personName+="("+personNum+")";
                    flowOwnerObj.put("personName",personName);
                    flowOwnerObj.put("personNum",personNum);
                    obj.put("flowOwner",flowOwnerObj);

                    JSONArray docSignsArr = new JSONArray();

            List<Map<String,String>> yywjmap= getdetail(flowNum,tableName);
            if(yywjmap==null||yywjmap.size()<=0){
                return null;
            }
           // for (String docid :yywj.split(",")) {
           for (Map<String,String> docmap :yywjmap) {
               String docaaray = docmap.get("wjmc").toString();
               String dsmdy = docmap.get("dsmdy").toString();
               String dzyyfs = docmap.get("dzyyfs").toString();
               String yqxdyr= docmap.get("yqxdyr").toString();
               String fwdyfs=docmap.get("fwdyfs").toString();
               for (String docid : docaaray.split(",")) {
                   if(docid==""){
                       break;
                   }
                   JSONObject docObj = new JSONObject();//正文对象

                   docObj.put("docId", docid);
                   //文件类型
                   String doctype = "oa_contract_sd";
                  /* String oa_contract_sd = "";
                   if (dzyyfs == "0") {
                       doctype = "电子件";
                   } else if (dzyyfs == "1") {
                       doctype = "防伪打印件";
                   }*/



                   docObj.put("docType", doctype);
                 //  docObj.put("oa_contract_sd", oa_contract_sd);

// by xf ceshi
                     Map<String, String> pdfMap = getLatestVersionPDF(requestid, docid);
                    if (pdfMap.isEmpty()) {
                            requestInfo.getRequestManager().setMessageid("111111");
                            requestInfo.getRequestManager().setMessagecontent("上传挂载正文PDF文件出错！");
                            return Action.FAILURE_AND_CONTINUE;
                         }
                      String fileAttachPatch = pdfMap.get("mountpath");//挂载出去的地址
                     docObj.put("fileAttachPatch", fileAttachPatch);
                          String fileNameDisplay = pdfMap.get("imagefilename");//文件名称
                     docObj.put("fileNameDisplay", fileNameDisplay);


                   docObj.put("signMethod", "ORDER");
                   JSONArray signersArr = new JSONArray();
                   JSONObject signersObj = new JSONObject();
                   signersObj.put("code", code);
                   signersObj.put("codeType", "USC");
                   signersObj.put("revokeFlag", "false");


                   if ("0".equals(dzyyfs)) { //电子件
                       docObj.put("effectType", "ELECTRONIC"); //
                   } else if ("1".equals(dzyyfs)) {  //电子防伪件

                       docObj.put("effectType", "ELECTRONIC");
                       Integer userid= Util.getIntValue(yqxdyr);
                        if(userid!=-1){
                            User use=new User(userid);
                            JSONObject printSettingobj=new JSONObject();
                            printSettingobj.put("personName",use.getLastname());
                            printSettingobj.put("personNum", use.getLoginid());
                            printSettingobj.put("printNum", fwdyfs);
                            docObj.put("printSetting",printSettingobj);
                        }

                   }



                   String yzcode = getSignCode(yz);
                   if ("".equals(yzcode)) {
                       requestInfo.getRequestManager().setMessageid("111111");
                       requestInfo.getRequestManager().setMessagecontent("未找到对应的印章ID，请查看是否维护！");
                       return Action.FAILURE_AND_CONTINUE;
                   }

                   signersObj.put("sealId", yzcode);  //印章id

                 /*  JSONArray sealsarray = new JSONArray();

                   for (String s : yzcode.split(",")) {
                       JSONObject sealobject = new JSONObject();
                       sealobject.put("sealId", s);
                       sealsarray.add(sealobject);
                   }

                  signersObj.put("seals", sealsarray);*/ //推荐的适用的印章id //暂时不用
                   //     sealId	印章ID	是	字符	100	印章ID
                   //   keyWord	关键字	否	字符	100	一键盖章或手动盖章，关键字定位。
                   //   templateId	模板ID	否	字符	100	一键盖章或手动盖章，模板ID。

                   signersObj.put("signNum", "1");
                   signersObj.put("ownerType", "INSIDE");
                   signersObj.put("signatoryType", "ENTERPRISE");
                   signersObj.put("keyWord", "华泰证券股份有限公司签章");
                   signersObj.put("signMethod", "TRUSTEESHIP");
                   signersObj.put("signedExamine", "DISABLE");
                   signersArr.add(signersObj);


                   docObj.put("signers", signersArr);
                   docObj.put("validityStartDate", sdf.format(new Date()));
                   docObj.put("validityEndDate", getNextYear(sdf.format(new Date()), "yyyy-MM-dd HH:mm:ss", 30));
                   docSignsArr.add(docObj);
               }
           }



                    obj.put("docSigns",docSignsArr);
                    obj.put("signUserId",user.getLoginid());
                    obj.put("signUserName",user.getLastname());
                    messageDetailLog.writLogsnotretrun(requestid,obj.toString(),"1",messageDetailLog.Other);
                    System.out.println("objtostring"+obj.toString());



                    String response = htUtil.ManualSignPost(obj.toJSONString());//返回结果
                    if("".equals(response)){
                        requestInfo.getRequestManager().setMessageid("111111");
                        requestInfo.getRequestManager().setMessagecontent("手动签章接口返回结果为空！");
                        return Action.FAILURE_AND_CONTINUE;
                    }
                    JSONObject res = JSONObject.parseObject(response);
                    String status = Util.null2String(res.get("status"));//标识  200：成功   否则失败
                    String message = Util.null2String(res.get("message"));
                    log.info("手动签章响应状态："+status);
                    log.info("手动签章响应信息："+message);
                    if(!"200".equals(status)){
                        messageDetailLog.writeinseertLogs(requestid,res.toString(),"1",messageDetailLog.success,messageDetailLog.error,response);
                        requestInfo.getRequestManager().setMessageid("111111");
                        requestInfo.getRequestManager().setMessagecontent("用印失败，请联系管理员处理!");
                        return Action.FAILURE_AND_CONTINUE;
                    }
                    JSONObject data = JSONObject.parseObject(Util.null2String(res.get("data")));
                 //   String flowNum = Util.null2String(data.get("flowNum"));
                    JSONArray docIdsArr = JSONArray.parseArray(Util.null2String(data.get("docIds")));
                    RecordSet rs_up = new RecordSet();
                    String docidStr = "";
                    for(int i=0;i<docIdsArr.size();i++){
                        if("".equals(docidStr)){
                            docidStr = Util.null2String(docIdsArr.get(i));
                        }else{
                            docidStr += "," + Util.null2String(docIdsArr.get(i));
                        }
                    }
                    rs_up.execute("update "+ tableName + " set flowNum='"+flowNum+"',docIds='"+docidStr+"' where requestid = "+requestid);
                    messageDetailLog.writeinseertLogs(requestid,res.toString(),"1",messageDetailLog.success,messageDetailLog.success,response);
                }


            }
        } catch (Exception e) {
            messageDetailLog.writLogsnotretrun(requestid,e.getMessage(),"1",messageDetailLog.error);
            e.printStackTrace();
            requestInfo.getRequestManager().setMessageid("111111");
            requestInfo.getRequestManager().setMessagecontent("手动签章接口异常，请联系系统管理员！");
            return Action.FAILURE_AND_CONTINUE;
        }
        log.info("手动签章流程接口-----END-----" + requestid);
        return Action.SUCCESS;
    }




    private List<Map<String,String>> getdetail(String mainid,String tablename){
        List<Map<String,String>> maplist=new ArrayList<>();
        RecordSet rs = new RecordSet();

        String sqlvalue="select id,sfyy,wjmc,dsmdy,dzyyfs,zpdfhwj,yqxdyr,fwdyfs from "+tablename+"_dt1 where mainid in ("+mainid+")";
        rs.execute(sqlvalue);
        if(rs.getArray().size()<=0){
            return  maplist;
        }
        while (rs.next()){
            Map<String,String> mapdetail=new HashMap<>();
            String detailid=Util.null2String(rs.getString("id"));
            String wjmc=Util.null2String(rs.getString("wjmc"));
            if(detailid==""||wjmc==""){
                break;
            }
            //测试
       //     String pdfwjmc=Util.null2String(rs.getString("zpdfhwj"));
           String pdfwjmc= getAcction(wjmc,detailid,tablename+"_dt1");
            if(pdfwjmc==""){
                break;
            }
            mapdetail.put("sfyy",Util.null2String(rs.getString("sfyy")));
            mapdetail.put("wjmc",pdfwjmc);
            mapdetail.put("dsmdy",Util.null2String(rs.getString("dsmdy")));
            mapdetail.put("dzyyfs",Util.null2String(rs.getString("dzyyfs")));
            mapdetail.put("yqxdyr",Util.null2String(rs.getString("yqxdyr")));
            mapdetail.put("fwdyfs",Util.null2String(rs.getString("fwdyfs")));

            maplist.add(mapdetail);
        }

        return  maplist;
    }

    /**
     * 读取最新版本的正文文件并上传至指定目录
     * @param requestid 流程请求ID
     * @param fileids 文档ID
     * @return 结果集合
     */
    public Map<String,String> getLatestVersionPDF(String requestid,String fileids){
        Map<String,String> map = new HashMap<>();

        PropBean pb = new PropBean();
        try{
            //取最大版本的正文信息
            String sql = "        select f.imagefileid,f.imagefilename from imagefile f  where f.imagefileid in     (?)";
            System.out.println("----------sqlmanualsignaction:------------"+sql);
            RecordSet rs = new RecordSet();
            rs.executeQuery(sql,new Object[]{fileids});
            if(rs.next()){
                String imagefileid = Util.null2String(rs.getString("imagefileid"));
                String imagefilenamehz = Util.null2String(rs.getString("imagefilename"));
                String postfix="";
                String postfilename="";
                if(imagefilenamehz.split(".").length>=2){
                      //    postfix="."+imagefilenamehz.split(".")[imagefilenamehz.split(".").length-1];
                    if(imagefilenamehz.indexOf(".")>0){
                        postfilename=imagefilenamehz.substring(0,imagefilenamehz.indexOf("."));
                    }

                }
//                String imagefilename = Util.null2String(rs.getString("imagefilename"));
                String imagefilename = imagefileid+imagefilenamehz;
                String imagefilepostname="";
                if(!"".equals(postfilename)){
                    imagefilepostname=postfilename+postfix;
                }else{
                    imagefilepostname=imagefileid+postfix;
                }
                InputStream inputstream = ImageFileManager.getInputStreamById(Util.getIntValue(imagefileid));
                int index;
                byte[] bytes = new byte[1024];
                // 文件夹名称
                String folderName = requestid+"_"+imagefileid+"_"+System.currentTimeMillis();
                String mountdir = Util.null2String(pb.getPropName("AutoSign.mountdir"));
                if("".equals(mountdir)){
                    log.info("获取的用印上传共享目录为空！");
                    return map;
                }

                String path = mountdir+"/" + folderName;
                // linux 下 先创建文件夹
                File dir = new File(path);
                //设置写权限，windows下不用此语句
                dir.setWritable(true, false);
                dir.mkdirs();
                //赋权限，正常是当前用户的权限，但是这里和之前的老OA不是同一个用户
                Runtime.getRuntime().exec("chmod -R 777 " + path);
                path += "/"+imagefilename;//创建文件
                File file = new File(path);
                if (file.exists()) {
                    file.delete();
                }
//                file.createNewFile();
                FileOutputStream uploadFile = new FileOutputStream(file);
                while ((index = inputstream.read(bytes)) != -1) {
                    uploadFile.write(bytes, 0, index);
                    uploadFile.flush();
                }
                inputstream.close();
                uploadFile.close();
                Runtime.getRuntime().exec("chmod -R 777 " + path);
                map.put("imagefilename",imagefilepostname);
                map.put("realpath",path);
                String Signmountpath = Util.null2String(pb.getPropName("Signmountpath"));
                String mountpath=Signmountpath+folderName+"/"+imagefilename;
                map.put("mountpath",mountpath);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return map;
    }

    public String getAcction(String docid,String detailid,String mainid){
        RecordSet rs = new RecordSet();
        ConvertToPdf convertToPdf=new ConvertToPdf();
        String rsdetail="";
        String sql="select imagefileid,imagefilename from DocImageFile where docid in ("+docid+")";
        rs.execute(sql);
        if(rs.getArray().size()<=0){
            return  null;
        }
        while (rs.next()){
           int imagefileid= Integer.parseInt(rs.getString("imagefileid"));
            String imagefilename=  rs.getString("imagefilename");

            int imagepdfid=convertToPdf.getDownloadPDFUrl(imagefileid,imagefilename);
            rsdetail+=imagepdfid+",";
        }
        if("".equals(rsdetail)){
            return "";
        }
        if(rsdetail.length()>0){
            rsdetail=rsdetail.substring(0,rsdetail.length()-1);
        }
        String sqlvalue="update "+mainid+" set zpdfhwj='"+rsdetail+"' where id="+detailid;
        rs.execute(sqlvalue);
        return rsdetail;

    }



    /**
     * 印章ID转印章编号
     * @param signid 印章ID
     * @return 印章编号
     */
    private String getSignCode(String signid){
        RecordSet rs = new RecordSet();
        String yzbhvalue="";
        rs.execute("select yzbh from uf_yinzhang where id in ("+signid+")");
        if (rs.getArray().size()<=0) {
            return "";
        }
        while(rs.next()){
            if(!"".equals(Util.null2String(rs.getString("yzbh")))){
                yzbhvalue+=Util.null2String(rs.getString("yzbh"))+",";
            }
        }
            if(yzbhvalue.length()>0){
                yzbhvalue=yzbhvalue.substring(0,yzbhvalue.length()-1);
            }
        return yzbhvalue;
    }

    /**
     * 取具体日期的后多少年日期
     * @param dateStr 参照日期
     * @param pattern 日期格式
     * @param num 几年
     * @return 几年后的日期
     */
    private  String getNextYear(String dateStr,String pattern,int num) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        try {
            Date date = sdf.parse(dateStr);
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            cal.add(Calendar.YEAR, num);
            return sdf.format(cal.getTime());
        } catch (ParseException  e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "";
        }
    }

}
