package com.gyee.alarm.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gyee.alarm.mapper.auto.ProBasicDeviceModelMetricsMapper;
import com.gyee.alarm.model.auto.*;
import com.gyee.alarm.model.vo.AjaxResult;
import com.gyee.alarm.model.vo.TreeNode;
import com.gyee.alarm.service.DeviceService;
import com.gyee.alarm.service.auto.IProBasicDeviceModelMetricsService;
import com.gyee.alarm.service.auto.IProBasicDeviceModelService;
import com.gyee.alarm.service.auto.IProBasicDeviceService;
import com.gyee.alarm.service.auto.IProBasicDeviceStructureService;
import com.gyee.alarm.util.ExcelUtil;
import com.gyee.alarm.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

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

/**
 * <p>
 * 设备模型 前端控制器
 * </p>
 *
 * @author shilin
 * @since 2023-09-14
 */
@RestController
@RequestMapping("///device")
@Api(value = "设备信息接口")
public class ProBasicDeviceController {

    Logger logger = LogManager.getLogger(ProBasicDeviceController.class);

    @Resource
    private DeviceService deviceService;
    @Resource
    private IProBasicDeviceService proBasicDeviceService;
    @Resource
    private IProBasicDeviceStructureService proBasicDeviceStructureService;
    @Resource
    private IProBasicDeviceModelService proBasicDeviceModelService;
    @Resource
    private  IProBasicDeviceModelMetricsService proBasicDeviceModelMetricsService;

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

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

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

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

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

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

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

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

    //@UserLoginToken
    @PostMapping(value = "/structure")
    @ResponseBody
    public AjaxResult  saveDeviceStructure(@RequestBody ProBasicDeviceStructure ds) {

        deviceService.saveOrUpdateDeviceStructure(ds);

        AjaxResult  wrapper = dataCheck(ds);
        return wrapper;

    }

    public AjaxResult  dataCheck(ProBasicDeviceStructure ds) {

        AjaxResult  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 = AjaxResult.success(msg);
        } else {
            wrapper = AjaxResult.error(msg);
        }

        return wrapper;
    }

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

    @GetMapping(value = "/metrics/{deviceId}/{structureCode}")
    public List<ProBasicDeviceMetrics> getDeviceMetricsBySturctureCode(@PathVariable("deviceId")  String deviceId,
                                                               @PathVariable("structureCode")  String structureCode) {
        return deviceService.getDeviceMetricsByStructureCode(deviceId, structureCode);
    }
    @GetMapping(value = "/metrics/page")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "当前页", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "分页大小", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "deviceId", value = "设备类型", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "structureCode", value = "结构码", required = true, dataType = "string", paramType = "query")})
    @ApiOperation(value = "分页查询标准测点")
    public IPage<ProBasicDeviceMetrics> queryByPage(Integer pageNum,Integer pageSize,String categorydata,String  keyword,String  model,String deviceId,String structureCode
    ){



        Page<ProBasicDeviceMetrics> page = new Page(pageNum, pageSize);
        try {


            IPage<ProBasicDeviceMetrics>  bmpage=deviceService.pageQueryAll(page,deviceId,structureCode);

            if(!bmpage.getRecords().isEmpty())
            {
                List<ProBasicDeviceMetrics> ls=bmpage.getRecords();


                for(ProBasicDeviceMetrics dm:ls)
                {
                    dm.setDeviceModelMetrics(new ArrayList());
                    if(StringUtils.notEmp(dm.getMetricCode()))
                    {
                        dm.setDeviceModelMetrics(  proBasicDeviceModelMetricsService.getDeviceModelMetricsById(dm.getMetricCode()));
                    }

                }
                return bmpage;
            }

        } catch (Exception e) {
            logger.error("操作失败",e);

        }
        return  new Page<>();
    }


    @GetMapping(value = "/metrics/single/{deviceId}/{metricCode}")
    public ProBasicDeviceMetrics 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") String metricId) {
        return deviceService.deleteDeviceMetric(metricId);
    }

    //@UserLoginToken
    @PostMapping(value = "/metrics/single")
    @ResponseBody
    public AjaxResult saveDeviceMetrics(@RequestBody ProBasicDeviceMetrics ds) {

        List<ProBasicDeviceModelMetrics> deviceModelMetrics =ds.getDeviceModelMetrics();
        int result = deviceService.saveOrUpdateDeviceMetric(ds,deviceModelMetrics);

        AjaxResult wrapper = dataCheck(ds);

        return wrapper;

    }

    private AjaxResult dataCheck(ProBasicDeviceMetrics ds) {

        AjaxResult 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 = AjaxResult.success(msg);
        } else {
            wrapper = AjaxResult.error(msg);
        }

        return wrapper;
    }

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

     @ApiOperation(value = "风机型号分页查询")
    @GetMapping(value = "/model/page")
     @ApiImplicitParams({
             @ApiImplicitParam(name = "pagenum", value = "当前页", required = true, dataType = "Integer", paramType = "query"),
             @ApiImplicitParam(name = "pagesize", value = "分页大小", required = true, dataType = "Integer", paramType = "query"),
             @ApiImplicitParam(name = "code", value = "风机型号", required = true, dataType = "string", paramType = "query"),
             @ApiImplicitParam(name = "stationname", value = "场站名称", required = true, dataType = "string", paramType = "query")})
    public AjaxResult queryByPage(Integer pageNum,Integer pageSize, String code, String stationname) {
        Page<ProBasicDeviceModel> page = new Page(pageNum, pageSize);
        IPage<ProBasicDeviceModel> pageResult = deviceService.pageQueryDeviceModel(page, code,stationname);
        return AjaxResult.success("请求成功");
    }

    @GetMapping(value = "/model/{id}")
    public List<ProBasicDeviceModel> 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 AjaxResult saveDeviceModel(@RequestBody ProBasicDeviceModel ds) {

        int result = deviceService.saveOrUpdateDeviceModel(ds);
        AjaxResult wrapper = dataCheck2(ds);

        return wrapper;
    }
    public AjaxResult dataCheck2(ProBasicDeviceModel ds) {

        AjaxResult 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 = AjaxResult.success(msg);
        } else {
            wrapper = AjaxResult.error(msg);
        }

        return wrapper;
    }




    public AjaxResult dataCheck3(ProBasicDeviceMetrics ds) {

        AjaxResult 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 = AjaxResult.success(msg);
        } else {
            wrapper = AjaxResult.error(msg);
        }

        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<ProBasicDeviceMetrics> bindingList = new ArrayList<>();
                //List<Bookcase> bookcaseList = new ArrayList<>();
                //Excel导入导出的单元类
                List<String[]> strings = ExcelUtil.readData(fileType, startRows, true, is);
                //遍历Excel表每一行的数据
                for (String[] str : strings) {
                    ProBasicDeviceMetrics deviceMetrics = new ProBasicDeviceMetrics();
                    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("上传文件失败！");
    }
}
