package com.yeejoin.equipmanage.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.equipmanage.common.dto.EquipmentSpecificDto;
import com.yeejoin.equipmanage.common.entity.EquipQrcodeRecord;
import com.yeejoin.equipmanage.common.entity.Equipment;
import com.yeejoin.equipmanage.common.entity.EquipmentDetail;
import com.yeejoin.equipmanage.common.entity.EquipmentSpecific;
import com.yeejoin.equipmanage.common.entity.dto.EquipmentSpecificDTO;
import com.yeejoin.equipmanage.common.entity.dto.SourceNameListDTO;
import com.yeejoin.equipmanage.common.entity.vo.ComplementCodeVO;
import com.yeejoin.equipmanage.common.entity.vo.EquiplistSpecificBySystemVO;
import com.yeejoin.equipmanage.common.entity.vo.IotIndexInfoVo;
import com.yeejoin.equipmanage.common.entity.vo.SourceNameByEquipSpeIdVO;
import com.yeejoin.equipmanage.common.enums.EquipQrcodeColorEnum;
import com.yeejoin.equipmanage.common.utils.CommonResponseUtil;
import com.yeejoin.equipmanage.common.utils.StringUtil;
import com.yeejoin.equipmanage.common.vo.EquipmentOnCarVo;
import com.yeejoin.equipmanage.common.vo.VideoOnEquipmentSpecificVo;
import com.yeejoin.equipmanage.fegin.IotFeign;
import com.yeejoin.equipmanage.mapper.EquipQrcodeRecordMapper;
import com.yeejoin.equipmanage.mapper.EquipmentSpecificMapper;
import com.yeejoin.equipmanage.service.IEquipmentDetailService;
import com.yeejoin.equipmanage.service.IEquipmentService;
import com.yeejoin.equipmanage.service.IEquipmentSpecificSerivce;
import com.yeejoin.equipmanage.service.impl.FireFightingSystemServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author ZeHua Li
 * @date 2020/10/29 14:26
 * @since v2.0
 */
@Slf4j
@RestController
@Api(tags = "单个设备管理")
@RequestMapping(value = "/equipSpecific")
public class EquipmentSpecificController extends AbstractBaseController {

    public static final int RESULT_SUCCESS_CODE = 200;

    @Autowired
    IEquipmentSpecificSerivce equipmentSpecificSerivce;

    @Autowired
    EquipmentSpecificMapper equipmentSpecificMapper;

    @Autowired
    EquipQrcodeRecordMapper equipQrcodeRecordMapper;

    @Autowired
    IEquipmentDetailService equipmentDetailService;

    @Autowired
    IEquipmentService equipmentService;

    @Value("${systemctl.sync.switch}")
    private Boolean syncSwitch;

    @Autowired
    FireFightingSystemServiceImpl fireFightingSystemServiceImpl;

    @Autowired
    IotFeign iotFeign;

