package com.mvc.service.aiiden;

import com.mvc.model.TAireadModel;
import com.mvc.model.TServerReadModel;
import com.mvc.model.TaskReviewModel;
import com.mvc.model.aiiden.AiIdenMap;
import com.mvc.model.aiiden.AiMeterResultModel;
import com.mvc.service.copy.TServerReadService;
import com.mvc.utils.StoreBlockingQueue;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 服务器侧识别线程
 * 加此线程是为了不影响报文解析的效率
 * 是否进行服务器侧识别,在此线程中进行判断和处理
 */
@Component
public class AiIdenTask {             //备用线程方式   extends Thread
    private static Logger log = LoggerFactory.getLogger(AiIdenService.class);
    private static AiIdenService aiIdenService;
    private static TServerReadService tServerReadService;

    public static List<TAireadModel> modelList = new ArrayList<>();
    private static ReentrantLock lock = new ReentrantLock();

    public static AiIdenService getAiIdenService() {
        return aiIdenService;
    }

    @Autowired   //静态必须这么写
    public void setAiIdenService(AiIdenService aiIdenService) {
        AiIdenTask.aiIdenService = aiIdenService;
    }

    public static TServerReadService getTServerReadService() {
        return tServerReadService;
    }

    @Autowired
    public void setTServerReadService(TServerReadService tServerReadService) {
        AiIdenTask.tServerReadService = tServerReadService;
    }

    @Autowired
    private static TaskReviewService taskReviewService;

    public static TaskReviewService getTaskReviewService() {
        return taskReviewService;
    }

    @Autowired   //静态必须这么写
    public void setAiIdenService(TaskReviewService taskReviewService) {
        AiIdenTask.taskReviewService = taskReviewService;
    }

/*    @Override
    public void run() {
        modelList = new ArrayList<>();

        while (true) {
            try {
                Thread.sleep(1000);

                lock.lock();
                if (modelList.size() > 0) {
                    startServerIden(modelList.get(0));
                    modelList.remove(0);
                }
            } catch (IOException | IllegalAccessException | InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }*/

    /**
     * 处理服务器侧任务
     */
    public static void handleAiIdenTask() {
        int size = StoreBlockingQueue.tAireadQueue.size();
        //System.out.println("handleAiIdenTask__modelList__size="+size);
        for (int i = 0; i < size; i++) {
            try {
                TAireadModel model = StoreBlockingQueue.tAireadQueue.take();
                startServerIden(model);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * 检查读数表数据
     */
    private static void startServerIden(TAireadModel model) throws IllegalAccessException, IOException {
        if (model == null) return;

        TServerReadModel srModel = new TServerReadModel();
        srModel.setAireadId(model.getAireadId());
        srModel.setDeviceSn(model.getDeviceSn());
        srModel.setStationCode(model.getStationCode());

        AiIdenMap aiIdenMap = null;
        try {
            aiIdenMap = getAiIdenService().getWaterResultByAiread(model);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        if (aiIdenMap != null) {
            AiMeterResultModel resultModel = null;
            //System.out.println("aiIdenMap.getCode:"+aiIdenMap.getCode()+"-----"+aiIdenMap.getCode()=="5200");
            if (aiIdenMap.getCode().equals("5200")) {
                String goodFlag = "2";
                resultModel = (AiMeterResultModel) aiIdenMap.getResult();
                if (resultModel.getResult_code() == 1 || resultModel.getResult_code() == 7) {
                    goodFlag = "1";
                }
                srModel.setGoodFlag(goodFlag);
            } else if (aiIdenMap.getCode().equals("NOCFG")) {
                srModel.setGoodFlag("4");
                log.info("[服务侧识别]没有读取到配置信息[" + model.getDeviceSn() + "]");
            } else if (aiIdenMap.getCode().equals("IMGERR")) {
                srModel.setGoodFlag("5");
                log.info("[服务侧识别]图片异常[" + model.getDeviceSn() + "]");
            } else if (aiIdenMap.getCode().equals("NODEBUG")) {
                log.info("[服务侧识别]上次值没有调试信息[" + model.getDeviceSn() + "]");
                return;
            } else if (aiIdenMap.getCode().equals("NOLAST")) {
                log.info("[服务侧识别]没有上次结果值[" + model.getDeviceSn() + "]");
                return;
            } else if (aiIdenMap.getCode().equals("DEBUGNOTNUM")) {
                log.info("[服务侧识别]上次结果的调试信息非数字[" + model.getDeviceSn() + "]");
                return;
            } else {
                log.info("[服务侧识别]推理异常:" + aiIdenMap.getCode() + ";" + aiIdenMap.getResult());
                srModel.setGoodFlag("2");           //2代表推理出现错误
            }

            if (resultModel != null) {
                //老版本程序可能存在小数有调试信息的问题,先只比较整数部分吧
                //boolean isDiff = model.getIdentValue()!=resultModel.getValue();
/*                BigDecimal value1=model.getIdentValue().setScale(0, RoundingMode.DOWN);
                BigDecimal value2=resultModel.getValue().setScale(0,RoundingMode.DOWN);
                boolean isDiff=value1!=value2;*/
                //存不同的图片意义不大,有需要再打开 2022-10-11 guozhao
                String imgUrl = getAiIdenService().getAiResultImage(resultModel.getAi_image_url(), false);
                srModel.setIdentValue(resultModel.getValue().setScale(model.getDecimalDigits(), RoundingMode.HALF_UP));
                srModel.setResultCode(resultModel.getResult_code() + "");

                if (StringUtils.isNotEmpty(resultModel.getSmall_image_url())) {
                    String small = getAiIdenService().getAiResultImage(resultModel.getSmall_image_url(), false);
                    srModel.setSmallJpgUrl(small);
                    //water_meter_test_20220718_224317_906655_small_2_42_164.jpg
                    if (StringUtils.isNotEmpty(small)) {
                        int index0 = small.indexOf("small");
                        small = small.substring(index0, small.length() - 4);
                        String[] temp = small.split("_");
                        if (temp != null && temp.length > 3) {
                            srModel.setSmallJpgType(temp[1]);
                            srModel.setSmallJpgHeight(Integer.valueOf(temp[2]));
                            srModel.setSmallJpgWidth(Integer.valueOf(temp[3]));
                        }
                    }
                }
                srModel.setJpgUrl(imgUrl);
            }
        } else {
            srModel.setGoodFlag("3");
            log.info("服务器侧识别异常;原始图片:" + model.getSmallJpgUrl());
            if (srModel == null) {
                System.out.println("startServerIden___srModel==null");
            }
        }

        getTServerReadService().saveTServerRead(srModel);
    }

    private static void TestReview(TServerReadModel srModel) throws IOException, InterruptedException {
        TaskReviewModel model = new TaskReviewModel();
        model.setId(1);
        model.setTaskId("test20220719");
        model.setAireadId(srModel.getAireadId());
        model.setServerReadId(srModel.getServerReadId());
        model.setReviewTime(new Date());
        model.setReviewValue(new BigDecimal(11111));
        model.setReviewMan("测试");
        model.setFinishedFlag("2");
        getTaskReviewService().dealReviewInfo(model, false);
    }

    /**
     * 将AI读数对象加到处理列表中
     *
     * @param model
     */
    public static void addTAireadModel(TAireadModel model) {
        try {
            lock.lock();
            modelList.add(model);

            //防止定时任务出现问题,缓存爆掉
            if (modelList.size() > 500) {
                modelList.remove(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
