package com.engine.htsc.receipt.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.core.impl.Service;
import com.engine.htsc.workflow.util.WorkflowUtil;
import com.weaver.general.Util;
import org.apache.commons.lang.StringUtils;
import weaver.conn.RecordSet;
import weaver.docs.docs.DocManager;
import weaver.general.BaseBean;
import weaver.hrm.company.DepartmentComInfo;
import weaver.interfaces.htsc.GlobatTools.JAVATools;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.htsc.cus.HTUtil;

import java.text.SimpleDateFormat;
import java.util.*;

public class ReceiptService extends Service {

    /**
     * 复制无水印附件
     * @param userid
     * @param docids
     * @param oldPair
     * @param type
     * @return
     */
    public Map<String,Object> getCopyDocid(String userid, String docids, String oldPair, String type){
        BaseBean bs = new BaseBean();
        PropBean pb = new PropBean();
        RecordSet rs = new RecordSet();
        Map<String,Object> resultMap = new HashMap<>();

        try{
            List<Map<String,String>> pairMapList = new ArrayList<>();
            List<Map<String,String>> filenameMapList = new ArrayList<>();
            JSONArray jsonArray = JSONObject.parseArray(oldPair);
            String gssw_fj_secid = pb.getPropName("gssw_fj");
            String gssw_wsyfj_secid = pb.getPropName("gssw_wsyfj");

            for(String docid:docids.split(",")){
                bs.writeLog("docid:"+docid);
                String imgfileName = "";
                String sql = "select imagefilename from docimagefile where docid = '"+docid+"'";
                bs.writeLog(sql);
                rs.executeQuery(sql);
                if(rs.next()){
                    imgfileName = Util.null2String(rs.getString("imagefilename"));
                }

                if(StringUtils.isNotEmpty(imgfileName)){
                    bs.writeLog("imgfileName:"+imgfileName);
                    String pairDocid = "";
                    if("1".equals(type)){//附件到无水印附件
                        boolean flag = false;
                        if(jsonArray.size()>0){
                            for(int i=0;i<jsonArray.size();i++){
                                String fjDocid = jsonArray.getJSONObject(i).getString("fjDocid");
                                String wsyfjDocid = jsonArray.getJSONObject(i).getString("wsyfjDocid");
                                if(docid.equals(fjDocid)){
                                    bs.writeLog("wsyfjDocid:"+wsyfjDocid);
                                    pairDocid = wsyfjDocid;
                                    flag = true;
                                    break;
                                }
                            }
                        }
                        if(!flag){
                            DocManager docmanager = new DocManager();
                            docmanager.setId(Integer.parseInt(docid));
                            docmanager.setSeccategory(Integer.parseInt(gssw_wsyfj_secid));
                            docmanager.setDocsubject(imgfileName);
                            docmanager.setUserid(Integer.parseInt(userid));
                            docmanager.setUsertype("1");
                            docmanager.setDoccreaterid(Integer.parseInt(userid));
                            int newdocid = docmanager.copyDoc();
                            bs.writeLog("newdocid:"+newdocid);
                            pairDocid = String.valueOf(newdocid);
                        }
                        Map<String,String> pairMap = new HashMap<>();
                        pairMap.put("fjDocid",docid);
                        pairMap.put("wsyfjDocid",pairDocid);
                        pairMapList.add(pairMap);
                        Map<String,String> filenameMap = new HashMap<>(pairMap);
                        filenameMap.put("imgfileName",imgfileName);
                        filenameMapList.add(filenameMap);
                    }else if("2".equals(type)){//无水印附件到附件
                        boolean flag = false;
                        if(jsonArray.size()>0){
                            for(int i=0;i<jsonArray.size();i++){
                                String fjDocid = jsonArray.getJSONObject(i).getString("fjDocid");
                                String wsyfjDocid = jsonArray.getJSONObject(i).getString("wsyfjDocid");
                                if(docid.equals(wsyfjDocid)){
                                    bs.writeLog("fjDocid:"+fjDocid);
                                    pairDocid = fjDocid;
                                    flag = true;
                                    break;
                                }
                            }
                        }
                        if(!flag){
                            DocManager docmanager = new DocManager();
                            docmanager.setId(Integer.parseInt(docid));
                            docmanager.setSeccategory(Integer.parseInt(gssw_fj_secid));
                            docmanager.setDocsubject(imgfileName);
                            docmanager.setUserid(Integer.parseInt(userid));
                            docmanager.setUsertype("1");
                            docmanager.setDoccreaterid(Integer.parseInt(userid));
                            int newdocid = docmanager.copyDoc();
                            bs.writeLog("newdocid:"+newdocid);
                            pairDocid = String.valueOf(newdocid);
                        }
                        Map<String,String> pairMap = new HashMap<>();
                        pairMap.put("fjDocid",pairDocid);
                        pairMap.put("wsyfjDocid",docid);
                        pairMapList.add(pairMap);
                        Map<String,String> filenameMap = new HashMap<>(pairMap);
                        filenameMap.put("imgfileName",imgfileName);
                        filenameMapList.add(filenameMap);
                    }
                }else{
                    resultMap.put("status",false);
                    resultMap.put("error","没有找到对应文件:"+docid);
                    return resultMap;
                }
            }

            bs.writeLog("pairMapList:"+JSON.toJSONString(pairMapList));
            bs.writeLog("filenameMapList:"+JSON.toJSONString(filenameMapList));
            resultMap.put("status",true);
            resultMap.put("pairMapList", pairMapList);
            resultMap.put("filenameMapList", filenameMapList);

        }catch (Exception e){
            e.printStackTrace();
            resultMap.put("status",false);
            resultMap.put("error","复制文件失败");
            return resultMap;
        }

        return resultMap;
    }


