package com.yeejoin.amos.boot.module.jg.biz.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.module.jg.api.mapper.JgChangeRegistrationTransferMapper;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Administrator
 */
@Component
@Slf4j
public class JgChangeRegistrationTransferUsedCheckImpl extends BaseEquipUsedCheckService {

    private final RedissonClient redissonClient;

    private final String bizType = "changeRegistrationTransfer";

    private final JgChangeRegistrationTransferMapper mapper;

    public JgChangeRegistrationTransferUsedCheckImpl(RedissonClient redissonClient, JgChangeRegistrationTransferMapper mapper) {
        this.redissonClient = redissonClient;
        this.mapper = mapper;
    }


    @Override
    public RedissonClient getRedisClient() {
        return redissonClient;
    }

    @Override
    public String getApplyBizType() {
        return bizType;
    }

    public void init() {
        // 获取设备数据并处理
        Map<String, Set<String>> resultMap = mapper.queryForFlowingEquipList().stream()
                .filter(Objects::nonNull)
                .flatMap(changeData -> {
                    JSONObject changeDataJson = JSON.parseObject(changeData);
                    return changeDataJson.getJSONArray("registrationList").stream()
                            .filter(item -> item instanceof JSONObject)
                            .map(item -> (JSONObject) item)
                            .collect(Collectors.groupingBy(
                                    reg -> reg.getString("useUnitCreditCode"),
                                    Collectors.mapping(reg -> reg.getString("sequenceNbr"), Collectors.toSet())
                            )).entrySet().stream();
                })
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        (existing, replacement) -> {
                            existing.addAll(replacement);
                            return existing;
                        }
                ));

        // 将结果存储到 Redis
        resultMap.forEach((companyCode, records) -> {
            RBucket<Set<String>> rBucket = redissonClient.getBucket(getFlowingEquipRedisKey(companyCode, bizType));
            rBucket.set(records);
        });
    }
}
