package com.engine.htsc.jgxt.service.imp;

import cn.hutool.core.date.DateUtil;
import com.engine.core.impl.Service;
import com.engine.htsc.jgxt.service.JgxtDataToOtherService;
import com.engine.workflowDesign.entity.xmlEntity.Array;
import org.joda.time.DateTime;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetData;
import weaver.conn.RecordSetDataSource;
import weaver.general.Util;
import weaver.interfaces.htsc.GlobatTools.DBTools;
import weaver.interfaces.htsc.GlobatTools.HtmlUtil;
import weaver.interfaces.htsc.GlobatTools.JAVATools;
import weaver.interfaces.htsc.comInfo.PropBean;

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

/**
 * @author xf
 * @version 1.0.0
 * @ClassName JgxtDataToOtherServiceImp.java
 * @createTime 2021年11月10日 15:59:00
 */
public class JgxtDataToOtherServiceImp extends Service implements JgxtDataToOtherService {

    @Override
    public void innserotherdata(Map<String, Object> map) {
        PropBean propbean=new PropBean();
       String requestid= Util.null2String(map.get("requestid"));
       String tablename= Util.null2String(map.get("tablename"));
       if("".equals(requestid) || "".equals(tablename)){
           return ;
       }
       Map<String,String> mapreturn=new HashMap<>();
       String sql="select * from "+tablename+" where 1=1 ";
       Map<String,String> whereparams=new HashMap<>();
       whereparams.put("requestid",requestid);
       Map<String,Object> mapdata=JAVATools.GetTableToMap(sql,whereparams);

       mapreturn.put("flow_id",Util.null2String(mapdata.get("lcbh"))); //流程id
       //mapreturn.put("actreply_code",Util.null2String(mapdata.get("lcbh"))); //流程编号

        String hjlx=selectitem(Util.null2String(mapdata.get("hjlx")),tablename,"hjlx");
                //selectpublic(Util.null2String(mapdata.get("hjlx")),propbean.getPropName("JGXT_END_HJLX_CUBEUUID"));
       String hjly=selectitem(Util.null2String(mapdata.get("hjly")),tablename,"hjly");
               //selectpublic(Util.null2String(mapdata.get("hjly")),propbean.getPropName("JGXT_END_HJLY_CUBEUUID"));
       mapreturn.put("letter_type",hjlx); //函件类型
       mapreturn.put("letter_source",hjly); //函件来源
       mapreturn.put("letter_receive_date",Util.null2String(mapdata.get("hjjsrq")));
       mapreturn.put("require_reply_date",Util.null2String(mapdata.get("yqhhrq")));
       String hjnrvalue=HtmlUtil.Html2Text(Util.null2String(mapdata.get("hjnr")));
       String hjyqvalue= HtmlUtil.Html2Text(Util.null2String(mapdata.get("hjyq")));
        if("".equals(hjnrvalue) && hjnrvalue.length()>=300 ){
            hjnrvalue=hjnrvalue.substring(0,300);
        }

        if("".equals(hjyqvalue) && hjyqvalue.length()>=300 ){
            hjyqvalue=hjyqvalue.substring(0,300);
        }
       mapreturn.put("letter_content",hjnrvalue); //函件内容
       mapreturn.put("letter_require",hjyqvalue);//函件要求
       mapreturn.put("custom_name",Util.null2String(mapdata.get("hjsjdkhxm")));//客户姓名
       mapreturn.put("shareholder_account",Util.null2String(mapdata.get("hjsjdgdzh")));//股东账号
       //工资
       mapreturn.put("status","0"); //函件来源

       mapreturn.put("update_time", DateUtil.format( new Date(), "yyyy-MM-dd HH:mm:ss")); //跟新日期
       mapreturn.put("mark",selectitem(Util.null2String(mapdata.get("bd")),tablename,"bd")); //标的
       mapreturn.put("trading_limit",selectitem(Util.null2String(mapdata.get("xzjy")),tablename,"xzjy")); //限制交易xzsj
       mapreturn.put("time_limit",selectitem(Util.null2String(mapdata.get("xzsj")),tablename,"xzsj")); //限制时间
       mapreturn.put("abnormallist",selectitem(Util.null2String(mapdata.get("ycjyxw")),tablename,"ycjyxw")); //异常交易行为
       String occurrencedate="";

       if(!"".equals(Util.null2String(mapdata.get("ycjyxwfssj")))&&
          !"".equals(Util.null2String(mapdata.get("ycjyxwfssj2")))
       ){
           occurrencedate=Util.null2String(mapdata.get("ycjyxwfssj"))+"-"+Util.null2String(mapdata.get("ycjyxwfssj2"));
       }else if(!"".equals(Util.null2String(mapdata.get("ycjyxwfssj")))){
           occurrencedate=Util.null2String(mapdata.get("ycjyxwfssj"));
       }else if(!"".equals(Util.null2String(mapdata.get("ycjyxwfssj2")))){
           occurrencedate=Util.null2String(mapdata.get("ycjyxwfssj2"));

       }

       mapreturn.put("occurrencedate",occurrencedate); //限制时间
       mapreturn.put("noticewarningtime",Util.null2String(mapdata.get("jgtzsj"))); //限制时间
       mapreturn.put("recipient",JAVATools.getHrmName(Util.null2String(mapdata.get("jsrxm")))); //接收人姓名
       mapreturn.put("recipient_dept",getdeptname(Util.null2String(mapdata.get("jsrbm")))); //接收人部门
       mapreturn.put("recipientcode",JAVATools.gethrmidtoworkcode(Util.null2String(mapdata.get("jsrxm")))); //接收人部门
       mapreturn.put("recipientdeptcode",getdeptworkcode(Util.null2String(mapdata.get("jsrbm")))); //接收人部门
       mapreturn.put("draftername",JAVATools.getHrmName(Util.null2String(mapdata.get("ngr")))); //流程发起人姓名
       mapreturn.put("draftdate",Util.null2String(mapdata.get("ngrq"))); //流程发起时间
       //detail7

        mapreturn.put("warningpeople",""); //警示人姓名
        mapreturn.put("notice_cus_time",""); //警示客户时间
        mapreturn.put("measures_cus",""); //对客户采取的措施及备注说明
        mapreturn.put("feedback",""); //客户反馈


        mapreturn.put("endtime",DateUtil.format( new Date(), "yyyy-MM-dd HH:mm:ss")); //流程办结时间

        mapreturn.put("feedbackregulator",Util.null2String(mapdata.get("fkjgjgsj"))); //反馈监管机构时间
        mapreturn.put("feedbackname",JAVATools.getHrmName(Util.null2String(mapdata.get("fkrxm")))); //反馈人姓名
        mapreturn.put("actreplydate",""); //实际回函日期

        mapreturn.put("isoverdue",""); //是否超期
        mapreturn.put("replyquality",""); //回函质量

        mapreturn.put("remark",Util.null2String(mapdata.get("bz"))); //备注
        mapreturn.put("attch",getfilename(Util.null2String(mapdata.get("fj"))) ); //附件
        mapreturn.put("channel_service",""); //通道服务情况
//        String statussql = "select * from workflow_requestbase where requestid = " +requestid;
//        RecordSet rsStatus = new RecordSet();
//        rsStatus.execute(statussql);
//        while(rsStatus.next()){
//           String type = rsStatus.getString("CURRENTNODETYPE");
//           if(Objects.equals("3",type)){
//               mapreturn.put("workflow_status","正常结束"); //流程状态//进行中
//           }else{
//               mapreturn.put("workflow_status","进行中"); //流程状态//进行中
//           }
//        }
        mapreturn.put("workflow_status","进行中"); //流程状态//进行中
    //    mapreturn.put("drafter",JAVATools.getHrmName(Util.null2String(mapdata.get("ngr")))); //拟稿人
        mapreturn.put("drafter",JAVATools.gethrmidtoworkcode(Util.null2String(mapdata.get("ngr")))); //拟稿人工号

        mapreturn.put("drafterdept",getdeptname(Util.null2String(mapdata.get("szbm")))); //拟稿人部门
        mapreturn.put("draftertime",Util.null2String(DateUtil.format(DateUtil.parse(Util.null2String(mapdata.get("ngrq"))), "yyyy/MM/dd HH:mm:ss"))); //拟稿人日期
        mapreturn.put("shares",Util.null2String(mapdata.get("hjsjdgp"))); //股票
        String  sdbmlxvalue=Util.null2String(mapdata.get("sdbmlx"));
        String  sdbmvalue=Util.null2String(mapdata.get("sdbm"));
        String branch_dept="";
        String delivery_dept="";

        if("1".equals(sdbmlxvalue)){
            //插入分公司、营业部
          Map<String,Object> deptmap=  getsubdeptname(sdbmvalue);
           if(deptmap!=null && deptmap.size()>0){
               branch_dept=Util.null2String(deptmap.get("supdepname")).replace(",",";");
               delivery_dept=Util.null2String(deptmap.get("name")).replace(",",";");

           }
        }else{
           // branch_dept="华泰证券有限公司";
            branch_dept=new PropBean().getPropName("jgxt.othertodata.deptname");
            String deptsql = "select wm_concat_old(hd.departmentname)  as name from hrmdepartment hd where id in("+sdbmvalue+")";
            RecordSet deptrs = new RecordSet();
            deptrs.execute(deptsql);
            deptrs.next();


            delivery_dept=deptrs.getString("name").replace(",",";");
        }
        branch_dept=!"".equals(branch_dept)?branch_dept+";":branch_dept;
        delivery_dept=!"".equals(delivery_dept)?delivery_dept+";":delivery_dept;

        mapreturn.put("branch_dept",branch_dept); //分公司
        mapreturn.put("delivery_dept",delivery_dept); //营业部



//        innert(mapreturn);
        //12-13
        String xyxtid = (String) mapdata.get("xyxtid");
        String selectSql = "select * from " + tablename +" where xyxtid = '" + xyxtid + "'";
        JAVATools.SetCmdwritelog("selectSql = " + selectSql);
        RecordSet rs = new RecordSet();
        rs.execute(selectSql);
        if(rs.getCounts()>0){
            while(rs.next()){
                mapreturn.put("xyxtid",xyxtid);
                //下游系统存在则更新
                update(mapreturn);
            }
        }else{
            Integer innid = innert(mapreturn);
            if(innid != null && innid >0 ){
                String selectByUuid = "select * from " + tablename + " where  requestid = '" + requestid + "'";
                JAVATools.SetCmdwritelog("selectByUuidSql = " + selectByUuid);
                rs.execute(selectByUuid);
                while(rs.next()){
                    String id = rs.getString("id");
                    String updateById = "update " + tablename + " set xyxtid = " + innid +" where id = " + id ;
                    JAVATools.SetCmdwritelog("updateByIdSql = " + updateById);
                    rs.execute(updateById);
                }
            }
        }
    }
    private  void update(Map<String,String> map){
        String xyxtid =  map.get("xyxtid");
        map.remove("xyxtid");
        Set set = map.keySet();
        Iterator  iterable =  set.iterator();
        String sql = "update JGXTINFO set ";
        while(iterable.hasNext()) {
            String key = (String) iterable.next();
            String value = map.get(key);
            sql += " " + key + " = '" + value +"' , ";
        }
        sql = sql.substring(0,sql.lastIndexOf(",")) + " where id = " + xyxtid ;
        JAVATools.SetCmdwritelog("监管协同下游系统更新" + sql);
        RecordSetDataSource rs=new RecordSetDataSource("Jgxt");
//        rs.execute(sql);
        if(!rs.execute(sql)){
            JAVATools.SetCmdwritelog("监管协同下游系统更新失败" + sql);
        }
    }

