package com.engine.htxc.cgglpt.service.impl;

import com.engine.core.impl.Service;
import com.engine.htxc.cgglpt.service.CgglptService;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.resource.ResourceComInfo;
import weaver.interfaces.htsc.GlobatTools.JAVATools;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.htxc.cgglpt.CheckComplete;
import weaver.soa.workflow.request.MainTableInfo;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestInfo;
import weaver.soa.workflow.request.RequestService;
import weaver.workflow.request.RequestComInfo;
import weaver.workflow.workflow.WorkflowComInfo;

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

public class CgglptServiceImpl extends Service implements CgglptService {
    @Override
    public boolean allowDelete(String ids) {
        RecordSet rs = new RecordSet();
        String sql = "select * from uf_cgxq where id ="+ids ;
        JAVATools.writelog("采购平台删除sql"+sql);
        rs.execute(sql);
        boolean flag = false;
        while(rs.next()){
            String zt = rs.getString("zt");
            if(Objects.equals("1",zt)){
                flag = true;
            }
        }
        if(flag){
            return flag;
        }else{
            String deleteSsql = "delete from uf_cgxq where id ="+ids;
            JAVATools.writelog("采购平台删除deleteSsql"+deleteSsql);
            rs.execute(deleteSsql);
            return flag;
        }
    }

    @Override
    public Boolean scrapPurchase(String id) {
        //select isstopped from workflow_requestbase  where isstopped is not null
        //select * from workflow_currentoperator where  requestid = 5788792 and iscomplete = 1
        RecordSet rs = new RecordSet();
        PropBean pb = new PropBean();
        String table = pb.getPropName("tycgsq_table");
        String tycgrwd= pb.getPropName("tycgrwd_tablename");
        Boolean acomplete = isComplete(table, id,"_dt4");
        Boolean bcomplete = isComplete(tycgrwd, id,"_dt5");
        JAVATools.writelog("废弃acomplete"+acomplete);
        JAVATools.writelog("废弃bcomplete"+bcomplete);
        if(acomplete || bcomplete ){
            return true;
        }else{
            String sql = " update uf_cgxq set zt = 2 where id ="+id;
            JAVATools.writelog("废弃sql"+sql);
            rs.execute(sql);
            return false;
        }

    }

    @Override
    public void recovery(String id) {
        RecordSet rs = new RecordSet();
        String sql = " update uf_cgxq set zt = 1 where id ="+id;
        JAVATools.writelog("采购平台恢复"+sql);
        rs.execute(sql);
    }

    @Override
    public boolean getWorkFlowByJmid(String billid) {
        RecordSet rs = new RecordSet();
        PropBean pb = new PropBean();
        String tycgsqTable = pb.getPropName("tycgsq_table");
        String tycgrwdTablename = pb.getPropName("tycgrwd_tablename");
        String tycgsqRequestid = getRequestidByBillId(tycgsqTable,Integer.parseInt(billid),"_dt4");
        JAVATools.writelog("校验发起招标请示的按钮tycgsqRequestid"+tycgsqRequestid);
        String tycgrwdRequestid = getRequestidByBillId(tycgrwdTablename,Integer.parseInt(billid),"_dt5");
        JAVATools.writelog("校验发起招标请示的按钮tycgrwdRequestid"+tycgrwdRequestid);
        CheckComplete check = new CheckComplete();
        if(check.isComplete(tycgsqRequestid)&&check.isComplete(tycgrwdRequestid)){
            return true;
        }else{
            return false;
        }

    }

