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

import cc.smtweb.biz.mztb.web.base.*;
import cc.smtweb.biz.mztb.web.domian.*;
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.db.dao.EntityColumn;
import cc.smtweb.framework.core.db.impl.DefaultEntity;
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 {

    private String  buildInsertSql(String tableName, DefaultEntity entity) {
        entity.getData().remove("_def_table_name");
        StringJoiner key = new StringJoiner(",");
        StringJoiner value = new StringJoiner(",");
        StringBuilder sql = new StringBuilder();
        sql.append(" insert into ").append(tableName).append(" (");
        for (Map.Entry<String, Object> entry : entity.getData().entrySet()) {
            key.add(entry.getKey());
            value.add("'"+entry.getValue()+"'");
        }
        sql.append(key);
        sql.append(") values (");
        sql.append(value);
        sql.append(")");

        return sql.toString();
    }
    @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.forEach(temp -> {
            ids.add(temp.readString("fo_id"));
        });
        fillOutList.forEach(temp->{
            temp.remove("fo_update_at");
            PreFillOut preFillOut = new PreFillOut();
            preFillOut.getData().putAll(temp);
            String sql = buildInsertSql(PreFillOut.ENTITY_NAME, preFillOut);
            insertSql.add(sql);
        });
        List<SwMap> businessInfos = instance.query("select * from "+EntityHelper.getSchemaTableName(BusinessInfo.ENTITY_NAME)+ " where bi_fo_id in (" + String.join(",", ids) + ")",SwMap.class);
        if (businessInfos.size() !=0){
            businessInfos.forEach(temp->{
                temp.remove("bi_update_at");
                PreBusinessInfo preBusinessInfo = new PreBusinessInfo();
                preBusinessInfo.getData().putAll(temp);
                String sql = buildInsertSql(PreBusinessInfo.ENTITY_NAME, preBusinessInfo);
                insertSql.add(sql);
            });
        }

        List<SwMap> financeInfos = instance.query("select * from "+EntityHelper.getSchemaTableName(FinanceInfo.ENTITY_NAME)+" where fi_fo_id in (" + String.join(",", ids) + ")",SwMap.class);
        if (financeInfos.size() != 0){
            financeInfos.forEach(temp->{
                temp.remove("fi_update_at");
                PreFinanceInfo preFinanceInfo = new PreFinanceInfo();
                preFinanceInfo.getData().putAll(temp);
                String sql = buildInsertSql(PreFinanceInfo.ENTITY_NAME, preFinanceInfo);
                insertSql.add(sql);
            });
        }

        List<SwMap> yearEndPersons = instance.query("select * from "+EntityHelper.getSchemaTableName(YearEndPersons.ENTITY_NAME)+" where yep_fo_id in (" + String.join(",", ids) + ")",SwMap.class);
        if (yearEndPersons.size() != 0){
            yearEndPersons.forEach(temp->{
                temp.remove("yep_update_at");
                PreYearEndPersons preYearEndPersons = new PreYearEndPersons();
                preYearEndPersons.getData().putAll(temp);
                String sql = buildInsertSql(PreYearEndPersons.ENTITY_NAME, preYearEndPersons);
                insertSql.add(sql);
            });
        }

        Connection connection = null;
        try {
            connection = DriverManager.getConnection(dbSourceConfig.getWholeUrl(), dbSourceConfig.getUsername(), dbSourceConfig.getPassword());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (connection == null){
            throw new BizException("连接失败！");
        }
        boolean success =false;
        try {
            connection.setAutoCommit(false);
            try (Statement statement = connection.createStatement()) {
                for (String s : insertSql) {
                    statement.addBatch(s); // 添加到批处理中
                }
                int[] updateCounts = statement.executeBatch(); // 执行批处理
                if (updateCounts.length != insertSql.size()){
                    throw new BizException("数据数量异常");
                }
                connection.commit(); // 提交事务
                success = true;
            } catch (SQLException e) {
                e.printStackTrace();
                success = false;
                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();
            }
        }
        // 推送完成后修改填报机构的推送状态
        if(success) {
            instance.update("update "+EntityHelper.getSchemaTableName(FillOut.ENTITY_NAME) +" set fo_state = 2 where fo_id in ("+String.join(",",ids)+")");
        }
        return null;
    }


}