    private  int innert(Map<String,String> map){
        if(map==null || map.size()<=0){
            return 0;
        }
        List<String> addlistkey =new ArrayList<>();
        List<String> valuelistkey =new ArrayList<>();
        for (String key:map.keySet()) {
            String value=Util.null2String(map.get(key));
            if(!"".equals(value)){
                addlistkey.add(key);
                valuelistkey.add("'"+value+"'");
            }
        }
       String keybody= addlistkey.stream().collect(Collectors.joining(","));
       String valuebody= valuelistkey.stream().collect(Collectors.joining(","));
        int id = getmaxid();
       String sql= "insert into JGXTINFO(id,"+keybody+") values("+id+","+valuebody+")";
        JAVATools.SetCmdwritelog("监管协同下游数据:");
        JAVATools.SetCmdwritelog(sql);
        RecordSetDataSource rsd=new RecordSetDataSource("Jgxt");
       if(!rsd.execute(sql)){
           JAVATools.SetCmdwritelog("监管协同下游数据写入失败");
           return 0;
       }
       return id;
    }


    //根据
    private String selectpublic(String value,String cebuuuid){
      String sql="select  rank() over (order by id )-1 id,name from mode_selectitempagedetail where mainid in (" +
              " select id from mode_selectitempage t where t.cubeuuid='"+cebuuuid+"')";
      List<Map<String,Object> > list= JAVATools.GetTableToListMap(sql,null);
      if(list==null || list.size()<=0){
          return "";
      }
        List<String> liststr=new ArrayList<>();
      List<String> valuearray= Arrays.stream(value.split(",")).collect(Collectors.toList());
      list.forEach((Map<String,Object> model)->{
          if(valuearray.contains(Util.null2String(model.get("id"))) ){
              liststr.add(Util.null2String(model.get("name")));
          }
      });
      if(liststr==null && liststr.size()<=0){
          return "";
      }else{
        return  liststr.stream().collect(Collectors.joining(","));
      }
    }

