package com.handset.serialportsensor.utils;

import android.content.Context;
import android.util.Log;
import android.util.SparseArray;

import com.handset.serialportsensor.bean.Sensor;
import com.handset.serialportsensor.bean.TestRecordsTotal;

import org.kymjs.kjframe.KJDB;

import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.List;

/**
 * Created by zy on 2019/2/24.
 */

public class PersistHelper {
    private static final String logTag = "HANDSET-JE002-EX";
    private static Context sContext;

    private static Sensor mSensor = null;
    private static ExcelUtils excelUtils;

    public static void init(Context context) {
        sContext = context;
        excelUtils = new ExcelUtils();
    }


    public static void generateSimulateData() {
        KJDB.getDefaultInstance().deleteByWhere(Sensor.class, "1=1");
        KJDB.getDefaultInstance().deleteByWhere(TestRecordsTotal.class, "1=1");
        initSensor();
    }

    private static void initSensor() {
        Sensor sensor = new Sensor();
        sensor.id = 1;
        sensor.egg_id = "EGG11234";
        sensor.sensor_id = 19011111;
        sensor.egg_type = "EGGA1234";
        sensor.tupe_id = "TUPEA1234";
        KJDB.getDefaultInstance().save(sensor);
        sensor.id = 2;
        sensor.egg_id = "EGG21234";
        sensor.sensor_id = 19011112;
        sensor.egg_type = "EGGB1234";
        sensor.tupe_id = "TUPEB1234";
        KJDB.getDefaultInstance().save(sensor);

        TestRecordsTotal testRecordsTotal = new TestRecordsTotal();
        long a = 315360000000L;
        testRecordsTotal.end_time = System.currentTimeMillis() - a;
        testRecordsTotal.Hum = 80;
        testRecordsTotal.sensor_id = 19011111;
        testRecordsTotal.pressure_yacha = 100;
        testRecordsTotal.pressurein = 90;
        testRecordsTotal.pressureout = 120;
        testRecordsTotal.temp = 50;
        testRecordsTotal.Hum20 = 90;
        testRecordsTotal.pressurein20 = 20;
        testRecordsTotal.tupe_use_times = "10";
        int i = 1;
        Calendar c = Calendar.getInstance();
        for (; i < 5000; i++) {
            testRecordsTotal.id = i;
            testRecordsTotal.end_time += 24 * 3600000;
            c.setTimeInMillis(testRecordsTotal.end_time);
            testRecordsTotal.day_t = c.get(Calendar.DAY_OF_YEAR) + c.get(Calendar.YEAR) * 1000;
            KJDB.getDefaultInstance().save(testRecordsTotal);
            if (i % 100 == 0) {
                Log.d(logTag, "initSensor  []:" + i);
            }
        }

        testRecordsTotal.sensor_id = 19011112;
        for (; i < 10000; i++) {
            testRecordsTotal.id = i;
            testRecordsTotal.end_time += 24 * 3600000;
            c.setTimeInMillis(testRecordsTotal.end_time);
            testRecordsTotal.day_t = c.get(Calendar.DAY_OF_YEAR) + c.get(Calendar.YEAR) * 1000;
            KJDB.getDefaultInstance().save(testRecordsTotal);
            if (i % 100 == 0) {
                Log.d(logTag, "initSensor  []:" + i);
            }
        }
    }

    public static void resetDB() {
        KJDB.getDefaultInstance().deleteByWhere(Sensor.class, "1=1");
        KJDB.getDefaultInstance().deleteByWhere(TestRecordsTotal.class, "1=1");
        SPUtils.getInstance(sContext).put("current_test_id", -1l);
    }

    public static long generateNextTestId() {
        long currentTestId = SPUtils.getInstance(sContext).get("current_test_id", -1L);
        long newId = currentTestId == -1 || currentTestId >= 10000000 ? 1 : currentTestId + 1;
        TestRecordsTotal old = KJDB.getDefaultInstance().findById(newId, TestRecordsTotal.class);
        if (old != null) {
            KJDB.getDefaultInstance().delete(old);
        }
        SPUtils.getInstance(sContext).put("current_test_id", newId);
        return newId;
    }

