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.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.service.adam.dto.vo.AdamThirdPartInfoVo;
import com.liquidnet.service.adam.entity.AdamThirdParty;
import com.liquidnet.service.adam.mapper.AdamThirdPartyMapper;
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 SyncThirdPartyProcessor extends SyncDataProcessorService {
    @Autowired
    AdamThirdPartyMapper thirdPartyMapper;

    @Override
    public void dataProcessing(int stp) {
        LambdaQueryWrapper<AdamThirdParty> lambdaQueryWrapper =
                Wrappers.lambdaQuery(AdamThirdParty.class).eq(AdamThirdParty::getState, 1)
                .orderByDesc(AdamThirdParty::getMid);
        Integer totalCount = thirdPartyMapper.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<AdamThirdParty> dtos = thirdPartyMapper.selectList(lambdaQueryWrapper);
            if (!CollectionUtils.isEmpty(dtos)) {
                int size = dtos.size();
                for (int i = 0; i < size; i++) {
                    AdamThirdParty dto = dtos.get(i);

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

                    dmRdmService.setUidByPlatformOpenId(dto.getPlatform(), dto.getOpenId(), dto.getUid());
                    dmRdmService.addThirdPartVoListByUid(dto.getUid(), dmRdmService.getThirdPartVoListByUid(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);
    }
}
