package com.jiayue.ipfcst.client.protocol2file;

import com.syjy.DataExchangeException;
import com.syjy.FileUtils;
import com.syjy.tunnelinfo.BaseTunnelInfo;
import com.syjy.tunnelinfo.DataPoint;
import com.syjy.tunnelinfo.gathertunnelinfo.*;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.read.biff.BiffException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import wei.yigulu.modbus.domain.datatype.ModbusDataTypeEnum;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 读取配置文件
 *
 * @author: xiuwei
 * @version:
 */
@Slf4j
public class MyReadConfigFile {


    public static List<BaseTunnelInfo> readConfigFile() throws IOException, BiffException {
        List<BaseTunnelInfo> tunnelInfos = new ArrayList<>();
        File configFile = getConfigFile();
        if (configFile == null) {
            return tunnelInfos;
        }
        InputStream is = new FileInputStream(configFile);
        WorkbookSettings ws = new WorkbookSettings();
        ws.setCellValidationDisabled(true);
        Workbook wb = Workbook.getWorkbook(is, ws);
        Sheet[] sheets = wb.getSheets();
        String cellValue;
        BaseTunnelInfo tunnelInfo;
        List<DataPoint> dataPoints;
        MyDataPoint dataPoint;
        ModbusDataTypeEnum dataType;
        int sheetI = 1;
        for (Sheet sheet : sheets) {
            if ("attribute".equals(sheet.getName())) {
                continue;
            }
            try {
                cellValue = getCellContext(sheet.getCell(1, 0));
                switch (cellValue) {
                    case "104M":
                        tunnelInfo = new Gather104TcpTunnelInfo();
                        break;
                    case "ModbusTCPM":
                        tunnelInfo = new GatherModbusTcpTunnelInfo();
                        break;
                    case "ModbusTCPM_锦州阳光":
                        tunnelInfo = new GatherModbusRtuByTcpServerTunnelInfo();
                        break;
                    case "ModbusRTUM":
                        tunnelInfo = new GatherModbusRtuTunnelInfo();
                        break;
                    case "CDTM":
                        tunnelInfo = new GatherCdtRtuTunnelInfo();
                        break;
                    case "GenFile":
                        tunnelInfo = new GenerateFileTunnelInfo();
                        break;
                    case "Calculator":
                        tunnelInfo = new CalculatorTunnelInfo();
                        break;
                    case "气象站":
                        continue;
                    default:
                        throw new DataExchangeException(4002, "通道类型异常");
                }
                tunnelInfo.setId(sheetI + "");
                tunnelInfo.setTunnelName(sheet.getName() + sheetI);
                tunnelInfo.setByRow(sheet.getRow(2));
                tunnelInfo.setRefreshInterval(Integer.parseInt(getCellContext(sheet.getCell(3, 0))));
                dataPoints = new ArrayList<>();
                for (int i = 4; i < sheet.getRows(); i++) {
                    dataPoint = new MyDataPoint();
                    try {
                        dataPoint.setId(Integer.parseInt(getCellContext(sheet.getCell(0, i))));
                    } catch (DataExchangeException e) {
                        continue;
                    }
                    if ("Calculator".equals(getCellContext(sheet.getCell(1, 0)))) {
                        dataPoint.setFormula(getCellContext(sheet.getCell(1, i)));
                    } else {
                        dataPoint.setProtocolPoint(Integer.parseInt(getCellContext(sheet.getCell(1, i))));
                    }
                    cellValue = getCellContext(sheet.getCell(2, i));
                    if ("遥信".equals(cellValue)) {
                        dataType = ModbusDataTypeEnum.A16;
                    } else if ("遥测".equals(cellValue)) {
                        dataType = ModbusDataTypeEnum.ABCD;
                    } else {
                        dataType = ModbusDataTypeEnum.valueOf(cellValue);
                    }
                    dataPoint.setDataType(dataType);
                    dataPoint.setMag(Double.parseDouble(getCellContext(sheet.getCell(3, i))));
                    if (sheet.getRow(i).length > 5) {
                        if ("测风塔".equals(sheet.getCell(4, i).getContents())) {
                            dataPoint.setEquipmentType(EquipmentType.WIND_TOWER);
                            dataPoint.setEquipmentAttr(sheet.getCell(5, i).getContents());
                        } else if ("气象站".equals(sheet.getCell(4, i).getContents())) {
                            dataPoint.setEquipmentType(EquipmentType.WEATHER_STATION);
                            dataPoint.setEquipmentAttr(sheet.getCell(5, i).getContents());
                        }
                    }
                    if (sheet.getRow(i).length > 6 && sheet.getCell(6, i) != null && !"".equals(sheet.getCell(6, i).getContents())) {
                        dataPoint.setSlaveId(Integer.parseInt(getCellContext(sheet.getCell(6, i))));
                    }
                    dataPoints.add(dataPoint);
                }
                tunnelInfo.setDataPoints(dataPoints);
                tunnelInfos.add(tunnelInfo);
            } catch (Exception e) {
                e.printStackTrace();
            }
            sheetI++;
        }
        return tunnelInfos;
    }

    public static String getCellContext(Cell cell) throws DataExchangeException {
        if (cell == null) {
            throw new DataExchangeException(4001, "配置文件缺少配置内容," + cell.getRow() + "行" + cell.getColumn() + "列");
        }
        String val = cell.getContents();
        if (StringUtils.isNoneEmpty(val)) {
            return val;
        } else {
            throw new DataExchangeException(4001, "配置文件缺少配置内容," + cell.getRow() + "行" + cell.getColumn() + "列");
        }
    }

    public static File getConfigFile() {
        // configFile1 是jar包同级目录
        File configFile1 = new File(FileUtils.getResourcesPath(MyReadConfigFile.class));
        //configFile2 是jar包的父级目录的同级目录
        File configFile2 = null;
        if (configFile1 != null) {
            configFile2 = configFile1.getParentFile();
        }
        File[] files = new File[0];
        if (configFile2 != null) {
            files = configFile2.listFiles();
        }
        if (files != null) {
            for (File f : files) {
                if (f.getName().contains("pointconfig.xls")) {
                    log.info("在jar包上层目录发现点表配置文件");
                    return f;
                }
            }
        }
        if (configFile1 != null) {
            files = configFile1.listFiles();
        }
        if (files != null) {
            for (File f : files) {
                if (f.getName().contains("pointconfig.xls")) {
                    log.info("在jar包同级目录发现点表配置文件");
                    return f;
                }
            }
        }
        return null;
    }


}
