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

import com.liquidnet.commons.lang.util.ServletUtils;
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 javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class DMUserMemberProcessor extends DataMigrationProcessorService {
    @Autowired
    IAdamUserMemberService adamUserMemberService;

    @SneakyThrows
    @Override
    protected void dataProcessing() {
        HttpServletRequest request = ServletUtils.getRequest();
        String lS = request.getParameter(DM_LS), incrDt = request.getParameter(DM_INCR_DT),
                flg = StringUtils.defaultIfBlank(request.getParameter(DM_FLG), "");
        if (StringUtils.isNotEmpty(request.getParameter(DM_FLUSH))) {
            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()";
        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 ?,?";

        statement = connection.prepareStatement(sqlCount);
        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 = (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<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);
    }
}
