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

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.service.adam.dto.vo.AdamUserMemberVo;
import com.liquidnet.service.adam.entity.AdamUserMember;
import com.liquidnet.service.platform.service.impl.adam.dm.DMUserMemberService;
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.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
    DMUserMemberService dmUserMemberService;

    @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()" : (">=curdate()-" + incrDt));
        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);
        boolean smFlg = "1".equals(flg);
        if (smFlg) {
            sqlCount += " and uid in (" + DG_UID + ")";
            sql += " and uid 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_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);

                        dmRdmService.setUserMemberVoByUid(uid, vo);
                    }
                    if (userMemberList.size() == 1000 || (userMemberList.size() > 0 && smFlg) || ct <= 1000) {
                        tl += userMemberList.size();
//                        mongoTemplate.insert(vos, AdamUserMemberVo.class.getSimpleName());
                        log.info("DM.execute.limit.result:{}", dmUserMemberService.saveBatch(userMemberList));
                        vos.clear();
                        userMemberList.clear();
                    }
                }
                if (userMemberList.size() > 0) {
                    tl += userMemberList.size();
                    log.info("DM.execute.limit.result:{}", dmUserMemberService.saveBatch(userMemberList));
                }
                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) {
//        }
    }
}
