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

import com.liquidnet.service.adam.dto.vo.AdamCollectVo;
import com.liquidnet.service.adam.entity.AdamCollection;
import com.liquidnet.service.adam.service.DataMigrationProcessorService;
import com.liquidnet.service.adam.service.IAdamCollectionService;
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 DMCollectionProcessor extends DataMigrationProcessorService {
    @Autowired
    IAdamCollectionService adamCollectionService;

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

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

        String sqlCount = "select count(1) from user_collections where type='TICKET' and status=1 and content_id>=5722 and created_at"+(StringUtils.isBlank(incrDt) ? "<" : ">=")+"curdate()";
        if (null != dg) {
            sqlCount = sqlCount + " and id%" + dG + "=" + dg;
        }
        String field = "uid,content_id,`type`,`status`,created_at,updated_at";
//                     1-uid,2-content_id,3-`type`,4-`status`,5-created_at,6-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(DB_DRIVER);
        Connection connection = DriverManager.getConnection(DB_URL + DB_NAME_PASSPORT, 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<AdamCollection> collectionList = new ArrayList<>();
            List<AdamCollectVo> vos = new ArrayList<>();
            while (row.next()) {
                String uid = row.getString(1);
                if (!reUidList.contains(uid)) {
                    AdamCollection collection = new AdamCollection();
                    collection.setUid(uid);
                    collection.setContentId(row.getString(2));
                    collection.setType(row.getString(3));
                    collection.setState(row.getInt(4));
                    collection.setCreatedAt(row.getLocalDateTime(5));
                    collection.setUpdatedAt(row.getLocalDateTime(6));

                    collectionList.add(collection);
                    vos.add(AdamCollectVo.getNew().copy(collection));
                }
            }
            log.info("DM.execute.limit {},{} - handle.counts:{}", ls, pSize, collectionList.size());
            if (!CollectionUtils.isEmpty(collectionList)) {
                tl += collectionList.size();
                mongoTemplate.insert(vos, AdamCollectVo.class.getSimpleName());
                log.info("DM.execute.limit.result:{}", adamCollectionService.saveBatch(collectionList));
            }

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