    private String selectitem(String value,String tablename,String fieldname  ){
        String sql=" select selectvalue as id,selectname from workflow_selectitem t where t.fieldid in ( " +
                "  select id from workflow_billfield t where t.billid in （ select id from workflow_bill where tablename='"+tablename+"' ） and rownum=1 and t.fieldname='"+fieldname+"' " +
                " )";
        List<Map<String,Object> > list= JAVATools.GetTableToListMap(sql,null);
        if(list==null || list.size()<=0){
            return "";
        }
        List<String> liststr=new ArrayList<>();
        List<String> valuearray= Arrays.stream(value.split(",")).collect(Collectors.toList());
        list.forEach((Map<String,Object> model)->{
            if(valuearray.contains(Util.null2String(model.get("id"))) ){
                liststr.add(Util.null2String(model.get("selectname")));
            }
        });
        if(liststr==null && liststr.size()<=0){
            return "";
        }else{
            return  liststr.stream().collect(Collectors.joining(","));
        }
    }

    private  String getfilename(String value){
        if("".equals(value)){
            return "";
        }
        String sql=" select  wm_concat_old(imagefilename) as name from docimagefile where docid in ("+value+") ";
        Map<String,Object > map=JAVATools.GetTableToMap(sql,null);
        if(map==null && map.size()<=0){
            return "";
        }
        return Util.null2String(map.get("name"));
    }


