package com.handset.serialportsensor.utils;

import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;


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

import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.WorkbookUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.kymjs.kjframe.KJDB;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

import static com.handset.serialportsensor.utils.DateStyle.YYYY_MM_DD_HH_MM_SS;


/**
 * Created by zy on 2019/3/4.
 */

public class ExcelMa {
    private final static String TAG = "ExcelMa";

    public static String getSavePath() {
        String path = Environment.getExternalStorageDirectory().getAbsolutePath()
                + File.separator + "htjc" + File.separator + "sensor" + File.separator + "export" + File.separator;
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return path;
    }

    public static File getSavePathFile() {
        String path = Environment.getExternalStorageDirectory().getAbsolutePath()
                + File.separator + "htjc" + File.separator + "sensor" + File.separator + "export" + File.separator;
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return dir;
    }

    public void createExcel() {
        String name = getSavePath() + "workbook.xlsx";
        Workbook wb = new XSSFWorkbook();
        FileOutputStream fileOut = null;
        try {
            fileOut = new FileOutputStream(name);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            wb.write(fileOut);
            fileOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public void stopExport() {
        exportStatus = false;
    }

    public void write(List<TestRecordsTotal> testRecordsTotals, PersistHelper.ExportCallback exportCallback, String timePerfix) {
        exportStatus = true;
        int counts = testRecordsTotals.size();
        int remain = counts;
        for (int i = 0; i < counts; i++) {
            if (!exportStatus) {
                break;
            }
            remain = counts - i;
            exportCallback.exportProgress(counts, remain);
            write(testRecordsTotals.get(i), timePerfix);
            remain = counts - i - 1;
            exportCallback.exportProgress(counts, remain);
            if (!exportStatus) {
                break;
            }
        }
        exportCallback.finish(counts, remain);
    }

    public void write(TestRecordsTotal t, Sensor s, String tiems) {
        File cacheDir = getSavePathFile();
        String sheetNama = t.sensor_id + "(" + tiems + ")";
        String outFileName = "检测结果(" + tiems + ").xlsx";
        File outFile = new File(cacheDir, outFileName);
        InputStream stream = null;
        try {
            stream = new FileInputStream(outFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        XSSFWorkbook workbook = null;
        try {
            if (stream != null) {
                workbook = new XSSFWorkbook(stream);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (workbook == null) {
            workbook = new XSSFWorkbook();
            Log.d(TAG, "write  [t, s]:" + "create workbook");
        }
        XSSFSheet sheet = workbook.getSheet(sheetNama);
        if (sheet == null) {
            sheet = workbook.createSheet(WorkbookUtil.createSafeSheetName(sheetNama));
            Log.d(TAG, "write  [t, s]:" + "create sheet" + sheetNama);
        }
        int rows = sheet.getPhysicalNumberOfRows();
        Log.d(TAG, "write  [t, s]rows:" + rows);
        if (rows == 0) {
            XSSFRow row = sheet.createRow(0);
            row.createCell(0).setCellValue("采样时间戳");
            row.createCell(1).setCellValue("高精度温度（℃）温度");
            row.createCell(2).setCellValue("高精度湿度（%RH）");
            row.createCell(3).setCellValue("高精度内压（kPa）");
            row.createCell(4).setCellValue("高精度外压（kPa）");
            row.createCell(5).setCellValue("差压（kPa");
            row.createCell(6).setCellValue("20℃湿度（%RH）");
            row.createCell(7).setCellValue("20℃压力（kPa）");
            row.createCell(8).setCellValue("传感器编号");
            row.createCell(9).setCellValue("弹型");
            row.createCell(10).setCellValue("弹号");
            row.createCell(11).setCellValue("筒号");
            row.createCell(12).setCellValue("弹筒使用次数");
            row.createCell(13).setCellValue("波特率");
            rows++;
        }

        XSSFRow row = sheet.createRow(rows);
        row.createCell(0).setCellValue(DateUtils.formatMilliesTimestamp(t.end_time, YYYY_MM_DD_HH_MM_SS));
        row.createCell(1).setCellValue(t.temp);
        row.createCell(2).setCellValue(t.Hum);
        row.createCell(3).setCellValue(t.pressurein);
        row.createCell(4).setCellValue(t.pressureout);
        row.createCell(5).setCellValue(t.pressure_yacha);
        row.createCell(6).setCellValue(t.Hum20);
        row.createCell(7).setCellValue(t.pressurein20);
        row.createCell(8).setCellValue(t.sensor_id);
        row.createCell(9).setCellValue(s.egg_type);
        row.createCell(10).setCellValue(s.egg_id);
        row.createCell(11).setCellValue(s.tupe_id);
        row.createCell(12).setCellValue(t.tupe_use_times);
        row.createCell(13).setCellValue(t.botelv);

        FileOutputStream fileOut = null;
        try {
            fileOut = new FileOutputStream(outFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            workbook.write(fileOut);
            fileOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void write(TestRecordsTotal t, String timePerfix) {
        List<Sensor> s = KJDB.getDefaultInstance().findAllByWhere(Sensor.class, "sensor_id = " + t.sensor_id + "");
        if (s == null || s.size() == 0) {
            Log.e(TAG, "write  [t]:" + "save test record failed, no sensor id info" + t.sensor_id + "");
            return;
        }
        write(t, s.get(0), timePerfix);
    }


    protected String getCellAsString(Row row, int c, FormulaEvaluator formulaEvaluator) {
        String value = "";
        try {
            Cell cell = row.getCell(c);
            CellValue cellValue = formulaEvaluator.evaluate(cell);
            switch (cellValue.getCellType()) {
                case Cell.CELL_TYPE_BOOLEAN:
                    value = "" + cellValue.getBooleanValue();
                    break;
                case Cell.CELL_TYPE_NUMERIC:
                    double numericValue = cellValue.getNumberValue();
                    if (HSSFDateUtil.isCellDateFormatted(cell)) {
                        double date = cellValue.getNumberValue();
                        SimpleDateFormat formatter =
                                new SimpleDateFormat("dd/MM/yy");
                        value = formatter.format(HSSFDateUtil.getJavaDate(date));
                    } else {
                        value = "" + numericValue;
                    }
                    break;
                case Cell.CELL_TYPE_STRING:
                    value = "" + cellValue.getStringValue();
                    break;
                default:
            }
        } catch (NullPointerException e) {
            /* proper error handling should be here */
            e.printStackTrace();
        }
        return value;
    }

    public void onWriteClick(TestRecordsTotal testRecordsTotal) {
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet(WorkbookUtil.createSafeSheetName("mysheet"));

        for (int i = 0; i < 10; i++) {
            Row row = sheet.createRow(i);
            Cell cell = row.createCell(0);
            cell.setCellValue(i);
        }
        String outFileName = "filetoshare.xlsx";
        try {

            File cacheDir = getSavePathFile();
            File outFile = new File(cacheDir, outFileName);
            OutputStream outputStream = new FileOutputStream(outFile.getAbsolutePath());
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();

            //share(outFileName, getApplicationContext());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //导出线程的状态
    volatile boolean exportStatus = true;

    public void onReadClick(File file, PersistHelper.ExportCallback exportCallback) {
        exportStatus = true;
        PersistHelper.resetDB();
        int dataItems = 0;
        int remain = dataItems;
        Log.d(TAG, "onReadClick  [view]:");
        try {
            InputStream stream = new FileInputStream(file);
            XSSFWorkbook workbook = new XSSFWorkbook(stream);
            int sheetsNums = workbook.getNumberOfSheets();
            Log.d(TAG, "onReadClick  [file]sheetsNums:" + sheetsNums);
            dataItems = 0;
            for (int i = 0; i < sheetsNums; i++) {
                dataItems += workbook.getSheetAt(i).getPhysicalNumberOfRows() - 1;
            }
            Log.d(TAG, "onReadClick  [file]dataItems:" + dataItems);
            remain = dataItems;
            exportCallback.exportProgress(dataItems, remain);
            Calendar calendar = Calendar.getInstance();
            for (int i = 0; i < sheetsNums; i++) {
                if (!exportStatus) {
                    break;
                }
                Sensor s = new Sensor();
                XSSFSheet sheet = workbook.getSheetAt(i);
                int rowsCount = sheet.getPhysicalNumberOfRows();
                FormulaEvaluator formulaEvaluator = workbook.getCreationHelper().createFormulaEvaluator();
                for (int r = 1; r < rowsCount; r++) {
                    if (!exportStatus) {
                        break;
                    }
                    Row row = sheet.getRow(r);
                    int cellsCount = row.getPhysicalNumberOfCells();
                    TestRecordsTotal testRecordsTotal = new TestRecordsTotal();
                    testRecordsTotal.id = PersistHelper.generateNextTestId();

                    String et = getCellAsString(row, 0, formulaEvaluator);
                    //2019-03-05 14:52:42
                    calendar.set(
                            Integer.parseInt(et.substring(0, 4)),
                            Integer.parseInt(et.substring(5, 7)) - 1,
                            Integer.parseInt(et.substring(8, 10)),
                            Integer.parseInt(et.substring(11, 13)),
                            Integer.parseInt(et.substring(14, 16)),
                            Integer.parseInt(et.substring(17, 19)));
                    String te = getCellAsString(row, 1, formulaEvaluator);
                    testRecordsTotal.temp = Float.parseFloat(te);
                    String hum = getCellAsString(row, 2, formulaEvaluator);
                    testRecordsTotal.Hum = Float.parseFloat(hum);
                    String neiya = getCellAsString(row, 3, formulaEvaluator);
                    testRecordsTotal.pressurein = Float.parseFloat(neiya);
                    String waiya = getCellAsString(row, 4, formulaEvaluator);
                    testRecordsTotal.pressureout = Float.parseFloat(waiya);
                    String yacha = getCellAsString(row, 5, formulaEvaluator);
                    testRecordsTotal.pressure_yacha = Float.parseFloat(yacha);
                    String shidu20 = getCellAsString(row, 6, formulaEvaluator);
                    testRecordsTotal.Hum20 = Float.parseFloat(shidu20);
                    String yali20 = getCellAsString(row, 7, formulaEvaluator);
                    testRecordsTotal.pressurein20 = Float.parseFloat(yali20);
                    testRecordsTotal.end_time = calendar.getTimeInMillis();
                    calendar.setTimeInMillis(testRecordsTotal.end_time);
                    testRecordsTotal.day_t = calendar.get(Calendar.DAY_OF_YEAR) + calendar.get(Calendar.YEAR) * 1000;
                    String sensor_id = getCellAsString(row, 8, formulaEvaluator);
                    if (sensor_id.length() > 8) {
                        sensor_id = sensor_id.replace(".", "").substring(0, 8);
                    }
                    testRecordsTotal.sensor_id = Long.parseLong(sensor_id);
                    s.sensor_id = testRecordsTotal.sensor_id;
                    String danxing = getCellAsString(row, 9, formulaEvaluator);
                    s.egg_type = danxing;
                    String danhao = getCellAsString(row, 10, formulaEvaluator);
                    s.egg_id = danhao;
                    String tonghao = getCellAsString(row, 11, formulaEvaluator);
                    s.tupe_id = tonghao;
                    String tupeUsetimes = getCellAsString(row, 12, formulaEvaluator);
                    if (!TextUtils.isEmpty(tupeUsetimes)) {

                        if (tupeUsetimes.endsWith(".0")) {
                            tupeUsetimes = tupeUsetimes.replace(".0", "");
                        }
                        s.tv_tupe_use_times = tupeUsetimes;
                        testRecordsTotal.tupe_use_times = tupeUsetimes;
                    }

                    String botelv = getCellAsString(row, 13, formulaEvaluator);
                    testRecordsTotal.botelv = botelv;

                    if (KJDB.getDefaultInstance().findById(testRecordsTotal.id, TestRecordsTotal.class) != null) {
                        KJDB.getDefaultInstance().update(testRecordsTotal);
                    } else {
                        KJDB.getDefaultInstance().save(testRecordsTotal);
                    }
                    remain--;
                    exportCallback.exportProgress(dataItems, remain);
                    if (!exportStatus) {
                        break;
                    }
                }
                if (KJDB.getDefaultInstance().findById(s.id, Sensor.class) != null) {
                    KJDB.getDefaultInstance().update(s);
                } else {
                    KJDB.getDefaultInstance().save(s);
                }
            }
            stream.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }

        exportCallback.finish(dataItems, remain);
    }
}
