package com.gyee.wisdom.alarm.sharding.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gyee.wisdom.alarm.sharding.config.AjaxResult;
import com.gyee.wisdom.alarm.sharding.entity.DeviceFaultMode;
import com.gyee.wisdom.alarm.sharding.entity.DeviceMetrics;
import com.gyee.wisdom.alarm.sharding.entity.FaultInfo;
import com.gyee.wisdom.alarm.sharding.service.DeviceFaultModeService;
import com.gyee.wisdom.alarm.sharding.util.ExcelUtil;
import com.gyee.wisdom.alarm.sharding.util.ResponseWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/device/faultmode")
@CrossOrigin
public class DeviceFaultModeController {

    @Autowired
    private DeviceFaultModeService deviceFaultModeService;


    @GetMapping(value = "/{deviceId}")
    public List<DeviceFaultMode> getDeviceFaultModeByDeviceId(@PathVariable("deviceId")  String deviceId) {
        return deviceFaultModeService.getDeviceFaultModeByDeviceId(deviceId);
    }

    @GetMapping(value = "/{deviceId}/{structurecode}")
    public List<DeviceFaultMode> getDeviceFaultModeBySturctureCode(@PathVariable("deviceId")  String deviceId,
                                                               @PathVariable("structurecode")  String structurecode) {
        return deviceFaultModeService.getDeviceFaultModeByStructureCode(deviceId, structurecode);
    }


    @GetMapping(value = "/single/{code}")
    public DeviceFaultMode getDeviceFaultModeByCode(@PathVariable("code")  String code) {
        return deviceFaultModeService.getDeviceFaultModeByCode(code);
    }


    @DeleteMapping(value = "/delete/{id}")
    public int deleteDeviceFaultMode(@PathVariable("id") Long id) {
        int result = deviceFaultModeService.deleteDeviceFaultMode(id);
        return result;
    }

    @PostMapping()
    @ResponseBody
    public ResponseWrapper<DeviceFaultMode> saveDeviceFaultMode(@RequestBody DeviceFaultMode ds) {
        ResponseWrapper<DeviceFaultMode> wrapper = dataCheck(ds);
        if (wrapper.getSuccess()) {
            //mybatis 操作数据库成功会返回影响的条数,如果成功则为1,失败为0
            int result = deviceFaultModeService.saveorUpdateDeviceFaultMode(ds);
            if (result <= 0) {
                wrapper.setSuccess(false);
                wrapper.setMsg("操作数据库失败");
            }
        }
        return wrapper;
    }

    private ResponseWrapper<DeviceFaultMode> dataCheck(DeviceFaultMode ds) {

        ResponseWrapper<DeviceFaultMode> wrapper = null;
        String msg = "";
        boolean result = true;

        if (ds.getCode() == null || ds.getCode().equals("")) {
            msg = "结构编码不能为空";
            result = false;
        } else if (ds.getDeviceid() == null || ds.getDeviceid().equals("")) {
            msg = "设备ID不能为空";
            result = false;
        } else if (ds.getName() == null || ds.getName().equals("")) {
            msg = "名称不能为空";
            result = false;
        }
        if (result) {
            wrapper = ResponseWrapper.success(msg, ds);
        } else {
            wrapper = ResponseWrapper.error(msg, ds);
        }
        return wrapper;
    }

    @PostMapping(value ="/input")
    @ResponseBody
    public AjaxResult InputExcel(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        if (!file.isEmpty()) {
            try {
                //获取原始的文件名
                String originalFilename = file.getOriginalFilename();
                //获取文件类型
                String fileType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length());
                //默认从第一行开始读取
                Integer startRows = 1;
                //获取输入流
                InputStream is = file.getInputStream();
                List<DeviceFaultMode> bindingList = new ArrayList<>();
                //List<Bookcase> bookcaseList = new ArrayList<>();
                //Excel导入导出的单元类
                List<String[]> strings = ExcelUtil.readData(fileType, startRows, true, is);
                //遍历Excel表每一行的数据
                for (String[] str : strings) {
                    DeviceFaultMode deviceFaultMode = new DeviceFaultMode();
                    if(str[0]==null||str[0].length()<=0){
                        deviceFaultMode.setStructurecode("1010102");
                    }else {
                        deviceFaultMode.setStructurecode(str[0]);
                    }
                    deviceFaultMode.setName(str[1]);
                    deviceFaultMode.setCode(str[2]);
                    deviceFaultMode.setOccurence(Integer.parseInt(str[3]));
                    deviceFaultMode.setSeverity(Integer.parseInt(str[4]));
                    deviceFaultMode.setDetection(Integer.parseInt(str[5]));
                    deviceFaultMode.setCause(str[6]);
                    deviceFaultMode.setEffects(str[7]);
                    deviceFaultMode.setMeasure(str[8]);
                    bindingList.add(deviceFaultMode);
                }
                int bookState = deviceFaultModeService.insertOrUpdate(bindingList);
                if(bookState>0){
                    return AjaxResult.success("上传文件成功！");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return AjaxResult.error("上传文件失败！");
    }


    private ResponseWrapper<DeviceFaultMode> dataCheck2(DeviceFaultMode ds) {

        ResponseWrapper<DeviceFaultMode> wrapper = null;
        String msg = "";
        boolean result = true;

        if (ds.getCode() == null || ds.getCode().equals("")) {
            msg = "结构编码不能为空";
            result = false;
        }  else if (ds.getName() == null || ds.getName().equals("")) {
            msg = "名称不能为空";
            result = false;
        }
        if (result) {
            wrapper = ResponseWrapper.success(msg, ds);
        } else {
            wrapper = ResponseWrapper.error(msg, ds);
        }
        return wrapper;
    }
}
