package cn.wise.sc.energy.power.plant.business.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.wise.sc.energy.power.plant.business.domain.BtreeInfoConfig;
import cn.wise.sc.energy.power.plant.business.domain.redisTrans.BtreeInerAct;
import cn.wise.sc.energy.power.plant.business.domain.redisTrans.BtreeInerAction;
import cn.wise.sc.energy.power.plant.business.domain.redisTrans.BtreeProcess;
import cn.wise.sc.energy.power.plant.business.jna.C2TreeAnalysis;
import cn.wise.sc.energy.power.plant.business.repository.BtreeInfoConfigRepository;
import cn.wise.sc.energy.power.plant.business.utils.BeanUtilsExt;
import cn.wise.sc.energy.power.plant.business.utils.Utils;
import cn.wise.sc.energy.power.plant.common.core.bean.BaseResponse;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.ApiOperation;
import org.redisson.api.RBucket;
import org.redisson.api.RList;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.StringCodec;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author neo.shu
 * @since 2020/9/14 11:15
 */
@CrossOrigin
@RestController
@RequestMapping("btreeinspec/")
public class BtreeInspectionController {

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    BtreeInfoConfigRepository configRepository;

    @ApiOperation("获取二叉树列表")
    @PostMapping("/configList")
    public BaseResponse<List<BtreeInfoConfig>> interaction() {

        List<BtreeInfoConfig> list = configRepository.findAll();
        return BaseResponse.okData(list);

    }

    @ApiOperation("更新二叉树")
    @PostMapping("/configUpdate")
    public BaseResponse<Boolean> interaction(@RequestBody BtreeInfoConfig info) {

        BtreeInfoConfig config;
        if (info.getId() == null || 0 == info.getId()) {
            config = configRepository.save(info);
        } else {
            config = configRepository.getOne(info.getId());
            BeanUtils.copyProperties(info, config, BeanUtilsExt.getNullPropertyNames(info));
            config = configRepository.save(config);
        }
        if (config.getId() != null) {
            return BaseResponse.okData(true);
        } else {
            return BaseResponse.okData(false);
        }

    }


    @PostMapping("/checkProcess")
    public BaseResponse getProcess() {
        long time = System.currentTimeMillis();
        Map<String, Object> result = new HashMap<>();
        RBucket<String> currentIndex = redissonClient.getBucket("btreetask:"+Utils.getTaskPrefix());
        if (currentIndex.get() == null) {
            result.put("status", -3);
            return BaseResponse.okData(result);
        }
        //查询当前任务的进度
        List<BtreeProcess> btreeProcesses = conventClazz("process_" + currentIndex.get(), BtreeProcess.class);
        int num = -1;
        if (btreeProcesses != null && btreeProcesses.size() > 0) {
            for (int i = 0; i < btreeProcesses.size(); i++) {

                if (btreeProcesses.get(i).getGrade() == -1.0) {
                    num = -1;
                } else if (btreeProcesses.get(i).getGrade() == -2.0) {
                    num = -2;
                } else if (btreeProcesses.get(i).getGrade() > 0) {
                    num = 0;
                }
                //如果有交互，查询交互
                if (btreeProcesses.get(i).getGrade() == -2.0) {
                    List<BtreeInerAction> interAction = conventClazz("inter_" + currentIndex.get(), BtreeInerAction.class);//currentIndex.get()
                    btreeProcesses.get(i).setBtreeInerAction(CollectionUtil.getLast(interAction));
                }
            }
        }
        result.put("status", num);
        result.put("data", btreeProcesses);
        long endTime = System.currentTimeMillis();
        System.out.println(endTime-time);
        return BaseResponse.okData(result);
    }

    private <T> List<T> conventClazz(String currentIndex, Class<T> tClass) {
        List<String> redisList = (ArrayList) redissonClient.getList(currentIndex, new StringCodec()).readAll();
        List<T> processes = new ArrayList<>();
        for (String str : redisList) {
            processes.add(JSON.parseObject(str, tClass));
        }
        return CollectionUtil.reverseNew(processes);
    }

    @PostMapping("/interaction")
    public BaseResponse interaction(@RequestBody BtreeInerAct btreeInerAct) {
        //存储redis
        RBucket<String> currentIndex = redissonClient.getBucket("btreetask:"+Utils.getTaskPrefix());
        Map<String, Object> result = new HashMap<>();
        if (currentIndex.get() == null) {
            result.put("status", -3);
            return BaseResponse.okData(result);
        }
        RList<String> a = redissonClient.getList("result_" + currentIndex.get(), new StringCodec());//currentIndex.get()
        a.add(0, JSON.toJSONString(btreeInerAct));
        //更新状态-2为-1
        RList<String> redisList = redissonClient.getList("process_" + currentIndex.get(), new StringCodec());//currentIndex.get()
        BtreeProcess btreeProcess = JSON.parseObject(redisList.get(0), BtreeProcess.class);
        btreeProcess.setGrade(-1.0);
        redisList.remove(0);
        redisList.add(0, JSON.toJSONString(btreeProcess));
        return BaseResponse.okData("交互成功");

    }

    @PostMapping("/createBtree")
    public BaseResponse<String> del() {
        //todo  获取全场机组的最后时间点
        //根据规则创建二叉树巡检任务，并存入redis
        String taskId =Utils.getTaskPrefix()+"-"+ System.currentTimeMillis();
        //每次新建任务都保存一下
        redissonClient.getBucket("btreetask:"+Utils.getTaskPrefix()).set(taskId, 10L, TimeUnit.MINUTES);
        //jna发起任务。
        String taskjson = "{\"taskId\":\"" + taskId + "\",\"taskTyped\":0,\"Data\":[1599717386000,1599717386000]}";
        try {
            new Thread(()->{
                C2TreeAnalysis.INSTANCE.C2TreeDiagnose(taskjson);
            }).start();
        } catch (RuntimeException e) {
            throw e;
        }
        return BaseResponse.okData("创建成功");
    }


}