    private static long NextTestIdCC() {
        long currentTestId = SPUtils.getInstance(sContext).get("current_test_id", -1l);
        long newId = currentTestId - 1;
        if (newId == -1 || newId == 0 || currentTestId >= 10000000) {
            newId = 0;
        }

        TestRecordsTotal old = KJDB.getDefaultInstance().findById(currentTestId, TestRecordsTotal.class);
        if (old != null) {
            KJDB.getDefaultInstance().delete(old);
        }
        SPUtils.getInstance(sContext).put("current_test_id", newId);
        return newId;
    }


    /**
     * 生成下一个保存数据的Id
     * <p>
     * 考虑到测试Id保存的的上线是1000 000，循环利用ID,超过后复写以前的数据
     */
    public static long generateNextTestId(int idHigh1, byte idHigh2, byte idHigh3, byte idHigh4) {
        if (sContext == null) {
            return -1;
        }
        long newId = generateNextTestId();
        TestRecordsTotal testRecordsTotal = new TestRecordsTotal();
        testRecordsTotal.id = newId;
        testRecordsTotal.botelv = sbotelv;
        Log.d(logTag, "generateNextTestId  [idHigh1, idHigh2, idHigh3, idHigh4]:" + newId);
        KJDB.getDefaultInstance().save(testRecordsTotal);
        if (mSensor == null) {
            mSensor = new Sensor();
        }
        int[] values = ProtoUtils.getSensorNumber(idHigh1, idHigh2, idHigh3, idHigh4);
        mSensor.sensor_id = values[1];
        return newId;
    }

    public static void genItem(int sensorId) {
        if (sContext == null) {
            return;
        }
        long newId = generateNextTestId();
        TestRecordsTotal testRecordsTotal = new TestRecordsTotal();
        testRecordsTotal.id = newId;
        testRecordsTotal.botelv = sbotelv;
        Log.d(logTag, "generateNextTestId  [idHigh1, idHigh2, idHigh3, idHigh4]:" + newId);
        KJDB.getDefaultInstance().save(testRecordsTotal);
        if (mSensor == null) {
            mSensor = new Sensor();
        }
        mSensor.sensor_id = sensorId;
    }

    public static void genItem(int sensorId, String baudRate) {
        if (sContext == null) {
            return;
        }
        long newId = generateNextTestId();
        TestRecordsTotal testRecordsTotal = new TestRecordsTotal();
        testRecordsTotal.id = newId;
        testRecordsTotal.botelv = baudRate;
        Log.d(logTag, "generateNextTestId  [idHigh1, idHigh2, idHigh3, idHigh4]:" + newId);
        KJDB.getDefaultInstance().save(testRecordsTotal);
        if (mSensor == null) {
            mSensor = new Sensor();
        }
        mSensor.sensor_id = sensorId;
    }

    static String sbotelv = "38400";

    public static void mateSuccess(String botelv) {
        sbotelv = botelv;
    }

    public static long getCurrentTestId() {
        if (sContext == null) {
            return -1;
        }
        return SPUtils.getInstance(sContext).get("current_test_id", -1l);
    }

    public static TestRecordsTotal getCurrentTestRecordsTotal() {
        if (sContext == null) {
            return null;
        }
        long id = getCurrentTestId();
        if (id == -1) {
            return null;
        }
        return KJDB.getDefaultInstance().findById(id, TestRecordsTotal.class);
    }

    public static void saveEggID(String eggNumber) {
    /*TestRecordsTotal testRecordsTotal = getCurrentTestRecordsTotal();
    testRecordsTotal.egg_id = eggNumber;
    KJDB.getDefaultInstance().update(testRecordsTotal);*/

        mSensor.egg_id = eggNumber;
    }

    public static void saveEggType(String eggType) {
    /*TestRecordsTotal testRecordsTotal = getCurrentTestRecordsTotal();
    testRecordsTotal.egg_type = eggtype;
    KJDB.getDefaultInstance().update(testRecordsTotal);*/

        mSensor.egg_type = eggType;
    }

    public static void saveConeNo(String coneNo) {
    /*TestRecordsTotal testRecordsTotal = getCurrentTestRecordsTotal();
    testRecordsTotal.tupe_id = coneNumber;
    KJDB.getDefaultInstance().update(testRecordsTotal);*/

        mSensor.tupe_id = coneNo;
    }

