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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.liquidnet.service.adam.dto.vo.AdamEntersVo;
import com.liquidnet.service.adam.entity.AdamEnters;
import com.liquidnet.service.adam.mapper.AdamEntersMapper;
import com.liquidnet.service.platform.service.impl.adam.sync.SyncDataProcessorService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class SyncEntersProcessor extends SyncDataProcessorService {
    @Autowired
    AdamEntersMapper entersMapper;

    @Override
    public void dataProcessing(int stp) {
        LambdaQueryWrapper<AdamEnters> lambdaQueryWrapper =
                Wrappers.lambdaQuery(AdamEnters.class).eq(AdamEnters::getState, 1)
                .orderByDesc(AdamEnters::getMid);
        Integer totalCount = entersMapper.selectCount(lambdaQueryWrapper);
        int totalRows = null == totalCount ? 0 : totalCount, nth = 0, offset = 5000, pct = 0;
        log.info("Sync.processing.begin:{}/{}, {} ~ {}", totalCount, offset, nth, pct);



        while (totalRows > 0) {
            int rows = nth * offset;
            log.info("Sync.processing.limit {},{} - {} begin", rows, offset, nth);


            PageHelper.startPage(nth + 1, offset);
            List<AdamEnters> dtos = entersMapper.selectList(lambdaQueryWrapper);
            if (!CollectionUtils.isEmpty(dtos)) {
                int size = dtos.size();
                for (int i = 0; i < size; i++) {
                    AdamEnters dto = dtos.get(i);

                    AdamEntersVo vo = AdamEntersVo.getNew().copy(dto);
                    //log.info("vo:{}", JsonUtils.toJson(vo));

                    if (dto.getType() == 1) {
                        dmRdmService.setCertification(1, dto.getIdCard(), dto.getName());
                    }
                    dmRdmService.addEntersVoByUid(dto.getUid(), dmRdmService.getEntersVoByUid(dto.getUid()), vo);

                    pct++;
                }
            }



            log.info("Sync.processing.limit {},{} - {} handle.counts:{}", rows, offset, nth, pct);
            nth++;
            totalRows -= offset;
        }



        log.info("Sync.processing.end:{} / {},{} ~ {}", totalCount, nth, offset, pct);
    }
}
