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 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.JAVATools;
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 java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 自动签章流程接口
 */
public class AutoSignAction 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());
        requestName=JAVATools.lengthsub(requestName,0,100);
        String tableName = Util.null2String(requestInfo.getRequestManager().getBillTableName());
        //当前操作人（印章管理员）
        User user = requestInfo.getRequestManager().getUser();
        MessageDetailLog messageDetailLog=new MessageDetailLog(tableName);
        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 doctype = Util.null2String(pb.getPropName("AutoSign.docType"));
            //统一信用代码
            String code = Util.null2String(pb.getPropName("AutoSign.code"));
           //增加dzyyfs用于keyword
            String sql = "select id,sfcwgz,zwpdf,yz,sfcwgz,flowNum,qzbj,lcbh  from " + tableName + " where requestid = "+requestid;
            RecordSet rs = new RecordSet();
            rs.execute(sql);
            rs.next();
            int heightMoveSize=0;
            int moveSize=0;
            try {
                moveSize = Integer.parseInt(Util.null2String(pb.getPropName("AutoSign.moveSize")));
                heightMoveSize = Integer.parseInt(Util.null2String(pb.getPropName("AutoSign.heightMoveSize")));
            }catch (Exception exo){
                System.out.println("自动用印转换失败");
            }
            String sfcwgz = Util.null2String(rs.getString("sfcwgz"));//是否盖章  0：是 1：否
            String zwpdf = Util.null2String(rs.getString("zwpdf"));
            String flowNumWf = Util.null2String(rs.getString("flowNum"));//
            String qzbj = Util.null2String(rs.getString("qzbj"));//
            String lcbh=Util.null2String(rs.getString("lcbh"));
            String keyword="华泰证券股份有限公司签章";
            if(!"".equals(qzbj)){
                keyword=qzbj;
            }
            if("".equals(zwpdf)){
                requestInfo.getRequestManager().setMessageid("111111");
                requestInfo.getRequestManager().setMessagecontent("请进行【定稿】操作！");
                return Action.FAILURE_AND_CONTINUE;
            }
            String yz = Util.null2String(rs.getString("yz"));

            if("0".equals(sfcwgz) && "".equals(flowNumWf)){//只有盖章的时候才会自动用印,避免重复用印
                if("".equals(yz)){
                    requestInfo.getRequestManager().setMessageid("111111");
                    requestInfo.getRequestManager().setMessagecontent("请选择印章后提交！");
                    return Action.FAILURE_AND_CONTINUE;
                }else if(!yz.contains(",")){//判断只有有且仅有一个印章的时候才会调用自动印章
                    JSONObject obj = new JSONObject();
                    obj.put("appId",appid);
                    obj.put("secret",secret);
                    obj.put("flowName",requestName);
                    obj.put("flowNum",lcbh);//这里流程编号修改成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();
                    JSONObject docObj = new JSONObject();//正文对象
                    docObj.put("docId",zwpdf);
                    docObj.put("docType",doctype);
                    docObj.put("effectType","ELECTRONIC");
                    Map<String,String> pdfMap = getLatestVersionPDF(requestid,zwpdf);
                    if(pdfMap.isEmpty()){
                        requestInfo.getRequestManager().setMessageid("111111");
                        requestInfo.getRequestManager().setMessagecontent("上传挂载正文PDF文件出错！");
                        return Action.FAILURE_AND_CONTINUE;
                    }
                    System.out.println("正文pdf文件上传成功");
                    String fileAttachPatch = pdfMap.get("mountpath");//挂载出去的地址
                    docObj.put("fileAttachPatch",fileAttachPatch);
                    String fileNameDisplay = pdfMap.get("imagefilename");//文件名称
                    docObj.put("fileNameDisplay",fileNameDisplay);
                    JSONObject jsonContent = new JSONObject();
                    docObj.put("jsonContent",jsonContent);
                    docObj.put("signMethod","ORDER");
                    JSONArray signersArr = new JSONArray();
                    JSONObject signersObj = new JSONObject();
                    signersObj.put("code",code);
                    signersObj.put("codeType","USC");
                    signersObj.put("revokeFlag","false");
                    String yzcode = getSignCode(yz);
                    if("".equals(yzcode)){
                        System.out.println("未找到对应的印章ID");
                        requestInfo.getRequestManager().setMessageid("111111");
                        requestInfo.getRequestManager().setMessagecontent("未找到对应的印章ID，请查看是否维护！");
                        return Action.FAILURE_AND_CONTINUE;
                    }
                    signersObj.put("sealId",yzcode);
                    signersObj.put("signNum","1");
                    signersObj.put("ownerType","INSIDE");
                    signersObj.put("signatoryType","ENTERPRISE");
                    signersObj.put("keyWord",keyword);
                    System.out.println("已添加keyword");
                    signersObj.put("moveSize",moveSize);
                    signersObj.put("heightMoveSize",heightMoveSize);
                    System.out.println("已添加偏移量");
                    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);
                    messageDetailLog.writLogsnotretrun(requestid,obj.toJSONString(),"1",messageDetailLog.Other);
                    String response = htUtil.doAutoSign(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,obj.toJSONString(),"1",messageDetailLog.success,messageDetailLog.error,response);
                        requestInfo.getRequestManager().setMessageid("111111");
                        requestInfo.getRequestManager().setMessagecontent("用印失败，请联系管理员处理!");
                        return Action.FAILURE_AND_CONTINUE;
                    }
                    messageDetailLog.writeinseertLogs(requestid,obj.toJSONString(),"1",messageDetailLog.success,messageDetailLog.success,response);
                    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.writLogsnotretrun(requestid,obj.toJSONString(),"1",messageDetailLog.Other);
                  }


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

    /**
     * 读取最新版本的正文文件并上传至指定目录
     * @param requestid 流程请求ID
     * @param docid 文档ID
     * @return 结果集合
     */
    private Map<String,String> getLatestVersionPDF(String requestid,String docid){
        Map<String,String> map = new HashMap<>();
        PropBean pb = new PropBean();
        try{
            //取最大版本的正文信息
            String sql = "select t.* from (select imagefileid,imagefilename,versionid from docimagefile \n" +
                    "where docid = ? \n" +
                    "order by versionid  desc) t where rownum < 2";
            RecordSet rs = new RecordSet();
            rs.executeQuery(sql,new Object[]{docid});
            if(rs.next()){
                String imagefileid = Util.null2String(rs.getString("imagefileid"));
//                String imagefilename = Util.null2String(rs.getString("imagefilename"));
                String imagefilename = docid+".pdf";
                String versionid = Util.null2String(rs.getString("versionid"));
                log.info("正文："+imagefilename+"的最新版本是："+versionid);
                InputStream inputstream = ImageFileManager.getInputStreamById(Util.getIntValue(imagefileid));
                int index;
                byte[] bytes = new byte[1024];
                // 文件夹名称
                String folderName = requestid+"_"+docid+"_"+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);
                log.info("正文imagefilename："+imagefilename);
                log.info("正文realpath："+path);
                log.info("正文mountpath："+imagefilename);
                map.put("imagefilename",folderName+"/"+imagefilename);
                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;
    }

    /**
     * 印章ID转印章编号
     * @param signid 印章ID
     * @return 印章编号
     */
    private String getSignCode(String signid){
        RecordSet rs = new RecordSet();
        rs.executeQuery("select yzbh from uf_yinzhang where id = ?",new Object[]{signid});
        rs.next();
        return Util.null2String(rs.getString("yzbh"));
    }

    /**
     * 取具体日期的后多少年日期
     * @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 "";
        }
    }

}