    public static void saveConeUsedTimes(String usedTimes) {
        TestRecordsTotal testRecordsTotal = getCurrentTestRecordsTotal();
        testRecordsTotal.tupe_use_times = usedTimes;
        mSensor.tv_tupe_use_times = usedTimes;
        KJDB.getDefaultInstance().update(testRecordsTotal);
    }

    private static SparseArray<Item> sItemSparseArray = new SparseArray<>();

    public static void save(float value, int type) {
        Item i = sItemSparseArray.get(type);
        if (i != null) {
            i.count++;
            i.sum += value;
            i.average = i.sum / i.count;
        } else {
            Item item = new Item();
            item.count = 1;
            item.sum = value;

            item.average = value;
            sItemSparseArray.put(type, item);
        }
    }

    public static class Item {
        int count = 0;
        float sum = 0;
        float average = 0;
    }

    public static void endTest(boolean save) {
        if (save) {
            endTest();
        } else {
            NextTestIdCC();
            //清楚所有单条记录
            sItemSparseArray.clear();
            sbotelv = "";
        }
    }


    /*结束本次测试*/
    public static void endTest() {
        long id = getCurrentTestId();
        if (id < 0) {
            return;
        }
        TestRecordsTotal testRecordsTotal = getCurrentTestRecordsTotal();
        if (testRecordsTotal == null) {
            return;
        }
        /*温度*/
        float temp = -1000;
        /*湿度*/
        float Hum = -1000;
        /*内压*/
        float pressurein = -1000;
        /*外压*/
        float pressureout = -1000;
        /*压差*/
        float pressure_yacha = -1000;
        /*湿度*/
        float Hum20 = -1000;
        /*内压*/
        float pressurein20 = -1000;
        Item iItem41 = sItemSparseArray.get(41);
        if (iItem41 != null) {
            temp = iItem41.average;
        }
        testRecordsTotal.temp = f(temp);

        Item iItem42 = sItemSparseArray.get(42);
        if (iItem42 != null) {
            pressurein = iItem42.average;
        }
        testRecordsTotal.pressurein = f(pressurein);

        Item iItem43 = sItemSparseArray.get(43);
        if (iItem43 != null) {
            Hum = iItem43.average;
        }
        testRecordsTotal.Hum = f(Hum);

        Item iItem44 = sItemSparseArray.get(44);
        if (iItem44 != null) {
            pressureout = iItem44.average;
        }
        testRecordsTotal.pressureout = f(pressureout);
        Item iItem45 = sItemSparseArray.get(45);
        if (iItem45 != null) {
            pressure_yacha = iItem45.average;
        }
        testRecordsTotal.pressure_yacha = f(pressure_yacha);

        Item iItem46 = sItemSparseArray.get(46);
        if (iItem46 != null) {
            Hum20 = iItem46.average;
        }
        testRecordsTotal.Hum20 = f(Hum20);

        Item iItem47 = sItemSparseArray.get(47);
        if (iItem47 != null) {
            pressurein20 = iItem47.average;
        }
        testRecordsTotal.pressurein20 = f(pressurein20);
        testRecordsTotal.end_time = System.currentTimeMillis();

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(testRecordsTotal.end_time);
        long startDatT = calendar.get(Calendar.DAY_OF_YEAR) + calendar.get(Calendar.YEAR) * 1000;
        testRecordsTotal.day_t = startDatT;
        List<Sensor> listSensor = KJDB.getDefaultInstance().findAllByWhere(Sensor.class,
                "sensor_id=" + mSensor.sensor_id);
        if (listSensor != null && listSensor.size() > 0) {
            mSensor.id = listSensor.get(0).id;
            KJDB.getDefaultInstance().update(mSensor);
        } else {
            KJDB.getDefaultInstance().save(mSensor);
        }
        testRecordsTotal.sensor_id = mSensor.sensor_id;
        //更新execl信息
        //mExeclMa.write(testRecordsTotal);
        testRecordsTotal.tagBackup = 0;
        KJDB.getDefaultInstance().update(testRecordsTotal);
        //清楚所有单条记录
        sItemSparseArray.clear();
        sbotelv = "";
    }


    private static float f(float f) {
        DecimalFormat df = new DecimalFormat("0.0");
        String pressure1 = df.format(f);
        try {
            Float ff = Float.parseFloat(pressure1);
            return ff;
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return f;
    }

    public interface ExportCallback {
        void exportProgress(int counts, int remain);

        void finish(int counts, int remain);
    }
}
