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

import com.liquidnet.service.adam.dto.vo.AdamUserMemberVo;
import com.liquidnet.service.adam.entity.AdamUserMember;
import com.liquidnet.service.adam.service.DataMigrationProcessorService;
import com.liquidnet.service.adam.service.IAdamUserMemberService;
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 DMUserMemberProcessor extends DataMigrationProcessorService {
    @Autowired
    IAdamUserMemberService adamUserMemberService;

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

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

        String sqlCount = "select count(1) from user_cards where created_at" + (StringUtils.isBlank(incrDt) ? "<" : ">=") + "curdate()";
        if (null != dg) {
            sqlCount = sqlCount + " and id%" + dG + "=" + dg;
        }
        String field = "uid,card_id,card_number,`status`,expired_at,created_at,updated_at";
//                     1-uid,2-card_id,3-card_number,4-status,5-expired_at,6-created_at,7-updated_at
        String sql = sqlCount.replace("count(1)", field);
        if ("1".equals(flg)) {
            sqlCount += " and uid in ('2026628','544327','1997335','773650','809406','1167451','423063','677171')";
            sql += " and uid in ('2026628','544327','1997335','773650','809406','1167451','423063','677171')";
        }
        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_PASSPORT, DB_USER, DB_PWD);
            statement = connection.prepareStatement(sqlCount);
            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);

            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<AdamUserMember> userMemberList = new ArrayList<>();
                List<AdamUserMemberVo> vos = new ArrayList<>();
                while (row.next()) {
                    String uid = row.getString(1);
                    if (!reUidList.contains(uid)) {
                        AdamUserMember userMember = new AdamUserMember();
                        userMember.setUid(uid);
                        userMember.setMemberId(row.getString(2));
                        userMember.setMemberNo(row.getString(3));
                        userMember.setState(row.getInt(4));
                        userMember.setExpiryAt(row.getLocalDateTime(5));
                        userMember.setCreatedAt(row.getLocalDateTime(6));
                        userMember.setUpdatedAt(row.getLocalDateTime(7));

                        AdamUserMemberVo vo = AdamUserMemberVo.getNew();
                        vo.setUid(uid);
                        vo.setMemberId(userMember.getMemberId());
                        vo.setMemberNo(userMember.getMemberNo());
                        vo.setState(userMember.getState());
                        vo.setExpiryAt(userMember.getExpiryAt());
                        vo.setCreatedAt(userMember.getCreatedAt());
                        vo.setUpdatedAt(userMember.getUpdatedAt());

                        userMemberList.add(userMember);
                        vos.add(vo);

                        adamRdmService.setUserMemberVoByUid(uid, vo);
                    }
                    if (userMemberList.size() == 500) {
                        tl += userMemberList.size();
                        mongoTemplate.insert(vos, AdamUserMemberVo.class.getSimpleName());
                        log.info("DM.execute.limit.result:{}", adamUserMemberService.saveBatch(userMemberList));
                        vos.clear();
                        userMemberList.clear();
                    }
                }
                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:{}/{},msg:{}", dG, dg, e.getMessage());
        }
        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) {
        }
    }
}