    /**
     * 补码页面分页
     *
     * @return
     */
    @RequestMapping(value = "/page", method = RequestMethod.POST)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "列表分页查询", notes = "补码列表接口,废弃未用到")
    public IPage<ComplementCodeVO> saveEquipmentPoint(@RequestBody EquipmentSpecificDTO equipmentSpecific) {
        return equipmentSpecificSerivce.selectEquipmentSpecific(equipmentSpecific);
    }

    /**
     * 通过id获取设备区域建筑等信息
     *
     * @return
     */
    @GetMapping(value = "/getSourceNameByEquipSpeId")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "通过id获取设备区域建筑等信息", notes = "通过id获取设备区域建筑等信息")
    public SourceNameByEquipSpeIdVO getSourceNameByEquipSpeId(Long id) {
        return equipmentSpecificSerivce.getSourceNameByEquipSpeId(id);
    }


    /**
     * 通过id获取设备区域建筑等信息
     *
     * @return
     */
    @PostMapping(value = "/getSourceNameList")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "获取设备区域建筑列表等信息", notes = "获取设备区域建筑列表等信息")
    public IPage<SourceNameByEquipSpeIdVO> getSourceNameList(@RequestBody SourceNameListDTO sourceNameListDTO) {
        return equipmentSpecificSerivce.getSourceNameList(sourceNameListDTO.getPage(), sourceNameListDTO.getWarehouseStructureId(), sourceNameListDTO.getSourceId(), sourceNameListDTO.getEquipmentName(), sourceNameListDTO.getEquipmentCode());
    }

    /**
     * 修改
     *
     * @return
     */
    @RequestMapping(value = "/exit", method = RequestMethod.POST)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "修改"	, notes = "修改")
    public EquipmentSpecific updateEquipmentSpecific(@RequestBody EquipmentSpecific equipmentSpecific) {
        EquipmentSpecific updateEquipmentSpecific = equipmentSpecificSerivce.updateEquipmentSpecific(equipmentSpecific, getSelectedOrgInfo(), getUserInfo());
        if (syncSwitch) {
            // TODO 后续判断成功，执行同步
            Long equipmentDetailId = updateEquipmentSpecific.getEquipmentDetailId();
            EquipmentDetail equipmentDetail = equipmentDetailService.getById(equipmentDetailId);
            equipmentSpecificSerivce.equipSpecificDataSync(equipmentDetail.getEquipmentId());
        }
        return updateEquipmentSpecific;
    }

    /**
     * 设备报警信息
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/getAll", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "根据id查询", notes = "根据id查询")
    public Map<String, Object> selectById(Long id) {
        return equipmentSpecificSerivce.getAll(id);
    }

    /**
     * 获取巡检维保信息
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/getMaintenanceInfo", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "根据id查询", notes = "根据id查询")
    public Map<String, Object> getMaintenanceInfo(String checkDate) {
        return equipmentSpecificSerivce.getMaintenanceInfo(checkDate);
    }

    /**
     * 组态使用装备卡片数据
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/getOneCard", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "根据id查询", notes = "组装组态使用装备卡片数据")
    public Object getOneCard(Long id, String type) {
        return equipmentSpecificSerivce.getOneCard(id, type);
    }

    /**
     * 获取巡检维保信息
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/hasIotCode/{id}", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "查询物联编码是否有重复", notes = "查询物联编码是否有重复")
    public ResponseModel hasIotCode(@PathVariable("id") String id, String iotCode) {
        Map map1 = new HashMap();
        map1.put("state", "FAILED");
        map1.put("message", "若您设置物联编码，请至少输入9位字符！");
        Map map2 = new HashMap();
        map2.put("state", "DUPLICATE");
        map2.put("message", "物联编码重复，请重新设置！");
        Map map3 = new HashMap();
        map3.put("state", "SUCCESS");
        map3.put("message", "成功！");
        if (iotCode.trim().length() < 9) {
            return CommonResponseUtil.success(map1);
        }
        List<String> list = equipmentSpecificMapper.getIotCodeList(id);
        List<String> iotCodeList = new ArrayList<String>();
        if (list != null && !list.isEmpty()) {
            iotCodeList = list.stream().filter(x -> x.equals(iotCode)).collect(Collectors.toList());
        }
        if (iotCodeList.size() == 0) {
            return CommonResponseUtil.success(map3);
        } else {
            return CommonResponseUtil.success(map2);
        }
    }

    /**
     * 获取设备详情
     *
     * @param equipmentSpecific
     * @return
     */
    @RequestMapping(value = "/getEquipSpecificDetail", method = RequestMethod.POST)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "获取设备详情", notes = "获取设备详情")
    public ResponseModel getEquipSpecificDetail(@RequestBody EquipmentSpecific equipmentSpecific) {
        return CommonResponseUtil.success(equipmentSpecificSerivce.getEquipSpecificDetail(equipmentSpecific));
    }

    /**
     * 获取instanceId和orgCode
     *
     * @param sourceId
     * @return
     */
    @RequestMapping(value = "/getInstanceIdAndOrgCode", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "获取instanceId和orgCode", notes = "获取instanceId和orgCode")
    public ResponseModel getInstanceIdAndOrgCode(@RequestParam Long sourceId) {
        if (Objects.isNull(sourceId)) {
            return CommonResponseUtil.success(null);
        }
        return CommonResponseUtil.success(equipmentSpecificSerivce.getInstanceIdAndOrgCode(sourceId));
    }

    /**
     * @param like    设备名称或编码code
     * @param notLike wl_equipment_category，code不包含（右%），多个用英文逗号隔开
     * @param status  wl_stock_detail.status
     * @return
     */
    @RequestMapping(value = "/getAirEquipSpecificList", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "获取特定条件设备集合", notes = "获取特定条件设备集合")
    public ResponseModel getAirEquipSpecificList(@RequestParam(required = false) String like,
                                                 @RequestParam(required = false) String notLike,
                                                 @RequestParam(required = false) Integer status) {
        return CommonResponseUtil.success(equipmentSpecificSerivce.getAirEquipSpecificList(like, notLike, status));
    }

    /**
     * 页面分页
     *
     * @return
     */
    @RequestMapping(value = "/getAirEquipSpecificPage", method = RequestMethod.POST)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "列表分页查询", notes = "列表分页查询")
    public IPage<EquipmentOnCarVo> onCarVoIPage(@RequestBody EquipmentSpecificDto equipmentSpecificDto) {
        return equipmentSpecificSerivce.onCarVoIPage(equipmentSpecificDto);
    }

    @RequestMapping(value = "/getAirEquipSpecificDetail", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "获取设备详情", notes = "获取特定条件设备集合")
    public ResponseModel getAirEquipSpecificDetail(@RequestParam Long stockDetailId) {
        return CommonResponseUtil.success(equipmentSpecificSerivce.getAirEquipSpecificDetail(stockDetailId));
    }

    /**
     * 根据specificId删除装备相关数据
     *
     * @param specificId id
     * @return ResponseModel
     */
    @DeleteMapping(value = "/delEquipmentBySpecificId")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation(value = "删除装备相关所有数据", notes = "删除装备相关所有数据")
    public ResponseModel delEquipmentBySpecificId(@RequestParam Long specificId) {
        EquipmentSpecific equipmentSpecific = equipmentSpecificSerivce.getById(specificId);
        // 删除detail数据
        QueryWrapper<EquipmentDetail> detailQueryWrapper = new QueryWrapper<>();
        detailQueryWrapper.eq("id", equipmentSpecific.getEquipmentDetailId());
        EquipmentDetail detail = equipmentDetailService.getOne(detailQueryWrapper);
        equipmentDetailService.removeOneById(detail.getId());
        Boolean result = equipmentSpecificSerivce.delEquipmentBySpecificId(specificId);
        // 同步刷新，不在异步，原因速度3秒左右
        this.refreshCount(equipmentSpecific.getBizOrgCode());
        return CommonResponseUtil.success(result);
    }


    private void refreshCount(String bizOrgCode) {
        try {
            equipmentSpecificSerivce.refreshStaData();
            fireFightingSystemServiceImpl.refreshEquipmentTypeAndCount(bizOrgCode);
        } catch (Exception e) {
            log.error("刷新装备分类树缓存失败" + e.getMessage());
        }
    }

    /**
     * 根据specificIds删除装备相关数据
     *
     * @param specificIds id
     * @return ResponseModel
     */
    @DeleteMapping(value = "/delAllEquipmentBySpecificIds")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "批量删除装备相关所有数据", notes = "批量删除装备相关所有数据")
    public ResponseModel delEquipmentBySpecificId(@RequestBody List<Long> specificIds) {
        if (ObjectUtils.isEmpty(specificIds)) {
            return CommonResponseUtil.failure("参数为空");
        }
        specificIds.forEach(specificId -> {
            equipmentSpecificSerivce.delEquipmentBySpecificId(specificId);
            EquipmentSpecific equipmentSpecific = equipmentSpecificSerivce.getById(specificId);
            // 同步刷新，不在异步，原因速度3秒左右
            this.refreshCount(equipmentSpecific.getBizOrgCode());
        });
        return CommonResponseUtil.success();
    }

    @RequestMapping(value = "/getFessIndexDetails", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "获取中州环境监测指标详情", notes = "获取中州环境监测指标详情")
    public ResponseModel getFessIndexDetails() {
        return CommonResponseUtil.success(equipmentSpecificSerivce.getFessIndexDetails());
    }

    @RequestMapping(value = "/videoOnEquipmentSpecific", method = RequestMethod.POST)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "摄像头绑定设备", notes = "摄像头绑定设备")
    public ResponseModel videoOnEquipmentSpecific(@RequestBody VideoOnEquipmentSpecificVo videoOnEquipmentSpecificVo) {
        return CommonResponseUtil.success(equipmentSpecificSerivce.videoOnEquipmentSpecific(videoOnEquipmentSpecificVo));
    }
    @RequestMapping(value = "/delVideoOnEquipmentSpecific/{equipmentSpecificId}/{videoId}", method = RequestMethod.POST)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "摄像头解绑设备", notes = "摄像头绑定设备")
    public ResponseModel delVideoOnEquipmentSpecific( @PathVariable Long equipmentSpecificId, @PathVariable Long videoId) {

        return CommonResponseUtil.success(equipmentSpecificSerivce.delVideoOnEquipmentSpecific(equipmentSpecificId,videoId));
    }


    @RequestMapping(value = "/delVideoOnEquipment/jb", method = RequestMethod.POST)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "摄像头解绑设备", notes = "摄像头绑定设备")
    public ResponseModel delVideoOnEquipmentjb(  @RequestBody  Map<String,List<String>>  ids) {
        List<String> equipmentSpecificIds = ids.get("ids");
        return CommonResponseUtil.success(equipmentSpecificSerivce.delVideoOnEquipmentjb( equipmentSpecificIds));
    }
    @RequestMapping(value = "/videoOnEquipmentSpecific/bj", method = RequestMethod.POST)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "摄像头绑定设备", notes = "摄像头绑定设备")
    public ResponseModel videoOnEquipmentSpecificbj(@RequestBody  Map<String,List<String>>  date ) {

        return CommonResponseUtil.success(equipmentSpecificSerivce.videoOnEquipmentSpecificbj(date));
    }





    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/{buildingId}/list")
    @ApiOperation(httpMethod = "GET", value = "查询指定建筑下的装备列表", notes = "查询指定建筑下的装备列表")
    public List<EquiplistSpecificBySystemVO> getListByWarehouseStructureId( @PathVariable Long buildingId){
        return equipmentSpecificMapper.getListByWarehouseStructureId(buildingId, null);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getListByEquipmentCode/{code}")
    @ApiOperation(httpMethod = "GET", value = "根据装备分类code获取装备list", notes = "根据装备分类code获取装备list")
    public List<Map<String, Object>> getListByEquipmentCode( @PathVariable String code){
        ReginParams ReginParams=getSelectedOrgInfo();
        String   bizCode= ReginParams.getPersonIdentity().getCompanyBizOrgCode();

        return equipmentSpecificSerivce.getListByEquipmentCodeJ(code,bizCode);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getListByEquipmentCodeEQ/{code}")
    @ApiOperation(httpMethod = "GET", value = "根据装备分类code获取装备list", notes = "根据装备分类code获取装备list")
    public List<Map<String, Object>> getFirePumpInfoEQ( @PathVariable String code){
        ReginParams ReginParams=getSelectedOrgInfo();
        String   bizCode= ReginParams.getPersonIdentity().getBizOrgCode();
        return equipmentSpecificSerivce.getFirePumpInfoEQ(code,bizCode);
    }


    @GetMapping(value = "/index/normal")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "查询非告警指标list", notes = "查询非告警指标list")
    public ResponseModel normalIndexInfoList(@RequestParam(required = false) String startDate,
                                             @RequestParam(required = false) String endDate){
        return CommonResponseUtil.success(equipmentSpecificSerivce.normalIndexInfoList(startDate, endDate));
    }

    @GetMapping(value = "/index/normalByPage")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "分页查询非告警指标list", notes = "分页查询非告警指标list")
    public ResponseModel normalIndexInfoListByPage(@RequestParam(required = false) String startDate,
                                             @RequestParam(required = false) String endDate,
                                             @RequestParam(required = false) String systemCode,
                                             @RequestParam(required = false) String name,
                                             @RequestParam Integer pageNumber,
                                             @RequestParam Integer pageSize){
        Page<Map<String, Object>> page = new Page<>(pageNumber, pageSize);
        return CommonResponseUtil.success(equipmentSpecificSerivce.normalIndexInfoListByPage(page, startDate, endDate,systemCode,name));
    }

    @GetMapping(value = "/info/fire")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "查询火报系统指标", notes = "查询火报系统指标")
    public ResponseModel getFireAutoSysInfo(@RequestParam(required = false) String startDate,
                                             @RequestParam(required = false) String endDate){
        return CommonResponseUtil.success(equipmentSpecificSerivce.getFireAutoSysInfo(startDate, endDate));
    }

    @GetMapping(value = "/status/equip")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "修改装备二维码状态", notes = "修改装备二维码状态")
    public ResponseModel updateEquipSpecificStatus( String status, String id,String sourceId,String source){

        EquipmentSpecific spec = equipmentSpecificSerivce.getBaseMapper().selectById(id);
        int oldStatus = Integer.valueOf(spec.getEquipStatus());
        int newStatus = Integer.valueOf(status);

        LambdaQueryWrapper<EquipQrcodeRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EquipQrcodeRecord::getEquipid, id);
        wrapper.eq(EquipQrcodeRecord::getSourceId, sourceId);
        EquipQrcodeRecord equipQrcodeRecord = equipQrcodeRecordMapper.selectOne(wrapper);

        if (ObjectUtils.isEmpty(equipQrcodeRecord)){
            //保存 wl_equip_qrcode_record 二维码记录
            EquipQrcodeRecord newEquipQrcodeRecord = new EquipQrcodeRecord();
            newEquipQrcodeRecord.setEquipid(Long.valueOf(id));
            newEquipQrcodeRecord.setSource(source);
            newEquipQrcodeRecord.setAlarmTime(new Date());
            newEquipQrcodeRecord.setStatus(status);
            newEquipQrcodeRecord.setSourceId(sourceId);
            newEquipQrcodeRecord.setBizOrgCode(spec.getBizOrgCode());
            newEquipQrcodeRecord.setBizOrgName(spec.getBizOrgName());
            newEquipQrcodeRecord.setSystemCode(spec.getSystemId());
            equipQrcodeRecordMapper.insert(newEquipQrcodeRecord);
        } else {
            equipQrcodeRecord.setStatus(status);
            equipQrcodeRecordMapper.updateById(equipQrcodeRecord);
        }

        if (oldStatus < newStatus){ //当前状态小于事件状态时 取更高级别状态赋码
            equipmentSpecificSerivce.updateEquipSpecificStatus(status, id);
        }
        return CommonResponseUtil.success();
    }

    @GetMapping(value = "/status/checkInput")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "idx修改对应装备二维码状态", notes = "idx修改对应装备二维码状态")
    public ResponseModel updateEquipSpecificStatusByCheckInput( @RequestParam(value = "id") String id,@RequestParam(value = "equipId",required = false) String equipId ){
        //查询 巡检项所绑定装备
       if (StringUtils.isEmpty(equipId)){
         equipId = equipmentSpecificSerivce.updateEquipSpecificStatusByCheckInput(id);
       }
        LambdaQueryWrapper<EquipQrcodeRecord> query = new LambdaQueryWrapper<>();
        query.eq(EquipQrcodeRecord::getEquipid,equipId);
        query.notIn(EquipQrcodeRecord::getSourceId,id);
        query.isNull(EquipQrcodeRecord::getCleanTime);
        List<EquipQrcodeRecord> equipQrcodeRecords = equipQrcodeRecordMapper.selectList(query);

        //修改本次清除的装备事件
        LambdaQueryWrapper<EquipQrcodeRecord> one = new LambdaQueryWrapper<>();
        one.eq(EquipQrcodeRecord::getEquipid,equipId);
        one.eq(EquipQrcodeRecord::getSourceId,id);
        one.isNull(EquipQrcodeRecord::getCleanTime);
        EquipQrcodeRecord equipQrcodeRecord = equipQrcodeRecordMapper.selectOne(one);
        equipQrcodeRecord.setCleanTime(new Date());
        if (equipQrcodeRecord.getSource().equals("patrol")){
            equipQrcodeRecord.setCleanReason("设备再次巡查正常");
        }
        equipQrcodeRecordMapper.updateById(equipQrcodeRecord);

        if (equipQrcodeRecords.size() == 0) {  //如果记录表中此装备无未消除的故障等 则恢复绿码
            //修改装备二维码状态为合格  此处为0代表绿色 是idx只有在合格是才会触发此接口
            equipmentSpecificSerivce.updateEquipSpecificStatus("0", equipId);
        } else {
            //然后取结果集中剩余状态最高的颜色赋码
            String status = equipQrcodeRecords.stream().sorted(Comparator.comparing(EquipQrcodeRecord::getStatus)).findFirst().get().getStatus();
            equipmentSpecificSerivce.updateEquipSpecificStatus(status, equipId);
        }

        return CommonResponseUtil.success();
    }

    @GetMapping("/change/status")
    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @ApiOperation(httpMethod = "GET", value = "查询泡沫系统指标", notes = "查询泡沫系统指标")
    public ResponseModel changeEquipStatusById(@RequestParam(value = "status") String status,
                                               @RequestParam(value = "equipId") String equipId) {
        equipmentSpecificSerivce.updateEquipSpecificStatus(status, equipId);
        return CommonResponseUtil.success();
    }

    @GetMapping("/find/id")
    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @ApiOperation(httpMethod = "GET", value = "查询泡沫系统指标", notes = "查询装备id")
    public ResponseModel getEquipIdByCheckInputId(@RequestParam(value = "id") String id) {
        return CommonResponseUtil.success(equipmentSpecificMapper.getEquipIdByCheckInputId(id));
    }

    @GetMapping("/find/one")
    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @ApiOperation(httpMethod = "GET", value = "查询泡沫系统指标", notes = "查询泡沫系统指标")
    public ResponseModel getOneEntityById(@RequestParam(value = "id") String id) {
        QueryWrapper<EquipmentSpecific> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        EquipmentSpecific equipmentSpecific = equipmentSpecificSerivce.getOne(queryWrapper);
        return CommonResponseUtil.success(equipmentSpecific);
    }

    @GetMapping(value = "/info/paomo")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "查询泡沫系统指标", notes = "查询泡沫系统指标")
    public ResponseModel getPaomoSysInfo(@RequestParam(required = false) String startDate,
                                             @RequestParam(required = false) String endDate){
        return CommonResponseUtil.success(equipmentSpecificSerivce.getPaomoSysInfo(startDate, endDate));
    }

    @GetMapping(value = "/info/water")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "查询给水系统指标", notes = "查询给水系统指标")
    public ResponseModel getWaterSysInfo(@RequestParam(required = false) String startDate,
                                             @RequestParam(required = false) String endDate){
        return CommonResponseUtil.success(equipmentSpecificSerivce.getWaterSysInfo(startDate, endDate));
    }

    @RequestMapping(value = "/equipment/iotIndexInfo/{equipSpeId}", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "根据装备id获取物联日志", notes = "根据装备id获取物联日志")
    public ResponseModel getEquipmentIotIndexInfo(@PathVariable String equipSpeId, @RequestParam String beginDate,  @RequestParam String endDate,
                                                  @RequestParam(required = false) Integer isTrend, @RequestParam(required = false) String fieldKey) {

        List<IotIndexInfoVo> indexInfoList = new ArrayList<>();
        List<String> split= Arrays.asList(equipSpeId.split(","));
        for (String s : split) {
            // 1.根据 equipSpeId 查询装备iotCode
            EquipmentSpecific equipmentSpecific = equipmentSpecificMapper.selectById(s);
            if (ObjectUtils.isEmpty(equipmentSpecific)) {
                return CommonResponseUtil.failure("未查询到装备信息!");
            }
            String iotCode = equipmentSpecific.getIotCode();
            String prefix = null;
            String suffix = null;
            if (StringUtil.isNotEmpty(iotCode) && iotCode.length() > 8) {
                prefix = iotCode.substring(0, 8);
                suffix = iotCode.substring(8);
            } else {
                return CommonResponseUtil.failure("装备物联编码错误，请确认！");
            }
            ResponseModel entity = null;
            try {
                entity = iotFeign.selectList(getAppKey(), getProduct(), getToken(), beginDate, endDate, prefix, suffix, null);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("调用iot服务出错");
                return CommonResponseUtil.failure("请求失败");
            }

            if (RESULT_SUCCESS_CODE != entity.getStatus() && ObjectUtils.isEmpty(entity.getResult())) {
                log.error("查询物联日志数据为空或iotCode为 (" + iotCode + ") 的装备不存在于物联系统中！");
                return CommonResponseUtil.failure("物联日志数据为空");
            }
            indexInfoList.addAll(equipmentSpecificSerivce.getIndexInfoList(iotCode, entity, isTrend, fieldKey));
        }
        return CommonResponseUtil.success(indexInfoList);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/list")
    @ApiOperation(httpMethod = "GET", value = "根据装备分类code获取装备list", notes = "根据装备分类code获取装备list")
    public List<Map<String, Object>> getListByEquipmentIds(@RequestParam(value = "ids") String ids, @RequestParam(value = "type") String type){
        ReginParams ReginParams = getSelectedOrgInfo();
        String bizCode= ReginParams.getPersonIdentity().getBizOrgCode();
        List<Map<String, Object>> list = new ArrayList<>();
        // 1 表示speId 0 表示equipmentId
        if ("1".equals(type)) {
            String[] strings = ids.split(",");
            list = equipmentSpecificMapper.getListByIds(strings, bizCode);
        } else {
            Equipment equipment = equipmentService.getById(ids);
            list = equipmentSpecificMapper.getListByCode(equipment.getCode(), bizCode);
        }
        return list;
    }

}
