package cn.cecep.talroad.controller;

import cn.cecep.talroad.common.core.exception.CommonException;
import cn.cecep.talroad.common.core.utils.poi.ExcelUtil;
import cn.cecep.talroad.common.core.web.controller.BasesController;
import cn.cecep.talroad.common.core.web.domain.AjaxResults;
import cn.cecep.talroad.common.log.annotation.Log;
import cn.cecep.talroad.common.log.enums.BusinessType;
import cn.cecep.talroad.common.security.utils.SecurityUtils;
import cn.cecep.talroad.domain.BasDevice;
import cn.cecep.talroad.domain.BasParam;
import cn.cecep.talroad.domain.BasProductionDeviceOperationLog;
import cn.cecep.talroad.domain.PcFactory;
import cn.cecep.talroad.enums.EnStatTimeType;
import cn.cecep.talroad.service.IBasDeviceService;
import cn.cecep.talroad.service.IBasParamService;
import cn.cecep.talroad.service.IBasProductionDeviceOperationLogService;
import cn.cecep.talroad.service.IPcFactoryService;
import cn.cecep.talroad.util.CsvUtils;
import cn.cecep.talroad.vo.*;
import cn.cecep.talroad.vo.query.BasDeviceDCSSystemParamQuery;
import cn.cecep.talroad.vo.query.BasDeviceQuery;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.*;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.PrimitiveIterator;
import java.util.stream.IntStream;


/**
 * * 开发公司：中节能天融科技有限公司
 * 设备信息(有组织)Controller 控制层
 *
 * @author szhpt
 * @date 2023-01-10
 */
@Api(tags = "基础信息--设备信息(有组织)")
@RestController
@RequestMapping("/basDevice")
public class BasDeviceController extends BasesController {
    @Autowired
    private IBasDeviceService basDeviceService;
    @Autowired
    private IPcFactoryService pcFactoryService;

    @Autowired
    private IBasParamService paramService;
    @Autowired
    private IBasProductionDeviceOperationLogService basProductionDeviceOperationLogService;

    @Autowired
    private IPcFactoryService factoryService;

    /**
     * 查询设备信息(有组织)列表
     */
    @ApiOperation(value = "查询设备信息(有组织)")
    @GetMapping("/list")
    public AjaxResults<IPage<BasDevice>> list(BasDeviceQuery basDevice) {
        // 若未指定企业，则默认当前用户企业
        Long roleId = SecurityUtils.getLoginUser().getSysUser().getRoles().get(0).getRoleId();
        if(ObjectUtil.equal(roleId,10L)){
            if (StringUtils.isEmpty(basDevice.getFactoryId())) {
                String factoryId = SecurityUtils.getLoginUser().getSysUser().getFactoryId();
                basDevice.setFactoryId(factoryId);
            }
        }
        basDevice.setStatus(1L);
        Page<BasDevice> page = new Page<>(basDevice.getPageNum(), basDevice.getPageSize());

        QueryWrapper<BasDevice> lambdaQueryWrapper = BasDeviceQuery.createLambdaQueryWrapper(basDevice);

        // 若未指定行业
        if (StringUtils.isEmpty(basDevice.getIndustry())) {
            lambdaQueryWrapper.in("industry", "GT,DL,JH,BL,SN,FS".split(","));
        }

        IPage<BasDevice> list = basDeviceService.page(page, lambdaQueryWrapper);
        return AjaxResults.success(list);
    }

    /**
     * DCS系统参数设置列表
     */
    @ApiOperation(value = "DCS系统参数设置列表")
    @GetMapping("/listDCSSystemParam")
    public AjaxResults<IPage<BasDeviceDCSSystemParamVo>> listDCSSystemParam(BasDeviceDCSSystemParamQuery query) {
        Long roleId = SecurityUtils.getLoginUser().getSysUser().getRoles().get(0).getRoleId();
        if(ObjectUtil.equal(roleId,10L)) {
            String factoryId = SecurityUtils.getLoginUser().getSysUser().getFactoryId();
            query.setFactoryId(factoryId);
        }
        if (StringUtils.isNotEmpty(query.getFactoryId())) {
            PcFactory pcFactory = pcFactoryService.getById(query.getFactoryId());
            if(StringUtils.isBlank(pcFactory.getIndustryCategory())){
                query.setIndustry("------");
            }else{
                query.setIndustry(pcFactory.getIndustryCategory());
            }
        }
        IPage<BasDeviceDCSSystemParamVo> list = basDeviceService.listDCSSystemParam(query);

        return AjaxResults.success(list);
    }

