package cn.wise.sc.energy.power.plant.business.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.wise.sc.energy.power.plant.business.domain.DetectionItem;
import cn.wise.sc.energy.power.plant.business.service.IDetectionService;
import cn.wise.sc.energy.power.plant.common.core.exception.ResponseEnum;
import com.alibaba.fastjson.JSON;
import org.redisson.api.RBucket;
import org.redisson.api.RQueue;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @description: 一键巡检
 * @author: qh
 * @create: 2020-08-17 10:15
 **/
@Service
public class DetectionServiceImpl implements IDetectionService {

    final
    RedissonClient redissonClient;

    public DetectionServiceImpl(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    private native String start(String sessionId, Integer status);

    @Override
    public Boolean startDetection(String sessionId) {

        String start = start(sessionId, 0);

        if (StrUtil.isNotBlank(start) && "0".equals(start)) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public DetectionItem nextItem(String sessionId) {
        //使用队列的模式
        ResponseEnum.LICENCE_NOT_FOUND.assertNotEmpty(sessionId);
        RQueue<DetectionItem> queue = redissonClient.getQueue(sessionId);
        DetectionItem poll = queue.poll();
        //判断是否为最后一个
        if (queue.size() == 0 && poll != null) {
            //判断是否存在交互
            String interactionKey = sessionId + "_Interaction";
            RBucket<String> bucket = redissonClient.getBucket(interactionKey);
            if (bucket.isExists()) {
                poll.setInteraction(JSON.parseObject(bucket.get(),
                        DetectionItem.Interaction.class));
                return poll;
            }
        }
        return poll;
    }


    @Override
    public Boolean interactionChose(String sessionId, String qid, List<Integer> selectIndex) {
        ResponseEnum.COLLECTION_NOT_ILLEGAL.assertNotEmpty(sessionId);
        ResponseEnum.COLLECTION_NOT_ILLEGAL.assertNotEmpty(qid);
        ResponseEnum.COLLECTION_NOT_ILLEGAL.assertNotNull(selectIndex);

        //拿到交互项redis这中存 数据
        String key = sessionId + "_Result";

        RBucket<Object> bucket = redissonClient.getBucket(key);
        DetectionItem.InteractionResult result = new DetectionItem.InteractionResult();
        result.setId(sessionId);
        result.setQid(qid);
        result.setSelect(selectIndex);

        bucket.set(JSON.toJSONString(result));

        return true;
    }


}
