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

import com.liquidnet.commons.lang.util.ServletUtils;
import com.liquidnet.service.adam.dto.vo.AdamEntersVo;
import com.liquidnet.service.adam.entity.AdamEnters;
import com.liquidnet.service.adam.service.DataMigrationProcessorService;
import com.liquidnet.service.adam.service.IAdamEntersService;
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 javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class DMEntersProcessor extends DataMigrationProcessorService {
    @Autowired
    IAdamEntersService adamEntersService;

    @SneakyThrows
    @Override
    protected void dataProcessing() {
        HttpServletRequest request = ServletUtils.getRequest();
        String lS = request.getParameter(DM_LS), flg = StringUtils.defaultIfBlank(request.getParameter(DM_FLG), "");
        if (StringUtils.isNotEmpty(request.getParameter(DM_FLUSH))) {
            log.info("DM.flush.enters:{}", userMapper.executeForDM("adam_enters"));

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

        String sqlCount = "select count(1) from enters where (type <> 1 or (type = 1 and is_certification = 'yes'))";
        String field = "id,user_id,type,`name`,mobile,idcode,if(is_default='no', 0, 1),created_at";
//                     1-id,2-user_id,3-type,4-`name`,5-mobile,6-idcode,7-if(is_default='no', 0, 1),8-created_at
        String sql = sqlCount.replace("count(1)", field);
        if ("1".equals(flg)) {
            sqlCount += " and user_id in ('2026628','544327','1997335','773650','809406','1167451','423063','677171')";
            sql += " and user_id in ('2026628','544327','1997335','773650','809406','1167451','423063','677171')";
        }
        sql += " limit ?,?";

        statement = connection.prepareStatement(sqlCount);
        row = (ResultSetImpl) statement.executeQuery();
        row.first();
        int ct = row.getInt(1), pSize = 1000, num = 0, tl = 0;
        log.info("DM.execute.counts:{} ----------------------------> start", ct);

        while (ct > 0) {
            statement = connection.prepareStatement(sql);
            int ls = (num == 0 && StringUtils.isNotEmpty(lS)) ? Integer.parseInt(lS) : pSize * num;
            statement.setInt(1, ls);
            statement.setInt(2, pSize);
            row = (ResultSetImpl) statement.executeQuery();
            log.info("DM.execute.limit {},{} - begin", ls, pSize);

            List<AdamEnters> entersList = new ArrayList<>();
            List<AdamEntersVo> vos = new ArrayList<>();
            while (row.next()) {
                String uid = row.getString(2);

                if (!reUidList.contains(uid)) {
                    AdamEnters enters = new AdamEnters();
                    enters.setEntersId(row.getString(1));
                    enters.setUid(uid);
                    enters.setType(row.getInt(3));
                    enters.setName(row.getString(4));
                    enters.setMobile(row.getString(5));
                    enters.setIdCard(row.getString(6));
                    enters.setIsDefault(row.getBoolean(7));
                    enters.setState(1);
                    enters.setCreatedAt(row.getLocalDateTime(8));

                    AdamEntersVo vo = AdamEntersVo.getNew().copy(enters);

                    entersList.add(enters);
                    vos.add(vo);
                }
            }
            log.info("DM.execute.limit {},{} - handle.counts:{}", ls, pSize, entersList.size());
            if (!CollectionUtils.isEmpty(entersList)) {
                tl += entersList.size();
                mongoTemplate.insert(vos, AdamEntersVo.class.getSimpleName());
                log.info("DM.execute.limit.result:{}", adamEntersService.saveBatch(entersList));
            }

            num++;
            ct -= pSize;
        }
        log.info("DM.execute.counts:{} ~ {} ----------------------------> end", num * pSize, tl);
    }
}