    private  String getdeptname(String value){
        if("".equals(value)){
            return "";
        }
        String sql="select  wm_concat_old(t.departmentmark) as deptnames from hrmdepartment t where t.id in ("+value+") ";
        Map<String,Object > map=JAVATools.GetTableToMap(sql,null);
        if(map==null && map.size()<=0){
            return "";
        }
        return Util.null2String(map.get("deptnames"));
    }

    private  String getdeptworkcode(String value){
        if("".equals(value)){
            return "";
        }
        String sql="select  wm_concat_old(t.departmentcode) as departmentcode from hrmdepartment t where t.id in ("+value+") ";
        Map<String,Object > map=JAVATools.GetTableToMap(sql,null);
        if(map==null && map.size()<=0){
            return "";
        }
        return Util.null2String(map.get("departmentcode"));
    }

    private  Map<String,Object>  getsubdeptname(String value){
        if("".equals(value)){
            return null;
        }
        Map<String,Object> deptreturn=new HashMap<>();

        String sql="select wm_concat_old( hd.departmentname) as name, wm_concat_old ( (select wm_concat_old(t.departmentname) from hrmdepartment  t where t.id=hd.supdepid)) as supdepname " +
                " from hrmdepartment hd join  hrmdepartmentdefined hdf on hd.id=hdf.deptid  where hd.id in (?) ";
        Map<String,Object > map= DBTools.getsqltomap(sql,value);
        if(map==null && map.size()<=0){
            return null;
        }
        deptreturn.put("name",Util.null2String(map.get("name")));
        deptreturn.put("supdepname",Util.null2String(map.get("supdepname")));

        return deptreturn;
    }

    public int getmaxid(){
      String sql="select JGXT_SEQ.nextval as id from dual where rownum = 1";
      int id=0;
      RecordSetDataSource rsd=new RecordSetDataSource("Jgxt");
      rsd.executeSql(sql);
       if(rsd.getCounts()>0){
           rsd.next();
           id= rsd.getInt("id");
       }
       return id;
    }

    public Map<String,Object> getdetailmap(String tablename,String requestid){
        String sql="select * from "+tablename+" t  where 1=1";
        Map<String,String> map=new HashMap<>();
        map.put("t.requestid",requestid);
        List list= JAVATools.GetTableToListMap(sql,map);
        if(list==null && list.size()<=0){
            return null;
        }
        return null;
    }



}