    @Override
    public String triggerWorkflow(String userId,String billId) {
        RecordSet rs = new RecordSet();
        PropBean pb = new PropBean();
        String sql = "select * from  uf_cgxq where id = "+billId;
        rs.execute(sql);
        if(rs.next()){
            String xmmc = rs.getString("xmmc");
            String cgxmbh = rs.getString("xmbh");
            String cglb = rs.getString("xmlb");
            HashMap<String, String> map = new HashMap<>();
            map.put("cgxmmc",xmmc);
            map.put("cgxmbh",cgxmbh);
            map.put("cglb",cglb);
            map.put("cgxmc",billId);
            String requestNmae = "合同起草信息预设-"+xmmc;
            map.put("bt",requestNmae);
            map.put("ngr",userId);
            Map<String, String> hrm = getHrm(userId);
            map.put("szbm",hrm.get("departmentid"));
            map.put("szjg",hrm.get("supdepid"));
            map.put("jjcd","0");
            map.put("lxfs",hrm.get("phone"));
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            map.put("ngrq",format.format(new Date()));
            String htysxxWorkflowId = pb.getPropName("htysxxWorkflowId");//合同预设id
            String requestId = WorkflowCreateByRequestMap(userId, htysxxWorkflowId, requestNmae, "0", map);
            return requestId;
        }
        return "";

    }
    public Map<String,String> getHrm(String ngr){
        HashMap<String, String> result = new HashMap<>();
        RecordSet rs = new RecordSet();
        String hrmSql = "select * from hrmresource where id = "+ngr;
        rs.execute(hrmSql);
        rs.next();
        String departmentid = rs.getString("departmentid");
        result.put("phone",rs.getString("mobile"));
        result.put("departmentid",departmentid);
        String deptSql = "select * from hrmdepartment where id =  "+departmentid;
        rs.execute(deptSql);
        rs.next();
        result.put("supdepid",rs.getString("supdepid"));
        return result;
    }
    /**
     *
     * @Title: WorkflowCreateByMainTableMap
     * @param @param creatorId    创建人Id
     * @param @param workflowId   流程Id
     * @param @param requestName  请求标题
     * @param @param IsNextFlow   是否提交到下一节点
     * @param @param requestMap   Map格式的主表数据<fieldname,fieldvalue>=<字段名称,字段值>
     * @param @return    设定文件
     * @return String    返回类型
     * @throws
     */
    public String WorkflowCreateByRequestMap(String creatorId ,String workflowId ,String requestName ,String IsNextFlow,Map<String,String> requestMainMap)
    {
        BaseBean bs = new BaseBean();
        bs.writeLog("-----创建流程传递的参数个数--------");
        bs.writeLog("creatorId:"+creatorId);
        bs.writeLog("workflowId:"+workflowId);
        bs.writeLog("requestName:"+requestName);
        bs.writeLog("IsNextFlow:"+IsNextFlow);

        String requestid = "";
        RequestInfo requestInfo = new RequestInfo();
        requestInfo.setCreatorid(creatorId);//创建人Id
        requestInfo.setWorkflowid(workflowId);//工作流Id
        requestInfo.setDescription(requestName);//请求标题
        if(!"".equals(IsNextFlow))
        {
            requestInfo.setIsNextFlow(IsNextFlow);
        }

        //主表字段
        MainTableInfo mainTableInfo = new MainTableInfo();
        Property[] propertyArray = new Property[requestMainMap.size()];
        int p = 0;
        for (Map.Entry<String, String> entry : requestMainMap.entrySet())
        {
            propertyArray[p] = new Property();
            propertyArray[p].setName(Util.null2String(entry.getKey()));
            propertyArray[p].setValue(Util.null2String(entry.getValue()));
            bs.writeLog("\r\n---p="+p+"---Key="+entry.getKey()+"---Value="+entry.getValue());
            p++;
        }
        bs.writeLog("-----创建流程传递的参数个数p="+p);
        mainTableInfo.setProperty(propertyArray);
        requestInfo.setMainTableInfo(mainTableInfo);

        RequestService service = new RequestService();
        try {
            //流程
            try {
                requestid = service.createRequest(requestInfo);//创建请求id
            } catch (Exception e) {
                bs.writeLog("======="+e.getMessage());
            }
            //String userId = requestInfo.getLastoperator();//请求最后的操作者
            //记录日志
            StringBuffer sbf = new StringBuffer("\r\n-----xwd创建工作流记录日志开始");
            WorkflowComInfo wfcif =new WorkflowComInfo();
            RequestComInfo rcif = new RequestComInfo();
            ResourceComInfo rscif = new ResourceComInfo();
            sbf.append("\r\n-----姓名:"+rscif.getLastname(rcif.getRequestCreater(requestid)));
            sbf.append("\r\n-----时间:"+rcif.getRequestCreateTime(requestid));
            sbf.append("\r\n-----创建流程:"+wfcif.getWorkflowname(workflowId));
            sbf.append("\r\n-----请求:"+rcif.getRequestname(requestid));
            sbf.append("\r\n-----请求:"+requestid);
            sbf.append("\r\n-----创建工作流记录日志结束");
            bs.writeLog(sbf.toString());
            System.out.println(""+sbf.toString());
        } catch (Exception e) {
            bs.writeLog("错误：" + e);
            System.out.println("错误：" + e);
        }
        return requestid;
    }

    private String getRequestidByBillId(String table, int billid, String dt) {
        RecordSet rs = new RecordSet();
        String sql = "select * from  "+table+dt+" where xmid = "+billid;
        rs.execute(sql);
        if(rs.next()){
            String mainid = rs.getString("mainid");
            String mainSql = "select requestid from "+table+" where id = "+mainid;
            rs.execute(mainSql);
            if(rs.next()){
                return rs.getString("requestid");
            }
        }
        return "";
    }
    /**
     * 用来判断当前的流程是否有在途流程
     * @param table
     * @param id
     * @return
     */
    public Boolean isComplete(String table, String id,String dt) {
        RecordSet rs = new RecordSet();
        RecordSet mainRs = new RecordSet();
        RecordSet stopRs = new RecordSet();
        RecordSet completeRs = new RecordSet();
        String sql = "select * from "+table+dt+" where xmid = "+id;
        rs.execute(sql);
        ArrayList<String> list = new ArrayList<>();
        //这个flag用来判断是有流程，没有流程不可以废弃

        while(rs.next()){

            String mainid = rs.getString("mainid");
            String mainSql = "select * from " + table+ " where id = "+mainid;
            mainRs.execute(mainSql);
            mainRs.next();
            String requestid = mainRs.getString("requestid");
            String stopSql = "select a.isremark,a.iscomplete ,b.isstopped from workflow_currentoperator   a right join workflow_requestbase b " +
                    "on a.requestid = b.requestid  where  a.requestid = "+requestid;
            completeRs.execute(stopSql);
            ArrayList<Integer> completes = new ArrayList<>();
            while (completeRs.next()){
                String iscomplete = completeRs.getString("iscomplete");
                String isstopped = completeRs.getString("isstopped");
                if(Objects.equals(iscomplete,"1")){
                    completes.add(1);
                } else if(Objects.equals(isstopped,"1")){
                    completes.add(1);
                }else{
                    completes.add(0);
                }
            }
            List<Integer> collect = completes.stream().filter((item) -> {
                return item > 0;
            }).collect(Collectors.toList());
            if(collect.size()>0){
                list.add("1");
            }else{
                list.add("0");
            }

        }
        Iterator<String> iterator = list.iterator();
        while(iterator.hasNext()){
            String next = iterator.next();
            if(Objects.equals(next,"0")){
                return true;
            }
        }
//        if(!flag){
//            return true;
//        }else{
//            return false;
//        }
        return false;
    }

}
