package com.liquidnet.service.adam.service.processor;

import com.liquidnet.service.adam.dto.vo.AdamEntersVo;
import com.liquidnet.service.adam.entity.AdamEnters;
import com.liquidnet.service.adam.service.DataMigrationProcessorService;
import com.liquidnet.service.adam.service.IAdamEntersService;
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 org.springframework.util.CollectionUtils;

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

@Slf4j
@Service
public class DMEntersProcessor extends DataMigrationProcessorService {
    @Autowired
    IAdamEntersService adamEntersService;

    @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 enters where (type <> 1 or (type = 1 and is_certification = 'yes')) and created_at" + (StringUtils.isBlank(incrDt) ? "<" : ">=") + "curdate()";
        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";
//                     1-id,2-user_id,3-type,4-`name`,5-mobile,6-idcode,7-if(is_default='no', 0, 1),8-created_at
        String sql = sqlCount.replace("count(1)", field);
        if ("1".equals(flg)) {
            sqlCount += " and user_id in ('2026628','544327','1997335','773650','809406','1167451','423063','677171')";
            sql += " and user_id in ('2026628','544327','1997335','773650','809406','1167451','423063','677171')";
        }
        sql += " order by id limit ?,?";

        Class.forName(DB_DRIVER);
        Connection connection = DriverManager.getConnection(DB_URL + DB_NAME_MALL, DB_USER, DB_PWD);

        PreparedStatement statement = connection.prepareStatement(sqlCount);
        ResultSetImpl row = (ResultSetImpl) statement.executeQuery();
        row.first();
        int ct = row.getInt(1), pSize = 1000, num = 0, tl = 0, pl = ct;
        log.info("DM.execute.counts:{}/{},{} ~ {} ----------------------------> start.sql:{}", pl, num, pSize, tl, sql);

        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));

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

                    entersList.add(enters);
                    vos.add(vo);
                }
            }
            log.info("DM.execute.limit {},{} - handle.counts:{}", ls, pSize, entersList.size());
            if (!CollectionUtils.isEmpty(entersList)) {
                tl += entersList.size();
                mongoTemplate.insert(vos, AdamEntersVo.class.getSimpleName());
                log.info("DM.execute.limit.result:{}", adamEntersService.saveBatch(entersList));
            }

            num++;
            ct -= pSize;
        }
        log.info("DM.execute.counts:{}/{},{} ~ {} ----------------------------> end", pl, num, pSize, tl);
        row.close();
        statement.close();
        connection.close();
    }
}
