package com.liquidnet.service.platform.service.impl.adam.dm.processor;

import com.liquidnet.service.adam.dto.vo.AdamEntersVo;
import com.liquidnet.service.adam.entity.AdamEnters;
import com.liquidnet.service.platform.service.impl.adam.dm.DMEntersService;
import com.liquidnet.service.platform.service.impl.adam.dm.DataMigrationProcessorService;
import com.mysql.cj.jdbc.result.ResultSetImpl;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class DMEntersProcessor extends DataMigrationProcessorService {
    @Autowired
    DMEntersService dmEntersService;

    @SneakyThrows
    @Override
    public void dataProcessing(Integer dg, Integer dG, String incrDt, String flg, String flu) {
        if (StringUtils.isNotEmpty(flu)) {
            log.info("DM.flush.enters:{}", userMapper.executeForDM("adam_enters"));

//            log.info("DM.flush.AdamEntersVo:{}", mongoTemplate.remove(Query.query(Criteria.where("_id").exists(true)), AdamEntersVo.class.getSimpleName()).getDeletedCount());
        }

        String sqlCount = "select count(1) from (" +
                "                  select row_number() over (partition by user_id,type,idcode,name order by updated_at desc) rn,e.* from enters e where e.is_certification = 'yes' and e.deleted_at is null and created_at" + (StringUtils.isBlank(incrDt) ? "<curdate()" : (">=curdate()-" + incrDt)) +
                "                  ) tk where tk.rn=1 ";
        if (null != dg) {
            sqlCount = sqlCount + " and id%" + dG + "=" + dg;
        }
        String field = "id,user_id,type,`name`,mobile,idcode,if(is_default='no', 0, 1),created_at,updated_at";
//                     1-id,2-user_id,3-type,4-`name`,5-mobile,6-idcode,7-if(is_default='no', 0, 1),8-created_at,9-updated_at
        String sql = sqlCount.replace("count(1)", field);
        boolean smFlg = "1".equals(flg);
        if (smFlg) {
            sqlCount += " and user_id in (" + DG_UID + ")";
            sql += " and user_id in (" + DG_UID + ")";
        }
        sql += " order by id limit ?,?";

        Connection connection = null;
        PreparedStatement statement = null;
        ResultSetImpl row = null;
        try {
            Class.forName(DB_DRIVER);
            connection = DriverManager.getConnection(DB_URL + DB_NAME_MALL, DB_USER, DB_PWD);
            statement = connection.prepareStatement(sqlCount);
            row = (ResultSetImpl) statement.executeQuery();
            row.first();
            int ct = row.getInt(1), pSize = 3000, num = 0, tl = 0, pl = ct;
            log.info("DM.execute.counts:{}/{},{} ~ {} ----------------------------> start.sql:{}", pl, num, pSize, tl, sql);

            row.close();
            statement.close();
            while (ct > 0) {
                statement = connection.prepareStatement(sql);
                int ls = pSize * num;
                statement.setInt(1, ls);
                statement.setInt(2, pSize);
                row = (ResultSetImpl) statement.executeQuery();
                log.info("DM.execute.limit {},{} - begin", ls, pSize);

                List<AdamEnters> entersList = new ArrayList<>();
                List<AdamEntersVo> vos = new ArrayList<>();
                while (row.next()) {
                    String uid = row.getString(2);
                    if (!reUidList.contains(uid)) {
                        AdamEnters enters = new AdamEnters();
                        enters.setEntersId(row.getString(1));
                        enters.setUid(uid);
                        enters.setType(row.getInt(3));
                        enters.setName(row.getString(4));
                        enters.setMobile(row.getString(5));
                        enters.setIdCard(row.getString(6));
                        enters.setIsDefault(row.getBoolean(7));
                        enters.setState(1);
                        enters.setCreatedAt(row.getLocalDateTime(8));
                        enters.setUpdatedAt(row.getLocalDateTime(9));

                        AdamEntersVo vo = AdamEntersVo.getNew().copy(enters);

                        entersList.add(enters);
                        vos.add(vo);

                        if (enters.getType() == 1) {
                            dmRdmService.setCertification(1, enters.getIdCard(), enters.getName());
                        }
                        dmRdmService.addEntersVoByUid(uid, dmRdmService.getEntersVoByUid(uid), vo);
                    }
                    if (entersList.size() == 1000 || (entersList.size() > 0 && smFlg) || ct <= 1000) {
                        tl += entersList.size();
//                        mongoTemplate.insert(vos, AdamEntersVo.class.getSimpleName());
                        log.info("DM.execute.limit.result:{}", dmEntersService.saveBatch(entersList));
                        vos.clear();
                        entersList.clear();
                    }
                }
                if (entersList.size() > 0) {
                    tl += entersList.size();
                    log.info("DM.execute.limit.result:{}", dmEntersService.saveBatch(entersList));
                }
                row.close();
                statement.close();

                num++;
                ct -= pSize;

                log.info("DM.execute.limit {},{} - handle.counts:{}", ls, pSize, tl);
            }
            log.info("DM.execute.counts:{}/{},{} ~ {} ----------------------------> end", pl, num, pSize, tl);
        } catch (Exception e) {
            log.error("ex:getConnection,dG/dg:{}/{}", dG, dg, e);
        }
        try {
            if (null != row) row.close();
        } catch (SQLException ignored) {
        }
        try {
            if (null != statement) statement.close();
        } catch (SQLException ignored) {
        }
//        try {
//            if (null != connection) connection.close();
//        } catch (SQLException ignored) {
//        }
    }
}