    /**
     * 设备信息(有组织)下拉框
     */
    @ApiOperation(value = "设备信息(有组织)下拉框")
    @GetMapping("/basDeviceSelect")
    public AjaxResults<List<BasDevice>> basDeviceSelect(BasDeviceQuery basDevice) {
        Long roleId = SecurityUtils.getLoginUser().getSysUser().getRoles().get(0).getRoleId();
        if(ObjectUtil.equal(roleId,10L)) {
            String factoryId = SecurityUtils.getLoginUser().getSysUser().getFactoryId();
            basDevice.setFactoryId(factoryId);
            basDevice.setStatus(1L);
        }
        List<BasDevice> list = basDeviceService.list(BasDeviceQuery.createLambdaQueryWrapper(basDevice));
        return AjaxResults.success(list);
    }

    /**
     * 工序下拉框
     */
    @ApiOperation(value = "工序下拉框")
    @GetMapping("/workStepSelect")
    public AjaxResults<List<String>> workStepSelect(BasDeviceQuery basDevice) {
        Long roleId = SecurityUtils.getLoginUser().getSysUser().getRoles().get(0).getRoleId();
        if(ObjectUtil.equal(roleId,10L)) {
            String factoryId = SecurityUtils.getLoginUser().getSysUser().getFactoryId();
            PcFactory pcFactory = pcFactoryService.getById(factoryId);
            basDevice.setFactoryId(factoryId);
            basDevice.setIndustry(pcFactory.getIndustryCategory());
        }
        List<String> list = basDeviceService.groupByWorkStepSelect(basDevice.getFactoryId(), basDevice.getIndustry());
        return AjaxResults.success(list);

    }

    /**
     * 工序下拉框
     */
    @ApiOperation(value = "参数名称下拉框")
    @GetMapping("/paramNameSelect")
    public AjaxResults<List<String>> paramNameSelect(BasDeviceQuery basDevice) {
        Long roleId = SecurityUtils.getLoginUser().getSysUser().getRoles().get(0).getRoleId();
        if(ObjectUtil.equal(roleId,10L)) {
            String factoryId = SecurityUtils.getLoginUser().getSysUser().getFactoryId();
            PcFactory pcFactory = pcFactoryService.getById(factoryId);
            basDevice.setFactoryId(factoryId);
            basDevice.setIndustry(pcFactory.getIndustryCategory());
        }
        List<String> list = basDeviceService.groupByParamNameSelect(basDevice.getFactoryId(), basDevice.getIndustry());
        return AjaxResults.success(list);
    }

    /**
     * 导出设备信息(有组织)列表
     */
    @ApiOperation(value = "导出设备信息(有组织)")
    @Log(title = "设备信息(有组织)", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, @RequestBody BasDeviceQuery basDevice) {
        Long roleId = SecurityUtils.getLoginUser().getSysUser().getRoles().get(0).getRoleId();
        if(ObjectUtil.equal(roleId,10L)) {
            if (StringUtils.isEmpty(basDevice.getFactoryId())) {
                String factoryId = SecurityUtils.getLoginUser().getSysUser().getFactoryId();
                basDevice.setFactoryId(factoryId);
            }
        }
        basDevice.setStatus(1L);
        QueryWrapper<BasDevice> lambdaQueryWrapper = BasDeviceQuery.createLambdaQueryWrapper(basDevice);
        //lambdaQueryWrapper.notIn("type", "XK,EL,TC".split(","));
        lambdaQueryWrapper.in("industry", "GT,DL,JH,BL,SN,FS".split(","));

        lambdaQueryWrapper.eq(basDevice.getStatus() != null, "status", basDevice.getStatus());
        List<BasDevice> list = basDeviceService.list(lambdaQueryWrapper);


        List<BasDeviceExcelVo> basDeviceExcelVoList = new ArrayList<>();
        PrimitiveIterator.OfInt iterator = IntStream.iterate(1, k -> k + 1).iterator();
        list.forEach(e -> {
            BasDeviceExcelVo basDeviceExcelVo = new BasDeviceExcelVo();
            BeanUtil.copyProperties(e, basDeviceExcelVo);
            basDeviceExcelVo.setSerialnumber(iterator.next());
            basDeviceExcelVoList.add(basDeviceExcelVo);
        });

        ExcelUtil<BasDeviceExcelVo> util = new ExcelUtil<BasDeviceExcelVo>(BasDeviceExcelVo.class);
        util.exportExcel(response, basDeviceExcelVoList, "生产设施坐标");
    }

