
package com.engine.htsc.doc.cmd;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetDataSource;
import weaver.general.BaseBean;
import weaver.general.Util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 配置第三方数据源（拼接sql同步数据）
 */
public class DataSourceCmd {

    private RecordSet rs = new RecordSet();
    private BaseBean bb = new BaseBean();


    /**
     * --关闭触发器 --开启 enable
     * alter
     *     table
     *     UF_GWKY disable
     *     all
     *     triggers;
     *
     *     UF_GWKY_DT4 disable
     *     UF_GWKY_DT7 disable
     * @param params
     * @return
     */
    public Map<String, Object> copyTableDatas(String params) {
        Map<String, Object> resultMap = new HashMap<>();
        RecordSetDataSource rsd = new RecordSetDataSource("eipsit");
        bb.writeLog("copyTableDatas params:"+params);
        try {
            //关闭触发器
            controlTrriger("disable");

            JSONObject datajson = JSONObject.parseObject(params);
            List<String> docList = (List<String>)datajson.get("docsList");
            String requestId = (String)datajson.get("requestId");
            //1.更新建模表
            Integer id = null;
            rsd.execute("select id from UF_GWKY where requestid ="+requestId);
            if (rsd.next()) {
                id = Util.getIntValue(rsd.getString("id"));
            }
            //主表uf_gwky uf_syjl
            rs.executeUpdate("delete from uf_gwky where requestid = ?",requestId);
            syncTableData("select * from uf_gwky where requestid ="+requestId,"uf_gwky");
            //rs.executeUpdate("delete from uf_syjl where requestid = ?",requestId);
            //syncTableData("select * from uf_syjl where requestid ="+requestId,"uf_syjl");

            //明细表4
            bb.writeLog("copyTableDatas id",+id);
            if (id != null) {
                rs.executeUpdate("delete from uf_gwky_dt4 where mainid = ?",id);
                syncTableData("select * from uf_gwky_dt4 where mainid ="+id,"uf_gwky_dt4");
            }
            bb.writeLog("copyTableDatas 建模数据同步成功");

            //2.更新文档表
            docList.forEach(docid -> {
                bb.writeLog("copyTableDatas 需同步的文档id:"+docid);
                if (StringUtils.isNotEmpty(docid)){
                    try {
                        //1.同步docdetail
                        rs.executeUpdate("delete from docdetail where id = ?",docid);
                        syncTableData("select * from docdetail where id ="+docid,"docdetail");

                        //2.同步docimagefile
                        rsd.execute("select id from docimagefile where docid ="+docid);
                        rsd.next();
                        rs.executeUpdate("delete from docimagefile where id = ?", Util.getIntValue(rsd.getString("id")));
                        rs.executeUpdate("delete from docimagefile where docid = ?",docid);
                        syncTableData("select * from docimagefile where docid ="+docid,"docimagefile");

                        //3.同步imagefile
                        rsd.execute("select imagefileid from docimagefile where docid ="+docid);
                        while (rsd.next()){
                            String imagefileid = Util.null2String(rsd.getString("imagefileid"));
                            bb.writeLog("Docid对应Imagefileiid"+imagefileid);
                            rs.executeUpdate("delete from imagefile where imagefileid = ?",imagefileid);
                            syncTableData("select * from imagefile where imagefileid ="+imagefileid,"imagefile");
                        }

                        //4.同步docshare
                        rsd.execute("select id from docshare where docid ="+docid);
                        rsd.next();
                        rs.executeUpdate("delete from docshare where id = ?", Util.getIntValue(rsd.getString("id")));
                        rs.executeUpdate("delete from docshare where docid = ?",docid);
                        syncTableData("select * from docshare where docid ="+docid,"docshare");

                        //5.同步shareinnerdoc
                        rsd.execute("select id from shareinnerdoc where sourceid ="+docid);
                        rsd.next();
                        rs.executeUpdate("delete from shareinnerdoc where id = ?", Util.getIntValue(rsd.getString("id")));
                        rs.executeUpdate("delete from shareinnerdoc where sourceid = ?",docid);
                        syncTableData("select * from shareinnerdoc where sourceid ="+docid,"shareinnerdoc");

                    }catch (Exception e){
                        bb.writeLog(" copyTableDatas DbLink更新文档表失败");
                        e.printStackTrace();
                    }

                }
            });

            resultMap.put("status",200);
            //开启触发器
            controlTrriger("enable");
        }catch (Exception e){
            resultMap.put("status",500);
            e.getMessage();
            e.printStackTrace();
        }
        return resultMap;
    }


    /**
     * 同步表数据
     * @param dataSql
     * @param tableName
     */
    public void syncTableData(String dataSql,String tableName){
        RecordSetDataSource rsd = new RecordSetDataSource("eipsit");
        rsd.execute(dataSql);
        String[] columnNames =  rsd.getColumnName();
        int count = rsd.getCounts();

        if(count>0){
            StringBuffer sb =  new StringBuffer();
            sb.append("insert into ").append(tableName).append(" values(");
            String split ="";
            for (int i = 0; i <columnNames.length ; i++) {
                sb.append(split).append("?");
                split=",";
            }
            sb.append(")");
            String insertSql = sb.toString();

            while(rsd.next()){
                List<String> values = new ArrayList<>();
                for (String columnName:columnNames) {
                    String columnValue = rsd.getString(columnName);
                    values.add(columnValue);
                }
                rs.executeUpdate(insertSql,values);
            }
        }
    }


    /**
     * 控制触发器开启与关闭
     * @param finalOperation
     */
    public void controlTrriger(String finalOperation){
        RecordSet rs = new RecordSet();
        List<String> tableList = Stream.of("uf_gwky","uf_gwky_dt4","docdetail",
                "docimagefile","imagefile","docshare","shareinnerdoc").collect(Collectors.toList());

        tableList.forEach(tablename -> {
            bb.writeLog("alter table "+tablename+" "+ finalOperation +" all triggers");
            rs.executeUpdate("alter table "+tablename+" "+ finalOperation +" all triggers");
        });
    }


}
