package net.vtstar.zhongtong.avi;

import io.netty.buffer.ByteBuf;
import lombok.extern.slf4j.Slf4j;
import net.vtstar.protocol.modbus.tcp.netty.packet.ReadCoilsRequest;
import net.vtstar.protocol.modbus.tcp.netty.packet.ReadCoilsResponse;
import net.vtstar.protocol.modbus.tcp.netty.packet.ReadInputDiscretesRequest;
import net.vtstar.protocol.modbus.tcp.netty.packet.ReadInputDiscretesResponse;
import net.vtstar.protocol.modbus.tcp.netty.service.ModbusTemplate;
import net.vtstar.protocol.modbus.tcp.netty.utils.PoolKey;
import net.vtstar.scada.base.equipmgt.domain.EquipDataTemplate;
import net.vtstar.scada.base.equipmgt.domain.EquipDataTemplateItem;
import net.vtstar.scada.base.equipmgt.mapper.EquipDataTemplateItemMapper;
import net.vtstar.scada.base.equipmgt.mapper.EquipDataTemplateMapper;
import net.vtstar.user.mybatis.provider.WhereFilter;
import net.vtstar.utils.asserts.ParamAssert;
import net.vtstar.zhongtong.avi.monitoring.domain.Warning;
import net.vtstar.zhongtong.avi.monitoring.mapper.WarningMapper;
import net.vtstar.zhongtong.avi.sqlserver.domain.MesWorkOrderInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@ActiveProfiles("xdw")
public class ModbusTest {

    @Autowired
    private ModbusTemplate modbusTemplate;
    @Autowired
    private WarningMapper warningMapper;
    @Autowired
    private EquipDataTemplateItemMapper itemMapper;
    @Autowired
    private EquipDataTemplateMapper templateMapper;

    @Test
    public void test() throws Exception {

        ReadCoilsRequest readCoilsRequest = new ReadCoilsRequest(1, 0, 5);
        PoolKey poolKey = new PoolKey("localhost", 502);
        ReadCoilsResponse response = modbusTemplate.execute(poolKey, readCoilsRequest, ReadCoilsResponse.class);
        ByteBuf body = response.getBody();
        byte b = body.readByte();
        System.out.println("___" + b);
//        byte[] array = body.array();
    }
    @Test
    public void testMoodbus() throws Exception {
        PoolKey poolKey = new PoolKey("localhost", 504);
        ReadInputDiscretesRequest request = new ReadInputDiscretesRequest(41, 4807, 1);
        ReadInputDiscretesResponse response = modbusTemplate.execute(poolKey, request, ReadInputDiscretesResponse.class);
        ByteBuf body = response.getBody();
        byte b = body.readByte();
        System.out.println("___" + b);
    }

    private static final String SUFFIX_2003 = ".xls";
    private static final String SUFFIX_2007 = ".xlsx";
    private Map<String, Integer> map = new HashMap<>();