    /**
     * 导出设备信息(有组织)列表
     */
    @ApiOperation(value = "导出DCS系统参数设置")
    @Log(title = "导出DCS系统参数设置", businessType = BusinessType.EXPORT)
    @PostMapping("/exportDCSSystemParam")
    public void exportDCSSystemParam(HttpServletResponse response, @RequestBody BasDeviceDCSSystemParamQuery query) {
        Long roleId = SecurityUtils.getLoginUser().getSysUser().getRoles().get(0).getRoleId();
        if(ObjectUtil.equal(roleId,10L)) {
            String factoryId = SecurityUtils.getLoginUser().getSysUser().getFactoryId();
            PcFactory pcFactory = pcFactoryService.getById(factoryId);
            query.setPageNum(1);
            query.setPageSize(Integer.MAX_VALUE);
            query.setFactoryId(factoryId);
            if (StringUtils.isBlank(pcFactory.getIndustryCategory())) {
                query.setIndustry("------");
            } else {
                query.setIndustry(pcFactory.getIndustryCategory());
            }
        }
        List<BasDeviceDCSSystemParamExcelVo> list = basDeviceService.exportDCSSystemParam(query);
        List<BasDeviceDCSSystemParamExcelVo> basDeviceExcelVoList = new ArrayList<>();
        PrimitiveIterator.OfInt iterator = IntStream.iterate(1, k -> k + 1).iterator();
        list.forEach(e -> {
            e.setSerialnumber(iterator.next());
        });
        ExcelUtil<BasDeviceDCSSystemParamExcelVo> util = new ExcelUtil<BasDeviceDCSSystemParamExcelVo>(BasDeviceDCSSystemParamExcelVo.class);
        util.exportExcel(response, list, "DCS系统参数设置数据");
    }

    /**
     * 获取设备信息(有组织)详细信息
     */
    @ApiOperation(value = "获取设备信息(有组织)详细信息")
    @GetMapping(value = "/{deviceId}")
    public AjaxResults<BasDevice> getInfo(@PathVariable("deviceId") String id) {
        return AjaxResults.success(basDeviceService.getById(id));
    }

    /**
     * 新增设备信息(有组织)
     */
    @ApiOperation(value = "新增设备信息(有组织)")
    @Log(title = "设备信息(有组织)", businessType = BusinessType.INSERT)
    @PostMapping(value = "/add")
    public AjaxResults<Boolean> add(@RequestBody BasDevice basDevice) {
        return toAjax(basDeviceService.save(basDevice));
    }

