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.*;
import com.gyee.wisdom.alarm.sharding.model.TreeNode;
import com.gyee.wisdom.alarm.sharding.service.DeviceService;
import com.gyee.wisdom.alarm.sharding.util.ExcelUtil;
import com.gyee.wisdom.alarm.sharding.util.ResponseWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
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.Date;
import java.util.List;

/**
 * 设备管理类数据接口
 */
@Slf4j
@RestController
@RequestMapping("/device")
@CrossOrigin
@Api(tags = {"设备信息接口"})
public class DeviceController {
    Logger logger = LogManager.getLogger(DeviceController.class);

    @Autowired
    private DeviceService deviceService;


    @GetMapping(value = "/list")
    public List<Device> getAllDevice() {
        return deviceService.getAllDevice();
    }

    @GetMapping(value = "/structure/all")
    public List<DeviceStructure> getAllDeviceStructure() {
        return deviceService.getAllDeviceStructure();
    }

    @GetMapping(value = "/structure/{deviceId}")
    public List<DeviceStructure> getDeviceStructureByDeviceId(@PathVariable("deviceId")  String deviceId) {
        return deviceService.getDeviceStructureByDeviceId(deviceId);
    }

    @GetMapping(value = "/structure/{deviceId}/{nodeCode}")
    public List<DeviceStructure> getAllDeviceStructure(@PathVariable("deviceId")  String deviceId,
                                                       @PathVariable("nodeCode")  String nodeCode) {
        return deviceService.getDeviceStructureChildNode(deviceId, nodeCode);
    }

    @GetMapping(value = "/structure/single/{deviceId}/{nodeCode}")
    public DeviceStructure getDeviceStructureByCode(@PathVariable("deviceId")  String deviceId,
                                                       @PathVariable("nodeCode")  String nodeCode) {
        return deviceService.getDeviceStructureByCode(deviceId, nodeCode);
    }

    @GetMapping(value = "/structure/tree/{deviceId}/{nodeCode}")
    public TreeNode<DeviceStructure> getDeviceStructureTree(@PathVariable("deviceId")  String deviceId,
                                                              @PathVariable("nodeCode")  String nodeCode) {
        return deviceService.getDeviceStructureTree(deviceId, nodeCode);
    }

    @GetMapping(value = "/structure/tree/{deviceId}")
    public TreeNode<DeviceStructure> getDeviceStructureTree(@PathVariable("deviceId")  String deviceId) {
        return deviceService.getDeviceStructureTree(deviceId);
    }

