package com.tofly.watermeter.custom.util;

import cn.hutool.core.collection.CollUtil;
import com.tofly.watermeter.config.ComConstans;
import com.tofly.watermeter.config.ForeignConfig;
import com.tofly.watermeter.custom.dto.SupplyYhYfDto;
import com.tofly.watermeter.custom.service.ReadMeterService;
import com.tofly.watermeter.custom.vo.ForeignSynchroYhQyQdVo;
import com.tofly.watermeter.util.CallAPIUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class RedisQueueUtil  {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ReadMeterService readMeterService;
    private volatile boolean flag = true;
    @Autowired
    private ForeignConfig foreignConfig;

    private static ExecutorService executorService = new ThreadPoolExecutor(2, 2,
            60L, TimeUnit.SECONDS,
            new SynchronousQueue<Runnable>());

    @PostConstruct
    public void start(){

        executorService.execute(()-> {
                try {
                    SupplyYhYfDto message;
                    log.info("============启动监听 客户用水变更  {}",flag && !Thread.currentThread().isInterrupted());
                    while(flag && !Thread.currentThread().isInterrupted()) {
                        message = (SupplyYhYfDto)redisTemplate.opsForList().rightPop(foreignConfig.getQueueKey(), foreignConfig.getPopTimeout(), TimeUnit.SECONDS);
                        if(message!=null) {
                            readMeterService.updateQfcbqfmxls(message);
                        }
                    }
                } catch (Exception e) {
                    System.err.println(e.getMessage());
                }
        });

        executorService.execute(()->{
            log.info("============启动监听 删除 客户区域区段变更  {}",flag && !Thread.currentThread().isInterrupted());
            List<String> lists = new ArrayList<>();
            while(flag && !Thread.currentThread().isInterrupted()) {
                String message = (String)redisTemplate.opsForList().rightPop(foreignConfig.getQyQdKey(), foreignConfig.getPopTimeout(), TimeUnit.SECONDS);
                if(message!=null){
                    lists.add(message);
                }
                if((message==null&& CollUtil.isNotEmpty(lists))||lists.size()>=100){
                    sendInfo(lists);
                    lists.clear();
                    lists = new ArrayList<>();
                }
            }
        });
    }

    public boolean sendInfo(List<String> vos) {
        try {
            List<ForeignSynchroYhQyQdVo> infos = new ArrayList<>();
            for (String vo:vos ) {
                ForeignSynchroYhQyQdVo info = new ForeignSynchroYhQyQdVo();
                info.setKhbh(vo);
                info.setZt(ComConstans.INT_ONE);
                infos.add(info);
            }
            //调用营销接口
            Map<String,Object> map = new HashMap<>();
            map.put("DATAS",infos);
            map.put("ACTION","query");
            Map cbMap = CallAPIUtil.callAPIUtil(map, "/api/Business/RegionAndSectionUpdate");
            if(CollUtil.isEmpty(cbMap)||!"0000".equals(cbMap.get("Code"))){
                log.warn("删除发送失败！数据:{}",infos);
            }
        }catch (Exception e){
            log.error("",e);
        }

        return true;
    }

}