    /**
     * 修改设备信息(有组织)
     */
    @ApiOperation(value = "修改设备信息(有组织)")
    @Log(title = "设备信息(有组织)", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/edit")
    public AjaxResults<Boolean> edit(@RequestBody BasDeviceVo basDeviceVo) {
        if (ObjectUtil.isEmpty(basDeviceVo)) {
            throw new InvalidParameterException("参数为空");
        }
        if (ObjectUtil.isEmpty(basDeviceVo.getDeviceId())) {
            throw new InvalidParameterException("参数id为空");
        }
        BasDevice basDevice = basDeviceService.getById(basDeviceVo.getDeviceId());
        if (ObjectUtil.isEmpty(basDevice)) {
            throw new CommonException(StrUtil.format("根据id{}查询不到数据", basDeviceVo.getDeviceId()));
        }
        //赋值
        BeanUtil.copyProperties(basDeviceVo, basDevice);
        return toAjax(basDeviceService.saveOrUpdate(basDevice));
    }


    /**
     * 修改设备信息(有组织)
     */
    @ApiOperation(value = "批量修改设备信息(有组织)")
    @Log(title = "批量分表计电--设备点位", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/editBatch")
    public AjaxResults<Boolean> editBatch(@RequestBody BasDeviceVo[] BasDeviceVoArr) {
        if (BasDeviceVoArr == null || BasDeviceVoArr.length < 1) {
            throw new InvalidParameterException("参数为空");
        }
        for(BasDeviceVo bs:BasDeviceVoArr){
            bs.setLon(bs.getLonMap());
            bs.setLat(bs.getLatMap());
        }
        basDeviceService.editBatch(BasDeviceVoArr);
        return toAjax(true);
    }

    /**
     * 删除设备信息(有组织)
     */
    @ApiOperation(value = "删除设备信息(有组织)")
//    @RequiresPermissions("talroad:device:remove")
    @Log(title = "设备信息(有组织)", businessType = BusinessType.DELETE)
    @PostMapping("/remove/{deviceIds}")
    public AjaxResults<Boolean> remove(@PathVariable String[] deviceIds) {
        return toAjax(basDeviceService.removeByIds(Arrays.asList(deviceIds)));
    }

    @GetMapping("/getDevicesByType")
    @ApiOperation(value = "获取指定工厂某工序下所有设备", notes = "")
    public AjaxResults<List<DeviceIdNameVO>> getDevicesByType(
            @ApiParam(name = "factoryId", value = "工厂id", required = true) @RequestParam String factoryId,
            @ApiParam(name = "deviceType", value = "设备类型(焦化:JL,烧结:SJJ,球团:SL,炼铁:GL,炼钢:ZL,白灰窑:LY,发电:FDJZ。ALL=全部)", required = false) @RequestParam(required = false) String deviceType
    ) {
        // 需要修改直接查询，不要进行BeanUtils.copyProperties

        List<BasDevice> list = null;
        if (StringUtils.isNotEmpty(deviceType)) {
            list = basDeviceService.lambdaQuery().eq(BasDevice::getFactoryId, factoryId)
                    .eq(!("ALL".equals(deviceType)), BasDevice::getType, deviceType)
                    .in(BasDevice::getIndustry, Arrays.asList("GT", "BL", "FS", "DL", "JH", "SN"))
                    .gt(BasDevice::getStatus, 0)
                    .orderByAsc(BasDevice::getDeviceId).list();
        } else {
            list = basDeviceService.lambdaQuery().eq(BasDevice::getFactoryId, factoryId)
                    .gt(BasDevice::getStatus, 0)
                    .orderByAsc(BasDevice::getDeviceId).list();
        }

        List<DeviceIdNameVO> deviceIdNameVOS = new ArrayList<>();
        list.forEach(a -> {
            DeviceIdNameVO vo = new DeviceIdNameVO();
            BeanUtils.copyProperties(a, vo);
            deviceIdNameVOS.add(vo);
        });
        return AjaxResults.success(deviceIdNameVOS);
    }

    @Data
    @ApiModel
    public static class DeviceIdNameVO {
        @ApiModelProperty(value = "设备ID")
        private String deviceId;

        @ApiModelProperty(value = "设备名称")
        private String name;
    }

    @GetMapping("/getDeviceDataByType")
    @ApiOperation(value = "设备数据查询")
    public AjaxResults<IPage> getDeviceDataByType(
            @ApiParam(name = "timeType", value = "时间类型（R:实时,H:小时,D:日,N:月,Y:年）", allowableValues = "R,H,D,N,Y") @RequestParam(required = false) String timeType,
            @ApiParam(name = "industry", value = "行业", required = true, allowableValues = "GT,JH,SN,BL,DL,FS") @RequestParam String industry,
            @ApiParam(name = "factoryId", value = "工厂id", required = true, defaultValue = "4001") @RequestParam String factoryId,
            @ApiParam(name = "deviceId", value = "设备id(英文逗号分隔)", defaultValue = "DL40010001") @RequestParam(required = false) String deviceId,
            @ApiParam(name = "deviceType", value = "设备类型。钢铁=(焦炉:JL,烧结机:SJJ,竖炉:SL,高炉:GL,转炉:ZL,炉窑:LY,发电:FDJZ，GLMQ:高炉煤气放散，ZLMQ:转炉煤气放散)，焦化=JL，水泥=SNY，玻璃:SCX，电力=(锅炉:GUL,发电机组:FDJZ)，焚烧:FS", required = true) @RequestParam String deviceType,
            @ApiParam(name = "startTime", value = "开始时间。实时=yyyy-MM-dd HH:mm:ss，小时=yyyy-MM-dd HH:00，日=yyyy-MM-dd，月=yyyy-MM，年=yyyy", defaultValue = "2021-11-03 10:00:00", required = true) @RequestParam String startTime,
            @ApiParam(name = "endTime", value = "结束时间。实时=yyyy-MM-dd HH:mm:ss，小时=yyyy-MM-dd HH:00，日=yyyy-MM-dd，月=yyyy-MM，年=yyyy", defaultValue = "2021-11-03 10:30:00", required = true) @RequestParam String endTime,
            @ApiParam(name = "orderField", value = "排序字段(dataTime)") @RequestParam(required = false) String orderField,
            @ApiParam(name = "orderType", value = "排序方向。asc=升序(默认),desc=降序") @RequestParam(required = false) String orderType,
            @ApiParam(name = "pageNo", value = "当前页号(从1开始)", defaultValue = "1") @RequestParam(required = false) Integer pageNo,
            @ApiParam(name = "pageSize", value = "每页条数", defaultValue = "20") @RequestParam(required = false) Integer pageSize
    ) {
        //检查分页是否生效
        long start = System.currentTimeMillis();
        Page page = new Page(pageNo, pageSize);
        basDeviceService.getDeviceDataByType(timeType, industry, factoryId, deviceId, deviceType, startTime, endTime, orderField, orderType, page);
        long end = System.currentTimeMillis();
        logger.info("basDevice.getDeviceDataByType##设备数据查询耗时:" + (end - start) + "毫秒");
        return AjaxResults.success(page);
    }

    @GetMapping("/getDeviceDataByType_Export")
    @ApiOperation(value = "设备数据查询-导出CSV")
    public void getDeviceDataByType_Export(
            @ApiParam(name = "timeType", value = "时间类型（R:实时,H:小时,D:日,N:月,Y:年）", allowableValues = "R,H,D,N,Y") @RequestParam(required = false) String timeType,
            @ApiParam(name = "industry", value = "行业", required = true, allowableValues = "GT,JH,SN,BL,DL,FS") @RequestParam String industry,
            @ApiParam(name = "factoryId", value = "工厂id", required = true, defaultValue = "4001") @RequestParam String factoryId,
            @ApiParam(name = "deviceId", value = "设备id(英文逗号分隔)", defaultValue = "DL40010001") @RequestParam(required = false) String deviceId,
            @ApiParam(name = "deviceType", value = "设备类型。钢铁=(焦炉:JL,烧结机:SJJ,竖炉:SL,高炉:GL,转炉:ZL,炉窑:LY,发电:FDJZ，GLMQ:高炉煤气，ZLMQ:转炉煤气)，焦化=JL，水泥=SNY，玻璃:SCX，电力=(锅炉:GUL,发电机组:FDJZ)，焚烧:FS", required = true) @RequestParam String deviceType,
            @ApiParam(name = "startTime", value = "开始时间。实时=yyyy-MM-dd HH:mm:ss，小时=yyyy-MM-dd HH:00，日=yyyy-MM-dd，月=yyyy-MM，年=yyyy", defaultValue = "2021-11-03 10:00:00", required = true) @RequestParam String startTime,
            @ApiParam(name = "endTime", value = "结束时间。实时=yyyy-MM-dd HH:mm:ss，小时=yyyy-MM-dd HH:00，日=yyyy-MM-dd，月=yyyy-MM，年=yyyy", defaultValue = "2021-11-03 10:30:00", required = true) @RequestParam String endTime,
            @ApiParam(name = "orderField", value = "排序字段(dataTime)") @RequestParam(required = false) String orderField,
            @ApiParam(name = "orderType", value = "排序方向。asc=升序(默认),desc=降序") @RequestParam(required = false) String orderType,
            @ApiParam(name = "pageNo", value = "当前页号(从1开始)", defaultValue = "1") @RequestParam(required = false) Integer pageNo,
            @ApiParam(name = "pageSize", value = "每页条数", defaultValue = "20") @RequestParam(required = false) Integer pageSize,
            HttpServletResponse response
    ) throws Exception {
        CsvUtils csvUtils = new CsvUtils();
        List<Object> lstMonData;
        String fileName;

        //===== 初始化
        if (StringUtils.isBlank(timeType))
            timeType = EnStatTimeType.REAL.id();
        fileName = String.format("DCS_%s%s_%s_%s_%s.csv", industry.toUpperCase(), factoryId, timeType, startTime, endTime);
        fileName = fileName.replaceAll(" ", "-").replaceAll(":", "");

        List<BasParam> basParams = paramService.list(new QueryWrapper<BasParam>().eq("industry", industry).eq("device_type", deviceType));
        PcFactory pcFactory = factoryService.getById(factoryId.toString());

        csvUtils.initMonDevData(timeType, pcFactory, basParams);

        response.setContentType("multipart/form-data");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
        response.getOutputStream().write(csvUtils.getBufInBytes());
        csvUtils.clearBuf();

        //==== 查询并生成
        AjaxResults<IPage> ajaxResults = getDeviceDataByType(timeType, industry, factoryId, deviceId, deviceType, startTime, endTime, orderField, orderType, pageNo, pageSize);
        if (ajaxResults.getCode() == 200)    //成功
        {
            IPage data = ajaxResults.getData();
            lstMonData = data.getRecords();

            csvUtils.exportMonDevData(lstMonData);
            response.getOutputStream().write(csvUtils.getBufInBytes());   //分段输出
            csvUtils.clearBuf();
        } else                        //失败
        {
            csvUtils.exportError("[" + ajaxResults.getCode() + "]" + ajaxResults.getMsg());
        }
        response.getOutputStream().write(csvUtils.getBufInBytes());
        csvUtils.clearBuf();
        response.flushBuffer();
    }

    @GetMapping("/getDeviceChart/{deviceId}/{startTime}/{endTime}")
    @ApiOperation(value = "获取设备工况折线图", notes = "")
    public AjaxResults<EChartsVO> getDeviceChart(@PathVariable(value = "deviceId") String deviceId,
                                                 @PathVariable(value = "startTime") String startTime,
                                                 @PathVariable(value = "endTime") String endTime) {
        return AjaxResults.success(basDeviceService.getDeviceChart(deviceId, startTime, endTime));
    }

    @GetMapping("/getDeviceChart/v2")
    @ApiOperation(value = "获取设备工况折线图")
    public AjaxResults<EChartsVO> getDeviceChart2(@RequestParam(value = "deviceId") String deviceId,
                                                  @RequestParam(value = "startTime") String startTime,
                                                  @RequestParam(value = "endTime") String endTime,
                                                  @RequestParam(value = "timeType", defaultValue = "R") String timeType) {
        return AjaxResults.success(basDeviceService.getDeviceChart(deviceId, startTime, endTime, timeType));
    }
    @GetMapping("/getDeviceChart/v3")
    @ApiOperation(value = "获取装备停限产设备工况折线图")
    public AjaxResults<ChartVo> getDeviceChart3(@RequestParam(value = "deviceId") String deviceId,
                                                  @RequestParam(value = "startTime") String startTime,
                                                  @RequestParam(value = "endTime") String endTime,
                                                  @RequestParam(value = "timeType", defaultValue = "R") String timeType) {
        return AjaxResults.success(basDeviceService.getDeviceChart3(deviceId, startTime, endTime, timeType));
    }
    @GetMapping("/getDeviceChart/v5")
    @ApiOperation(value = "获取CO设备工况折线图")
    public AjaxResults<ChartVo> getDeviceChart5(@RequestParam(value = "deviceId") String deviceId,
                                                  @RequestParam(value = "startTime") String startTime,
                                                  @RequestParam(value = "endTime") String endTime,
                                                  @RequestParam(value = "timeType", defaultValue = "R") String timeType) {
        return AjaxResults.success(basDeviceService.getDeviceChart5(deviceId, startTime, endTime, timeType));
    }
    @GetMapping("/getDeviceChart/v6")
    @ApiOperation(value = "获取CO设备工况折线图")
    public AjaxResults<ChartVo> getDeviceChart6(@RequestParam(value = "deviceId") String deviceId,
                                                  @RequestParam(value = "startTime") String startTime,
                                                  @RequestParam(value = "endTime") String endTime,
                                                  @RequestParam(value = "timeType", defaultValue = "R") String timeType) {
        return AjaxResults.success(basDeviceService.getDeviceChart6(deviceId, startTime, endTime, timeType));
    }

    @GetMapping("/getDevicesByInsduty")
    @ApiOperation(value = "获取指定企业、指定行业下所有设备", notes = "")
    public AjaxResults<List<BasDeviceIndustryVo>> getDevicesByInsduty(
            @ApiParam(name = "factoryId", value = "工厂id", required = true) @RequestParam String factoryId,
            @ApiParam(name = "industry", value = "行业类型(焦化:JH,钢铁:GT,玻璃:BL,垃圾焚烧:FS,水泥:SN,电力:DL,分表计电:EL,排污许可生产、治理设备:XK。ALL=全部)", required = true) @RequestParam String industry
    ) {
        // 需要修改直接查询，不要进行BeanUtils.copyProperties
        List<BasDevice> list = basDeviceService.lambdaQuery().eq(BasDevice::getFactoryId, factoryId)
                .eq(!("ALL".equals(industry)), BasDevice::getIndustry, industry)
                .gt(BasDevice::getStatus, 0)
                .orderByAsc(BasDevice::getDeviceId).list();
        List<BasDeviceIndustryVo> basDeviceIndustryVOs = new ArrayList<>();
        list.forEach(a -> {
            BasDeviceIndustryVo vo = new BasDeviceIndustryVo();
            BeanUtils.copyProperties(a, vo);
            basDeviceIndustryVOs.add(vo);
        });
        return AjaxResults.success(basDeviceIndustryVOs);
    }

    /**
     * 操作日志
     */
    @ApiOperation(value = "操作日志")
    @GetMapping("/editLogList")
    public AjaxResults<IPage<BasProductionDeviceOperationLog>> editLogList(BasProductionDeviceOperationLogQuery basProductionDeviceOperationLogQuery) {
        Long roleId = SecurityUtils.getLoginUser().getSysUser().getRoles().get(0).getRoleId();
        if(ObjectUtil.equal(roleId,10L)) {
            String factoryId = SecurityUtils.getLoginUser().getSysUser().getFactoryId();
            basProductionDeviceOperationLogQuery.setFactoryId(factoryId);
        }
        Page<BasProductionDeviceOperationLog> page = new Page<>(basProductionDeviceOperationLogQuery.getPageNum(), basProductionDeviceOperationLogQuery.getPageSize());
        IPage<BasProductionDeviceOperationLog> list = basProductionDeviceOperationLogService.page(page, basProductionDeviceOperationLogQuery.createLambdaQueryWrapper(basProductionDeviceOperationLogQuery));
        return AjaxResults.success(list);
    }

    @ApiOperation(value = "生产工况监测大屏-工况监控数量总览")
    @GetMapping("/countOverview")
    public AjaxResults<BasDeviceVo.CountOverview> countOverview() {
        BasDeviceVo.CountOverview countOverview = basDeviceService.getCountOverview();
        return AjaxResults.success(countOverview);
    }

    @ApiOperation(value = "煤气放散分析大屏-煤气放散数量")
    @GetMapping("/coal/countOverview")
    public AjaxResults<BasDeviceVo.CoalCountOverview> coalCountOverview() {
        BasDeviceVo.CoalCountOverview countOverview = basDeviceService.getCoalCountOverview();
        return AjaxResults.success(countOverview);
    }

    @ApiOperation(value = "煤气放散分析大屏-煤气放散清单")
    @GetMapping("/coal/diffuse/list")
    public AjaxResults<List<BasDeviceVo.CoalDiffuse>> coalDiffuseList(
            @ApiParam(value = "设备名称", name = "deviceName") @RequestParam(value = "deviceName", required = false) String deviceName,
            @ApiParam(value = "当前状态 1正常放散，2异常放散，3未放散，4离线", name = "status") @RequestParam(value = "status", required = false) String status
    ) {
        List<BasDeviceVo.CoalDiffuse> list = basDeviceService.getCoalDiffuseList(deviceName, status);
        return AjaxResults.success(list);
    }

}