    /**
     * 刷新无水印附件历史数据
     * @param requestids
     * @return
     */
    public Map<String,Object> copyAllFile(String requestids){
        BaseBean bs = new BaseBean();
        PropBean pb = new PropBean();
        RecordSet rs = new RecordSet();
        Map<String,Object> resultMap = new HashMap<>();
        List<String> successList = new ArrayList<>();
        List<String> failList = new ArrayList<>();

        try{
            String workflowid = pb.getWorkflowIdsByUnNumber("gssw");
            String gssw_wsyfj_secid = pb.getPropName("gssw_wsyfj");
            HTUtil ht = new HTUtil();
            String tablename = ht.getTableNameByWfid(Integer.parseInt(workflowid));

            List<String> requestidList = new ArrayList<>();
            if(StringUtils.isNotEmpty(requestids)){
                requestidList = Arrays.asList(requestids.split(","));
            }else {
                String sql = "select requestid from workflow_requestbase where workflowid = '"+workflowid+"'";
                bs.writeLog(sql);
                rs.executeQuery(sql);
                while (rs.next()){
                    requestidList.add(Util.null2String(rs.getString("requestid")));
                }
            }

            for(String requestid:requestidList){
                try{
                    String fj = "";
                    String sql = "select fj from "+tablename+" where requestid = '"+requestid+"'";
                    bs.writeLog(sql);
                    rs.executeQuery(sql);
                    if(rs.next()){
                        fj = Util.null2String(rs.getString("fj"));
                    }

                    if(StringUtils.isNotEmpty(fj)){
                        List<String> wsyfjidList = new ArrayList<>();
                        List<Map<String,String>> pairMapList = new ArrayList<>();
                        for(String docid:fj.split(",")){
                            bs.writeLog("docid:"+docid);
                            String imgfileName = "";
                            String operateuserid = "";
                            sql = "select imagefilename,operateuserid from docimagefile where docid = '"+docid+"'";
                            bs.writeLog(sql);
                            rs.executeQuery(sql);
                            if(rs.next()){
                                imgfileName = Util.null2String(rs.getString("imagefilename"));
                                operateuserid = Util.null2String(rs.getString("operateuserid"));
                            }

                            if(StringUtils.isNotEmpty(imgfileName)) {
                                bs.writeLog("imgfileName:"+imgfileName);
                                DocManager docmanager = new DocManager();
                                docmanager.setId(Integer.parseInt(docid));
                                docmanager.setSeccategory(Integer.parseInt(gssw_wsyfj_secid));
                                docmanager.setDocsubject(imgfileName);
                                docmanager.setUserid(Integer.parseInt(operateuserid));
                                docmanager.setUsertype("1");
                                docmanager.setDoccreaterid(Integer.parseInt(operateuserid));
                                int newdocid = docmanager.copyDoc();
                                bs.writeLog("newdocid:"+newdocid);
                                String pairDocid = String.valueOf(newdocid);
                                wsyfjidList.add(pairDocid);

                                Map<String,String> pairMap = new HashMap<>();
                                pairMap.put("fjDocid",docid);
                                pairMap.put("wsyfjDocid",pairDocid);
                                pairMapList.add(pairMap);
                            }
                        }

                        bs.writeLog("wsyfjidList:"+JSON.toJSONString(wsyfjidList));
                        bs.writeLog("pairMapList:"+JSON.toJSONString(pairMapList));
                        String wsyfj = org.apache.commons.lang3.StringUtils.join(wsyfjidList, ",");
                        String ppxx = JSON.toJSONString(pairMapList);
                        String update_sql = "update "+tablename+" set wsyfj = '"+wsyfj+"', ppxx = '"+ppxx+"' where requestid = '"+requestid+"'";
                        bs.writeLog(update_sql);
                        rs.executeUpdate(update_sql);
                        successList.add(requestid);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    failList.add(requestid);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            resultMap.put("status",false);
            resultMap.put("error","复制文件失败");
            return resultMap;
        }

        resultMap.put("successList",successList);
        resultMap.put("failList",failList);
        return resultMap;
    }

    public Map<String,Object> refreshInfo(String requestids){
        BaseBean bs = new BaseBean();
        PropBean pb = new PropBean();
        RecordSet rs = new RecordSet();
        Map<String,Object> resultMap = new HashMap<>();
        List<String> successList = new ArrayList<>();
        List<String> failList = new ArrayList<>();

        try{
            String workflowid = pb.getWorkflowIdsByUnNumber("gssw");
            HTUtil ht = new HTUtil();
            String tablename = ht.getTableNameByWfid(Integer.parseInt(workflowid));

            List<String> requestidList = new ArrayList<>();
            if(StringUtils.isNotEmpty(requestids)){
                requestidList = Arrays.asList(requestids.split(","));
            }else {
                String sql = "select requestid from workflow_requestbase where workflowid = '"+workflowid+"'";
                bs.writeLog(sql);
                rs.executeQuery(sql);
                while (rs.next()){
                    requestidList.add(Util.null2String(rs.getString("requestid")));
                }
            }

            for(String requestid:requestidList){
                try{
                    String mainid = "";
                    String sql = "select id from "+tablename+" where requestid = '"+requestid+"'";
                    bs.writeLog(sql);
                    rs.executeQuery(sql);
                    if(rs.next()){
                        mainid = Util.null2String(rs.getString("id"));
                    }

                    //主办部门领导
                    String zbbmld = "";
                    sql = "select bmld from "+tablename+"_dt6 where mainid = '"+mainid+"'";
                    bs.writeLog(sql);
                    rs.executeQuery(sql);
                    if(rs.next()){
                        zbbmld = Util.null2String(rs.getString("bmld"));
                    }

                    //协办部门人员
                    String xbbmry = "";
                    List<String> xbbmryList = new ArrayList<>();
                    sql = "select bmld from "+tablename+"_dt8 where mainid = '"+mainid+"'";
                    bs.writeLog(sql);
                    rs.executeQuery(sql);
                    while(rs.next()){
                        xbbmryList.add(Util.null2String(rs.getString("bmld")));
                    }
                    if(xbbmryList.size()>0){
                        xbbmry = StringUtils.join(xbbmryList,",");
                    }

                    //看阅部门人员
                    String kybmry = "";
                    List<String> kybmryList = new ArrayList<>();
                    sql = "select bmld from "+tablename+"_dt10 where mainid = '"+mainid+"'";
                    bs.writeLog(sql);
                    rs.executeQuery(sql);
                    while(rs.next()){
                        kybmryList.add(Util.null2String(rs.getString("bmld")));
                    }
                    if(kybmryList.size()>0){
                        kybmry = StringUtils.join(kybmryList,",");
                    }

                    String update_sql = "update "+tablename+" set zbbmld = '"+zbbmld+"', xbbmry = '"+xbbmry+"', kybmry = '"+kybmry+"' where requestid = '"+requestid+"'";
                    bs.writeLog(update_sql);
                    rs.executeUpdate(update_sql);

                    //更新子流程数据
                    List<String> subRequestidList = new ArrayList<>();
                    sql = "select subrequestid from WORKFLOW_SUBWFREQUEST where mainrequestid = '"+requestid+"'";
                    bs.writeLog(sql);
                    rs.executeQuery(sql);
                    while(rs.next()){
                        subRequestidList.add(Util.null2String(rs.getString("subrequestid")));
                    }
                    for(String subRequestid:subRequestidList) {
                        String subTablename = JAVATools.getMaintable(subRequestid);
                        update_sql = "update " + subTablename + " set zbbmld = '" + zbbmld + "', xbbmry = '" + xbbmry + "', kybmry = '" + kybmry + "' where requestid = '" + subRequestid + "'";
                        bs.writeLog(update_sql);
                        rs.executeUpdate(update_sql);
                    }

                    successList.add(requestid);
                }catch (Exception e){
                    e.printStackTrace();
                    failList.add(requestid);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            resultMap.put("status",false);
            resultMap.put("error","刷新失败");
            return resultMap;
        }

        resultMap.put("successList",successList);
        resultMap.put("failList",failList);
        return resultMap;
    }

    public String updateDeptName(String requestid, String ids, String spDeptid, String spDeptName, String startTime){
        BaseBean bs = new BaseBean();
        RecordSet rs = new RecordSet();
        RecordSet rs1 = new RecordSet();
        RecordSet rs2 = new RecordSet();

        try {
            DepartmentComInfo departmentComInfo = new DepartmentComInfo();
            String tableName = JAVATools.getMaintable(requestid);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

            String sql = "select t1.id,t1.fsbm,t1.bm,t2.ngrq from "+tableName+"_dt11 t1, "+tableName+" t2 where t2.id = t1.mainid";
            if (StringUtils.isNotBlank(ids)) {
                sql += " and t1.id in (" + ids + ")";
            }
            bs.writeLog(sql);
            rs.executeQuery(sql);
            while (rs.next()) {
                String id = Util.null2String(rs.getString("id"));
                String fsbm = Util.null2String(rs.getString("fsbm"));
                String bm = Util.null2String(rs.getString("bm"));
                String ngrq = Util.null2String(rs.getString("ngrq"));
                if (StringUtils.isNotBlank(fsbm) && StringUtils.isBlank(bm)) {
                    List<String> deptNameList = new ArrayList<>();
                    for (String deptid : fsbm.split(",")) {
                        String showName = "";
                        if(deptid.equals(spDeptid)&&(StringUtils.isBlank(startTime)||sdf.parse(ngrq).before(sdf.parse(startTime)))){
                            showName = spDeptName;
                        }else{
                            showName = departmentComInfo.getDepartmentname(deptid);
                        }
                        String orgid = "";
                        sql = " select l.id from (select t.id from HrmDepartment t where t.supdepid is null or t.supdepid = 0 start with t.id=" + deptid + " connect by prior t.supdepid=t.id ) l";
                        rs1.execute(sql);
                        if (rs1.next()) {
                            orgid = com.weaver.general.Util.null2String(rs1.getString("id"));
                        }
                        if (!deptid.equals(orgid)) {
                            String orgName = WorkflowUtil.getTopDeptShortName(orgid);
                            showName = showName + "(" + orgName + ")";
                        }
                        deptNameList.add(showName);
                    }
                    String deptNameStr = String.join(" ", deptNameList);

                    String update_sql = "update " + tableName + "_dt11 set bm = '" + deptNameStr + "' where id = '" + id + "'";
                    bs.writeLog(update_sql);
                    rs2.executeUpdate(update_sql);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            return "error";
        }
        return "success";
    }
}