    @Test
    public void parsingExcel() {
        map.put("KS111腻子烘干室335", 3);
        map.put("KS1053工位电泳烘干室302", 1);
        map.put("KS1062工位电泳烘干室303", 1);
        map.put("KS113腻子烘干室336", 3);
        map.put("KS112腻子烘干室377", 3);
        map.put("KS114中途烘干室351", 3);
        map.put("KS115中途烘干室352", 3);
        map.put("KS116面漆烘干室360", 7);
        map.put("KS117面漆烘干室362", 7);
        map.put("KS118面漆烘干室364", 7);
        map.put("KS119彩条烘干室366", 6);
        map.put("KS120彩条烘干室368", 6);
        map.put("KS121彩条烘干室370", 6);
        map.put("KS122彩条烘干室372", 6);
        map.put("KS123罩光漆烘干室373", 6);
        map.put("KS142A中涂喷漆室349", 4);
        map.put("KS143A中涂喷漆室350", 4);
        map.put("KS144A面漆喷漆室359", 5);
        map.put("KS145面漆喷漆室361", 5);
        map.put("KS146A面漆喷漆室363", 5);
        map.put("KS147A彩条喷漆室365", 6);
        map.put("KS149A彩条喷漆室367", 6);
        map.put("KS148A彩条喷漆室369", 6);
        map.put("KS150A彩条喷漆室371", 6);
        map.put("KS151A罩光喷漆室374", 6);
        map.put("前处理", 1);
        map.put("超滤UF", 1);
        map.put("纯水OR", 1);
        map.put("前处理空中行车", 1);
        List<Warning> list = new ArrayList<>();
        File file = new File("Y:/前处理纯水超滤行车.xlsx");
        //获取文件的名字
        Workbook workbook = null;
        String fileName = file.getName();
        try {
            if (fileName.endsWith(SUFFIX_2003)) {
                workbook = new HSSFWorkbook(new FileInputStream(file));
            } else if (fileName.endsWith(SUFFIX_2007)) {
                workbook = new XSSFWorkbook(new FileInputStream(file));
            }
        } catch (Exception e) {
            log.error("读取文件错误: {}", e.getMessage());
        }
        ParamAssert.notNull(workbook, "文件名 :" + file + "不符合EXCEL的格式要求!标准格式:.xls/.xlsx");
        //获取所有的工作表的的数量
        int numOfSheet = workbook.getNumberOfSheets();
        //遍历这个这些表
        for (int i = 0; i < numOfSheet; i++) {
            //获取一个sheet也就是一个工作簿
            Sheet sheet = workbook.getSheetAt(i);
            int lastRowNum = sheet.getLastRowNum();
            //从第一行开始第一行一般是标题
            for (int j = 0; j <= lastRowNum; j++) {
                Row row = sheet.getRow(j);
                if (null == row) {
                    continue;
                }
                Warning warning = new Warning();
                //描述
                if (row.getCell(0) != null) {
                    row.getCell(0).setCellType(CellType.STRING);
                    String info = row.getCell(0).getStringCellValue();
                    if (StringUtils.isEmpty(info)) {
                        continue;
                    }
                    warning.setInfo(info);
                }
                //类型
                if (row.getCell(3) != null) {
                    row.getCell(3).setCellType(CellType.STRING);
                    String type = row.getCell(3).getStringCellValue();
                    if (null == type) {
                        continue;
                    }
                    warning.setType(type);
                }
                //解决
                if (row.getCell(4) != null) {
                    row.getCell(4).setCellType(CellType.STRING);
                    String name = row.getCell(4).getStringCellValue();
                    warning.setName(name);
                }
                //创建warning, 获取code
                warningMapper.insertRecord(warning);
                Long id = warning.getId();

                //产线
                String name = "";
                if (row.getCell(1) != null) {
                    row.getCell(1).setCellType(CellType.STRING);
                    name = row.getCell(1).getStringCellValue();
                }
                String address = "";
                if (row.getCell(2) != null) {
                    row.getCell(2).setCellType(CellType.STRING);
                    address = row.getCell(2).getStringCellValue();
                }
                EquipDataTemplate byName = templateMapper.findByName(name);
                if (byName == null){
                    log.error(name);
                    return;
                }
                EquipDataTemplateItem item = new EquipDataTemplateItem();
                item.setTemplateId(byName.getId());
                item.setFieldName("warning:" + map.get(name) + ":" + id);

                if (address.contains(".")){
                    String[] split = address.substring(1).split("\\.");
                    item.setAddress(Integer.valueOf(split[0]) * 8 + Integer.valueOf(split[1]));
                }else{
                    item.setAddress(Integer.valueOf(address.substring(1)) * 8);
                }

                item.setFunctionCode(2);
                item.setFieldType("BIT");
                item.setLength(1);
                item.setFieldDesc(name);
                itemMapper.insert(item);
                list.add(warning);
            }
            log.error("加载数据: {} 条", list.size());
            List<Warning> list1 = warningMapper.findList(new WhereFilter(), Warning.class);
            for (Warning warning : list1){
                warning.setCode(warning.getId() + "");
                warningMapper.update(warning);
            }

        }
    }
}
