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 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 DMUserMemberProcessor extends DataMigrationProcessorService {
    @Autowired
    IAdamUserMemberService adamUserMemberService;

    @SneakyThrows
    @Override
    public void dataProcessing(Integer dg, Integer lS, 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%" + lS + "=" + 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 ?,?";

        Class.forName("com.mysql.cj.jdbc.Driver");
//        String url = "jdbc:mysql://pc-2ze6z2hxkug559q79.mysql.polardb.rds.aliyuncs.com:3306/passport";
        String url = "jdbc:mysql://zhengzai.mysql.polardb.rds.aliyuncs.com:3306/passport";
        Connection connection = DriverManager.getConnection(url, "readonly", "ZWDsf8Fy");

        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<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);
                }
            }
            log.info("DM.execute.limit {},{} - handle.counts:{}", ls, pSize, userMemberList.size());
            if (!CollectionUtils.isEmpty(userMemberList)) {
                tl += userMemberList.size();
                mongoTemplate.insert(vos, AdamUserMemberVo.class.getSimpleName());
                log.info("DM.execute.limit.result:{}", adamUserMemberService.saveBatch(userMemberList));
            }

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