    @DeleteMapping(value = "/structure/delete/{dsId}")
    public int deleteDeviceStructure(@PathVariable("dsId") long dsId) {
        return deviceService.deleteDeviceStructure(dsId);
    }

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

    }

    private ResponseWrapper<DeviceStructure> dataCheck(DeviceStructure ds) {

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

        if (ds.getCode() == null || ds.getCode().equals("")) {
            msg = "结构编码不能为空";
            result = false;
        } else if (ds.getParentcode() == null || ds.getParentcode().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;
    }

    @GetMapping(value = "/metrics/{deviceId}")
    public List<DeviceMetrics> getDeviceMetricsByDeviceId(@PathVariable("deviceId")  String deviceId) {
        return deviceService.getDeviceMetricsByDeviceId(deviceId);
    }

    @GetMapping(value = "/metrics/{deviceId}/{structureCode}")
    public List<DeviceMetrics> getDeviceMetricsBySturctureCode(@PathVariable("deviceId")  String deviceId,
                                                       @PathVariable("structureCode")  String structureCode) {
        return deviceService.getDeviceMetricsByStructureCode(deviceId, structureCode);
    }
    @GetMapping(value = "/metrics/page")
    @ApiOperation("分页查询标准测点")
    public IPage<DeviceMetrics> queryByPage(
            @ApiParam(value = "当前页")  @RequestParam(value = "pagenum")Integer pageNum,
            @ApiParam(value = "分页大小")@RequestParam(value = "pagesize")Integer pageSize,
            @ApiParam(value = "测点类型 AI-遥测 CI-计算 MI-遥调")  @RequestParam(value = "categorydata")String categorydata,
            @ApiParam(value = "名称关键字")  @RequestParam(value = "keyword",required = false)String  keyword,
            @ApiParam(value = "型号")  @RequestParam(value = "model",required = false)String  model,
            @ApiParam(value = "设备类型") @RequestParam(value = "deviceId", required = false) String deviceId,
            @ApiParam(value = "结构码")   @RequestParam(value = "structureCode",required = false) String structureCode
    ){
        Page<DeviceMetrics> page =new Page(pageNum,pageSize);

        try {
            return  deviceService.pageQueryAll(page,deviceId,categorydata,keyword,model,structureCode);
        } catch (Exception e) {
            logger.error("操作失败",e);
            return null;
        }

    }


    @GetMapping(value = "/metrics/single/{deviceId}/{metricCode}")
    public DeviceMetrics getDeviceMetricsByCode(@PathVariable("deviceId")  String deviceId,
                                                    @PathVariable("metricCode")  String metricCode) {
        return deviceService.getDeviceMetricsByCode(deviceId, metricCode);
    }


    @DeleteMapping(value = "/metrics/single/delete/{metricId}")
    public int deleteDeviceMetric(@PathVariable("metricId") long metricId) {
        return deviceService.deleteDeviceMetric(metricId);
    }

    //@UserLoginToken
    @PostMapping(value = "/metrics/single")
    @ResponseBody
    public ResponseWrapper<DeviceMetrics> saveDeviceMetrics(@RequestBody DeviceMetrics ds) {
        ResponseWrapper<DeviceMetrics> wrapper = dataCheck(ds);
        if (wrapper.getSuccess()) {
            //mybatis 操作数据库成功会返回影响的条数,如果成功则为1,失败为0
            List<DeviceModelMetrics> deviceModelMetrics =ds.getDeviceModelMetrics();
            int result = deviceService.saveOrUpdateDeviceMetric(ds,deviceModelMetrics);
            if (result <= 0) {
                wrapper.setSuccess(false);
                wrapper.setMsg("操作数据库失败");
            }
        }
        return wrapper;

    }

    private ResponseWrapper<DeviceMetrics> dataCheck(DeviceMetrics ds) {

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

        if (ds.getMetriccode() == null || ds.getMetriccode().equals("")) {
            msg = "指标编码不能为空";
            result = false;
        } else if (ds.getStructurecode() == null || ds.getStructurecode().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 (deviceService.getDeviceMetricsByCode(ds.getDeviceid(), ds.getMetriccode()) != null) {
            msg = "指标编码重复！！";
            result = false;
        }*/

        if (result) {
            wrapper = ResponseWrapper.success(msg, ds);
        } else {
            wrapper = ResponseWrapper.error(msg, ds);
        }

        return wrapper;
    }

    @GetMapping(value = "/model/list")
    public List<DeviceModel> getDeviceModelList() {
        return deviceService.getDeviceModelList();
    }

    @GetMapping(value = "/model/{id}")
    public List<DeviceModel> getDeviceModelsById(@PathVariable("id")  String id) {
        return deviceService.getDeviceModelsById(id);
    }


    @DeleteMapping(value = "/model/delete/{id}")
    public int deleteDeviceModel(@PathVariable("id") int id) {
        return deviceService.deleteDeviceModel(id);
    }

    @PostMapping(value = "/model")
    @ResponseBody
    public ResponseWrapper<DeviceModel> saveDeviceModel(@RequestBody DeviceModel ds) {
        ResponseWrapper<DeviceModel> wrapper = dataCheck2(ds);
        if (wrapper.getSuccess()) {
            //mybatis 操作数据库成功会返回影响的条数,如果成功则为1,失败为0
            int result = deviceService.saveOrUpdateDeviceModel(ds);
            if (result <= 0) {
                wrapper.setSuccess(false);
                wrapper.setMsg("操作数据库失败");
            }
        }
        return wrapper;
    }
    private ResponseWrapper<DeviceModel> dataCheck2(DeviceModel ds) {

        ResponseWrapper<DeviceModel> 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 (deviceService.getDeviceModelByCode(ds.getDeviceid(), ds.getCode()) != null) {
            msg = "指标编码重复！！";
            result = false;
        }

        if (result) {
            wrapper = ResponseWrapper.success(msg, ds);
        } else {
            wrapper = ResponseWrapper.error(msg, ds);
        }

        return wrapper;
    }


    //@RequestMapping("input")
    @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<DeviceMetrics> bindingList = new ArrayList<>();
                //List<Bookcase> bookcaseList = new ArrayList<>();
                //Excel导入导出的单元类
                List<String[]> strings = ExcelUtil.readData(fileType, startRows, true, is);
                //遍历Excel表每一行的数据
                for (String[] str : strings) {
                    DeviceMetrics deviceMetrics = new DeviceMetrics();
                    if(str[0]==null||str[0].length()<=0){
                        deviceMetrics.setStructurecode("1010102");
                    }else {
                        deviceMetrics.setStructurecode(str[0]);
                    }
                    deviceMetrics.setMetriccode(str[1]);
                    deviceMetrics.setName(str[2]);
                    deviceMetrics.setEnname(str[3]);
                    deviceMetrics.setUnitname(str[4]);
                    deviceMetrics.setCategorydata(str[5]);
                    deviceMetrics.setCategorysci(str[6]);
                    deviceMetrics.setDescription(str[7]);
                    bindingList.add(deviceMetrics);
                }
                int bookState = deviceService.insertOrUpdate(bindingList);
                if(bookState>0){
                    return AjaxResult.success("上传文件成功！");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return AjaxResult.error("上传文件失败！");
    }

    private ResponseWrapper<DeviceMetrics> dataCheck3(DeviceMetrics ds) {

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

        if (ds.getMetriccode() == null || ds.getMetriccode().equals("")) {
            msg = "指标编码不能为空";
            result = false;
        } else if (ds.getStructurecode() == null || ds.getStructurecode().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;
    }

}
