package cc.smtweb.biz.mztb.web.task;

import cc.smtweb.biz.mztb.web.base.*;
import cc.smtweb.biz.mztb.web.tool.DbUtil;
import cc.smtweb.framework.core.common.SwMap;
import cc.smtweb.framework.core.db.DbEngine;
import cc.smtweb.framework.core.db.EntityHelper;
import cc.smtweb.framework.core.exception.BizException;
import cc.smtweb.system.bpm.web.sys.base.job.BaseJob;

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

public class PushTask extends BaseJob {
    @Override
    protected String work() {
        DbEngine instance = DbEngine.getInstance();
        //获取前置库配置
        DbSourceConfig dbSourceConfig = instance.findDao(DbSourceConfig.class).queryEntityWhere("dsc_use_state=0");
        if (dbSourceConfig == null) {
            throw new BizException("请先进行前置库配置");
        }

        // 查询已确认 还未推送的数据
        List<String> insertSql = new ArrayList<>();
        List<SwMap> fillOutList = instance.query("select * from "+ EntityHelper.getSchemaTableName(FillOut.ENTITY_NAME)+ " where fo_state = 1 ",SwMap.class);
        if (fillOutList.size() == 0) {
            return null;
        }
        List<String> ids = new ArrayList<>();
        fillOutList.stream().forEach(temp -> {
            ids.add(String.valueOf(temp.readLong("fo_id")));
        });
        fillOutList.forEach(temp->{
            List<String> fields = new LinkedList<>();
            List<String> value = new LinkedList<>();
            for (String s : temp.keySet()) {
                fields.add(s);
                if (s.equals("fo_id")){
                    value.add(String.valueOf(instance.nextId()));
                    value.add(temp.readString(s));
                }
            }
            insertSql.add("insert into tb_fill_out ("+fields.stream().collect(Collectors.joining(","))+") VALUES ("+value.stream().collect(Collectors.joining(","))+")");

        });

//        List<BusinessInfo> businessInfos = instance.findDao(BusinessInfo.class).queryWhere("bi_fo_id in (" + ids.stream().collect(Collectors.joining(",")) + ")");
//        Map<Long, BusinessInfo> businessInfoMap = new HashMap<>();
//        if (businessInfos.size() != 0) {
//            businessInfos.forEach(temp -> {
//                businessInfoMap.put(temp.getFoId(), temp);
//            });
//        }
        List<SwMap> businessInfos = instance.query("select * from "+EntityHelper.getSchemaTableName(BusinessInfo.ENTITY_NAME)+ " where bi_fo_id in (" + ids.stream().collect(Collectors.joining(",")) + ")",SwMap.class);
        if (businessInfos.size() !=0){
            businessInfos.forEach(temp->{
                List<String> fields = new LinkedList<>();
                List<String> value = new LinkedList<>();
                for (String s : temp.keySet()) {
                    fields.add(s);
                    value.add(temp.readString(s));
                }
                insertSql.add("insert into tb_business_info ("+fields.stream().collect(Collectors.joining(","))+") VALUES ("+value.stream().collect(Collectors.joining(","))+")");
            });
        }
        List<SwMap> financeInfos = instance.query("select * from "+EntityHelper.getSchemaTableName(FinanceInfo.ENTITY_NAME)+" where fi_fo_id in (" + ids.stream().collect(Collectors.joining(",")) + ")",SwMap.class);
        if (financeInfos.size() != 0){
            financeInfos.forEach(temp->{
                List<String> fields = new LinkedList<>();
                List<String> value = new LinkedList<>();
                for (String s : temp.keySet()) {
                    fields.add(s);
                    value.add(temp.readString(s));
                }
                insertSql.add("insert into tb_finance_info ("+fields.stream().collect(Collectors.joining(","))+") VALUES ("+value.stream().collect(Collectors.joining(","))+")");
            });
        }


        List<SwMap> yearEndPersons = instance.query("select * from "+EntityHelper.getSchemaTableName(YearEndPersons.ENTITY_NAME)+" where yep_fo_id in (" + ids.stream().collect(Collectors.joining(",")) + ")",SwMap.class);
        if (yearEndPersons.size() != 0){
            yearEndPersons.forEach(temp->{
                List<String> fields = new LinkedList<>();
                List<String> value = new LinkedList<>();
                for (String s : temp.keySet()) {
                    fields.add(s);
                    value.add(temp.readString(s));
                }
                insertSql.add("insert into tb_year_end_persons ("+fields.stream().collect(Collectors.joining(","))+") VALUES ("+value.stream().collect(Collectors.joining(","))+")");
            });
        }


        Connection connection = null;
        try {
            connection = DriverManager.getConnection(dbSourceConfig.getWholeUrl(), dbSourceConfig.getUsername(), dbSourceConfig.getPassword());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (connection == null){
            throw new BizException("连接失败！");
        }
        try {
            connection.setAutoCommit(false);
            try (Statement statement = connection.createStatement()) {
                for (int i = 0; i <insertSql.size(); i++) {
                    statement.addBatch(insertSql.get(i)); // 添加到批处理中
                }
                int[] updateCounts = statement.executeBatch(); // 执行批处理
                if (updateCounts.length != insertSql.size()){
                    throw new BizException("数据数量异常");
                }
                connection.commit(); // 提交事务
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
                try {
                    connection.rollback(); // 回滚事务
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                connection.setAutoCommit(true); // 重新开启自动提交
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


}
