package com.yfd.platform.modules.basedata.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.BetweenFormatter;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yfd.platform.config.DynamicTask;
import com.yfd.platform.config.redis.RiisConstants;
import com.yfd.platform.constant.Constant;
import com.yfd.platform.modules.basedata.domain.DeviceChannel;
import com.yfd.platform.modules.basedata.domain.Substation;
import com.yfd.platform.modules.basedata.domain.SubstationPatroldevice;
import com.yfd.platform.modules.basedata.mapper.DeviceChannelMapper;
import com.yfd.platform.modules.basedata.mapper.SubstationMapper;
import com.yfd.platform.modules.basedata.mapper.SubstationPatroldeviceMapper;
import com.yfd.platform.modules.basedata.service.ISubstationPatroldeviceService;
import com.yfd.platform.system.domain.RolePatroldevice;
import com.yfd.platform.system.domain.SysDictionaryItems;
import com.yfd.platform.system.mapper.RolePatroldeviceMapper;
import com.yfd.platform.system.mapper.SysUserMapper;
import com.yfd.platform.system.service.ISysDictionaryItemsService;
import com.yfd.platform.utils.FileUtil;
import com.yfd.platform.utils.HttpRESTfulUtils;
import com.yfd.platform.utils.SecurityUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 变电站_巡视设备 服务实现类
 * </p>
 *
 * @since 2023-03-28
 */
@Service
@Transactional
public class SubstationPatroldeviceServiceImpl extends ServiceImpl<SubstationPatroldeviceMapper,
        SubstationPatroldevice> implements ISubstationPatroldeviceService {

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private RolePatroldeviceMapper rolePatroldeviceMapper;

    @Resource
    private SubstationMapper substationMapper;

    @Resource
    private DynamicTask dynamicTask;

    @Resource
    private DeviceChannelMapper deviceChannelMapper;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Resource
    private SubstationPatroldeviceMapper substationPatroldeviceMapper;


    @Resource
    private HttpRESTfulUtils httpUtil;
    @Resource
    private ISysDictionaryItemsService sysDictionaryItemsService;

    /**********************************
     * 用途说明: 删除巡视设备
     * 参数说明 id 巡视设备id
     * 返回值说明: boolean
     ***********************************/
    @Override
    public boolean deleteSubstationDeviceById(String id) {
        String[] split = id.split(",");
        for (String s : split) {
            SubstationPatroldevice substationPatroldevice = this.getById(s);
            if ("1".equals(substationPatroldevice.getDatastatus())) {
                continue;
            }
            String patroldeviceCode = substationPatroldevice.getPatroldeviceCode();
            this.remove(new LambdaQueryWrapper<SubstationPatroldevice>().eq(SubstationPatroldevice::getRobotsCode, patroldeviceCode));
            rolePatroldeviceMapper.delete(new LambdaQueryWrapper<RolePatroldevice>().eq(RolePatroldevice::getDeviceid, s));
            this.removeById(s);
        }
        return true;
    }

    /**********************************
     * 用途说明:
     * 参数说明 id 巡视设备id
     * 参数说明 dataStatus 设备状态
     * 返回值说明: boolean
     ***********************************/
    @Override
    public boolean setSubstationDeviceStatus(String id, String dataStatus) {
        LambdaUpdateWrapper<SubstationPatroldevice> updateWrapper = new LambdaUpdateWrapper<>();
        //根据id 修改是否启用静默任务 ，最近修改人，最近修改时间
        updateWrapper.eq(SubstationPatroldevice::getPatroldeviceId, id).set(SubstationPatroldevice::getDatastatus,
                dataStatus).set(SubstationPatroldevice::getLastmodifier, SecurityUtils.getCurrentUsername()).set(SubstationPatroldevice::getLastmodifydate, new Timestamp(System.currentTimeMillis()));
        return this.update(updateWrapper);
    }

    /**********************************
     * 用途说明: 根据用户id查询所有摄像头id
     * 参数说明 id 用户id
     * 返回值说明: java.util.List<java.lang.String>
     ***********************************/
    @Override
    public List<String> getCameraIds(String id) {
        List<String> roleIds = sysUserMapper.getRoleid(id);
        List<String> cameraIds = new ArrayList<>();
        for (String roleId : roleIds) {
            LambdaQueryWrapper<RolePatroldevice> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(RolePatroldevice::getRoleid, roleId).select(RolePatroldevice::getDeviceid);
            List<RolePatroldevice> list = rolePatroldeviceMapper.selectList(queryWrapper);
            List<String> collect = list.stream().map(RolePatroldevice::getDeviceid).collect(Collectors.toList());
            cameraIds.addAll(collect);
        }
        return cameraIds;
    }

    /**********************************
     * 用途说明: 新增或修改机器人
     * 参数说明 substationPatroldevices
     * 返回值说明: void
     ***********************************/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addOrUpdatePatrolRobot(List<SubstationPatroldevice> substationPatroldevices) {
        String currentUsername = SecurityUtils.getCurrentUsername();
        LocalDateTime now = LocalDateTime.now();
        // 如果id为空则为新增，否则为修改
        for (SubstationPatroldevice substationPatroldevice : substationPatroldevices) {
            if (BeanUtil.isEmpty(substationPatroldevice)) {
                continue;
            }
            // 根据变电站id获取名称和编码
            String stationId = substationPatroldevice.getStationId();
            if (StrUtil.isNotBlank(stationId)) {
                Substation substation = substationMapper.selectById(stationId);
                substationPatroldevice.setStationName(substation.getStationName());
                substationPatroldevice.setStationCode(substation.getStationCode());
            }
            substationPatroldevice.setLastmodifier(currentUsername);
            substationPatroldevice.setLastmodifydate(now);
            substationPatroldevice.setDatastatus("1");
            String patroldeviceId = substationPatroldevice.getPatroldeviceId();
            if (StrUtil.isBlank(patroldeviceId)) {
                this.save(substationPatroldevice);
            } else {
                this.updateById(substationPatroldevice);
            }
        }
    }

    /**********************************
     * 用途说明: 对摄像头添加静默监视任务
     * 参数说明
     * 返回值说明: 无
     ***********************************/
    @Override
    public void addDailyMonitorTask() {
        List<SubstationPatroldevice> devices = this.list(
                new LambdaQueryWrapper<SubstationPatroldevice>()
                        .in(SubstationPatroldevice::getType, "1", "2", "3", "10")
                        .eq(SubstationPatroldevice::getDatastatus, "1")
                        .eq(SubstationPatroldevice::getDailymonitor, "1")
                        .orderByAsc(SubstationPatroldevice::getStationCode, SubstationPatroldevice::getPatroldeviceCode)
        );
        for (SubstationPatroldevice device : devices) {
            startPatroldeviceJob(device);
        }
    }

    //启动单个摄像机静默监视任务
    private void startPatroldeviceJob(SubstationPatroldevice device) {

        String key = "DailyMonitorJob_" + device.getStationCode() + "_" + device.getPatroldeviceCode();
        String slienceParams = device.getSlienceParams();
        String channelinfo = device.getChannelinfo();
        String patroldevice_code = "";
        String patrolchannel_code = "";
        String rtspurl = "";
        if (ObjUtil.isNotEmpty(channelinfo) && JSONUtil.isTypeJSONArray(channelinfo)) {
            JSONArray channels = JSONUtil.parseArray(channelinfo);
            for (int i = 0; i < channels.size(); i++) {
                JSONObject channel = channels.getJSONObject(i);
                if (channel.getStr("channel_type").equals("1")) {//1=可见光
                    if (channel.getStr("from_device").equals("1")) {//1=摄像机
                        patroldevice_code = device.getInternationalId();
                        patrolchannel_code = channel.getStr("channel_code");
                    } else {//1=来源录像机
                        patroldevice_code = channel.getStr("recorder_code");
                        patrolchannel_code = channel.getStr("recorder_channelcode");
                    }
                    rtspurl = channel.getStr("channel_rtspurl");
                    break;
                }
            }
        }

        if (StrUtil.isNotEmpty(slienceParams)) {
            JSONArray jsonArray = JSONUtil.parseArray(slienceParams);
            for (Object o : jsonArray) {
                JSONObject deviceobj = new JSONObject();
                JSONObject jsonObject = JSONUtil.parseObj(o);
                deviceobj.putOnce("station_code", device.getStationCode());
                deviceobj.putOnce("patroldevice_id", device.getPatroldeviceId());
                deviceobj.putOnce("patroldevice_name", device.getPatroldeviceName());
                deviceobj.putOnce("patroldevice_code", patroldevice_code);
                deviceobj.putOnce("patrolchannel_code", patrolchannel_code);
                deviceobj.putOnce("area_name", device.getAreaName());
                deviceobj.putOnce("place", device.getPlace());
                deviceobj.putOnce("rtspurl", rtspurl);
                if (jsonObject.getStr("type").equals("wcgz") || jsonObject.getStr("type").equals("wcaqm")) {
                    deviceobj.putOnce("sliencetype", "ryxw");
                } else {
                    deviceobj.putOnce("sliencetype", jsonObject.getStr("type"));
                }


                LambdaQueryWrapper<SysDictionaryItems> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(SysDictionaryItems::getDictId, "fedeb076ef96422eee01c88d7f7efd4e").eq(SysDictionaryItems::getItemCode, deviceobj.get("sliencetype")); //缺陷类别字典
                queryWrapper.select(SysDictionaryItems::getItemCode,
                        SysDictionaryItems::getDictName, SysDictionaryItems::getCustom1,
                        SysDictionaryItems::getCustom2);
                SysDictionaryItems item = sysDictionaryItemsService.getOne(queryWrapper);
                JSONArray typeresult = new JSONArray();
                if (StrUtil.isNotEmpty(item.getCustom1()) && JSONUtil.isTypeJSONArray(item.getCustom1())) {
                    //确认一下是否是这个字段
                    typeresult.addAll(JSONUtil.parseArray(item.getCustom1()));
                }
                jsonObject.putOpt("defectresulttypes", JSONUtil.toJsonStr(typeresult));

                deviceobj.putOnce("customParams", jsonObject);
                key += "_" + jsonObject.getStr("type");
                int taskcycle = 30000;
                if (StrUtil.isNotEmpty(jsonObject.getStr("frame_interval"))) {
                    taskcycle = (int) Math.ceil(Integer.parseInt(jsonObject.getStr("frame_interval")) * 1000);
                }
                //调用静默监视任务
                if (taskcycle > 0) {
                    dynamicTask.startCron(key, new DailyMonitorJob(JSONUtil.toJsonStr(deviceobj)), taskcycle);
                }
            }
        }
    }

    private void stopPatrolDeviceJob(SubstationPatroldevice device) {
        String key = "DailyMonitorJob_" + device.getStationCode() + "_" + device.getPatroldeviceCode();
        String sliencetypes = device.getSlienceType();
        if (StrUtil.isNotEmpty(sliencetypes)) {
            String[] sliencetype = sliencetypes.split(",");
            for (String s : sliencetype) {
                key += "_" + s;
                try {
                    dynamicTask.stop(key);
                } catch (Exception e) {
                    log.error(e.getMessage());;
                }
            }
        }
    }

    /**
     * 判断摄像机是否处于巡视任务状态
     *
     * @param stationcode 变电站编号
     * @param devicecode  摄像机编号
     * @return String 是否工作中
     */
    @Override
    public String isWorkingofPatroldevice(String stationcode, String devicecode) {
        List<SubstationPatroldevice> list = this.list(new LambdaQueryWrapper<SubstationPatroldevice>().eq(SubstationPatroldevice::getPatroldeviceCode, devicecode));
        String code = devicecode;
        if (list.size() > 0) {
            SubstationPatroldevice substationPatroldevice = list.get(0);
            String channelinfo = substationPatroldevice.getChannelinfo();
            if (JSONUtil.isTypeJSONArray(channelinfo)) {
                JSONArray jarray = JSONUtil.parseArray(channelinfo);
                for (int i = 0; i < jarray.size(); i++) {
                    JSONObject jobj = jarray.getJSONObject(i);
                    if (jobj.getStr("channel_type").equals("2")) { //红外
                        if (ObjUtil.isNotEmpty(jobj.getStr("pan_code"))) {
                            code = jobj.getStr("pan_code");
                        }
                    }
                }
            }
        }
        String rediskey = RiisConstants.Patroldevice_IsWorking + stationcode + "_" + code;
        String isworking = redisTemplate.opsForValue().get(rediskey);
        if (StrUtil.isEmpty(isworking)) {
            return "0";
        }
        return isworking;
    }

    /**********************************
     * 用途说明: 摄像机录像完整率统计
     * 参数说明 page
     * 参数说明 stationId
     * 参数说明 patrolDeviceName
     * 参数说明 channel
     * 参数说明 flag
     * 返回值说明: com.baomidou.mybatisplus.extension.plugins.pagination.Page<java.util.Map<java.lang.String,java.lang
     * .Object>>
     ***********************************/
    @Override
    public Page<Map<String, Object>> getCameraIntegrityRate(Page<Map<String, Object>> page, String stationId,
                                                            String patrolDeviceName, String channel, String flag) {
        LambdaQueryWrapper<SubstationPatroldevice> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(stationId)) {
            queryWrapper.eq(SubstationPatroldevice::getStationId, stationId);
        }
        if (StrUtil.isNotBlank(patrolDeviceName)) {
            queryWrapper.eq(SubstationPatroldevice::getPatroldeviceName, patrolDeviceName);
        }
        if (StrUtil.isNotBlank(channel)) {

        }
        if (StrUtil.isNotBlank(flag)) {

        }
        Page<Map<String, Object>> mapPage = this.pageMaps(page, queryWrapper);
        List<Map<String, Object>> records = mapPage.getRecords();
        DateTime date = DateUtil.date();
        records.forEach(r -> {
            Date startDate = DateUtil.parse("2023-05-20 02:00:00");
            //相差毫秒数
            long millis = DateUtil.between(startDate, date, DateUnit.MS);
            String formatSecond = DateUtil.formatBetween(millis, BetweenFormatter.Level.SECOND);
            // 录像时长
            r.put("duration", formatSecond);
            // 录像周期
            r.put("cycle", formatSecond);
            int num = (int) (((float) millis / millis) * 100 + 0.5);
            // 录像完整率
            r.put("rate", num);
            if (num == 100) {
                r.put("isComplete", "1");
            } else {
                r.put("isComplete", "0");
            }
        });
        return mapPage;
    }

    /**********************************
     * 用途说明: 设置静默监视是否启用
     * 参数说明
     * 返回值说明: void
     ***********************************/
    @Override
    public boolean setDailyMonitorStatus(String id, String dailyMonitor) {
        LambdaUpdateWrapper<SubstationPatroldevice> updateWrapper = new LambdaUpdateWrapper<>();
        //根据id 修改是否启用静默任务 ，最近修改人，最近修改时间
        updateWrapper.eq(SubstationPatroldevice::getPatroldeviceId, id).set(SubstationPatroldevice::getDailymonitor,
                dailyMonitor).set(SubstationPatroldevice::getLastmodifier, SecurityUtils.getCurrentUsername()).set(SubstationPatroldevice::getLastmodifydate, new Timestamp(System.currentTimeMillis()));
        this.update(updateWrapper);
        SubstationPatroldevice device = this.getById(id);
        //启动或者停止对应静默任务号
        if ("1".equals(dailyMonitor)) {
            startPatroldeviceJob(device);
        } else {
            stopPatrolDeviceJob(device);
        }
        return true;
    }

    @Override
    public Page<Map<String, Object>> getCameraStat(Page<Map<String, Object>> page, String stationId,
                                                   String patrolDeviceName, String channel, String flag) {

        Page<Map<String, Object>> cameraStatPage = substationPatroldeviceMapper.getCameraStat(page, stationId,
                patrolDeviceName, channel, flag);
        List<Map<String, Object>> records = cameraStatPage.getRecords();
        records.forEach(r -> {
            if (ObjectUtil.isNotEmpty(r.get("ipaddr"))) {
                DeviceChannel deviceChannel = this.queryChannelByDeviceIp(r.get("ipaddr").toString());
                if (deviceChannel != null) {
                    String cameraStatByCode = this.getCameraStatByCode(deviceChannel.getChannelid());
                    if (StrUtil.isNotBlank(cameraStatByCode)) {
                        long sum = 90 * 24 * 60;
                        long duration = Long.parseLong(cameraStatByCode) / 60;
                        r.put("duration", duration);
                        r.put("rate", (int) (((float) duration / sum) * 100 + 0.5));
                        r.put("cycle", 90);
                    }
                }
            }
        });
        cameraStatPage.setRecords(records);
        return cameraStatPage;
    }

    @Override
    public List<Map<String, Object>> getCameraStat(String stationCode) {
        List<Map<String, Object>> cameraStatReport = substationPatroldeviceMapper.getCameraStatReport(stationCode);
        cameraStatReport.forEach(r -> {
            String channelId = r.get("channelId").toString();
            String cameraStatByCode = this.getCameraStatByCode(channelId);
            if (StrUtil.isNotBlank(cameraStatByCode)) {
                long sum = 90 * 24 * 60;
                long duration = Long.parseLong(cameraStatByCode) / 60;
                r.put("duration", duration);
//                String num = String.format("%.3f", ((float) duration * 100 / sum));
                r.put("rate", String.format("%.3f", ((float) duration * 100 / sum)));
                r.put("cycle", 90);
            }
        });
        return cameraStatReport;
    }

    /**********************************
     * 用途说明: 单个摄像机完整率
     * 参数说明 channelId
     * 返回值说明: java.util.Map<java.lang.String,java.lang.Object>
     ***********************************/
    @Override
    public String getCameraStatByCode(String channelId) {
        String redisKey = Constant.REDIS_RECORD_TIMES_PRE + channelId;
        if (ObjectUtil.isEmpty(redisTemplate.opsForValue().get(redisKey))) {
            return null;
        }
        return String.valueOf(redisTemplate.opsForValue().get(redisKey));
    }

    /**********************************
     * 用途说明: 巡视设备累计运行天数
     * 参数说明 page
     * 参数说明 stationId
     * 参数说明 patrolDeviceName
     * 参数说明 patrolDeviceCode
     * 参数说明 type
     * 返回值说明: com.baomidou.mybatisplus.extension.plugins.pagination.Page<java.util.Map<java.lang.String,java.lang
     * .Object>>
     ***********************************/
    @Override
    public Page<Map<String, Object>> getRobotOnlineRate(Page<Map<String, Object>> page, String stationId,
                                                        String patrolDeviceName, String patrolDeviceCode, String type) {
        LambdaQueryWrapper<SubstationPatroldevice> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(stationId)) {
            queryWrapper.eq(SubstationPatroldevice::getStationId, stationId);
        }
        if (StrUtil.isNotBlank(patrolDeviceName)) {
            queryWrapper.like(SubstationPatroldevice::getPatroldeviceName, patrolDeviceName);
        }
        if (StrUtil.isNotBlank(patrolDeviceCode)) {
            queryWrapper.eq(SubstationPatroldevice::getPatroldeviceCode, patrolDeviceCode);
        }
        if (StrUtil.isNotBlank(type)) {
            queryWrapper.eq(SubstationPatroldevice::getType, type);
        } else {
            queryWrapper.in(SubstationPatroldevice::getType, "1", "2", "3", "13");
        }
        queryWrapper.select(SubstationPatroldevice::getPatroldeviceId, SubstationPatroldevice::getPatroldeviceCode,
                SubstationPatroldevice::getPatroldeviceName, SubstationPatroldevice::getType,
                SubstationPatroldevice::getOnline).orderByAsc(SubstationPatroldevice::getPatroldeviceCode);
        Page<Map<String, Object>> mapPage = this.pageMaps(page, queryWrapper);
        List<Map<String, Object>> records = mapPage.getRecords();
        records.forEach(r -> {
            // 最近开始时间
            r.put("recentStartTime", "2023-08-01 00:00:00");
            // 最近结束间
            r.put("recentEndTime", "2023-08-08 00:00:00");
            // 在线时长
            r.put("onlineDuration", 168);
            // 累计离线次数
            r.put("onlineNumber", 20);
            // 连续正常运行天数
            r.put("normalDay", 2);
            // 自检正常天数
            r.put("checkNormal", 8);
        });
        mapPage.setRecords(records);
        return mapPage;
    }

    /**********************************
     * 用途说明: 巡视设备累计运行天数
     * 返回值说明: com.baomidou.mybatisplus.extension.plugins.pagination.Page<java.util.Map<java.lang.String,java.lang.Object>>
     ***********************************/
    @Override
    public List<Map<String, Object>> getRobotOnlineRate() {
        LambdaQueryWrapper<SubstationPatroldevice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SubstationPatroldevice::getType, "1", "2", "3", "13");
        queryWrapper.select(SubstationPatroldevice::getPatroldeviceId, SubstationPatroldevice::getPatroldeviceCode,
                SubstationPatroldevice::getPatroldeviceName, SubstationPatroldevice::getType,
                SubstationPatroldevice::getOnline).orderByAsc(SubstationPatroldevice::getPatroldeviceCode);
        List<Map<String, Object>> mapList = this.listMaps(queryWrapper);
        mapList.forEach(r -> {
            // 最近开始时间
            r.put("recentStartTime", "2023-08-01 00:00:00");
            // 最近结束间
            r.put("recentEndTime", "2023-08-08 00:00:00");
            // 在线时长
            r.put("onlineDuration", 168);
            // 累计离线次数
            r.put("onlineNumber", 20);
            // 连续正常运行天数
            r.put("normalDay", 2);
            // 自检正常天数
            r.put("checkNormal", 8);
        });
        return mapList;
    }

    /**********************************
     * 用途说明: 新增巡视设备
     * 参数说明 patrolDeviceInfo
     * 返回值说明: boolean
     ***********************************/
    @Override
    public boolean addPatrolDevice(String patrolDeviceInfo) {
        JSONObject jsonObject = JSONUtil.parseObj(patrolDeviceInfo);
        SubstationPatroldevice substationPatroldevice = JSONUtil.toBean(jsonObject, SubstationPatroldevice.class);
        String stationId = substationPatroldevice.getStationId();
        int count =
                this.count(new LambdaQueryWrapper<SubstationPatroldevice>().eq(SubstationPatroldevice::getStationId,
                        stationId).eq(SubstationPatroldevice::getPatroldeviceCode,
                        substationPatroldevice.getPatroldeviceCode()));
        if (count > 0) {
            return false;
        }
        String id = IdUtil.fastSimpleUUID();
        substationPatroldevice.setPatroldeviceId(id);
        substationPatroldevice.setLastmodifier(SecurityUtils.getCurrentUsername());
        substationPatroldevice.setLastmodifydate(LocalDateTime.now());
        substationPatroldevice.setDatastatus("1");
        return this.save(substationPatroldevice);
    }

    @Override
    public boolean setEffectiveArea(String type, String id, String effecttivearea) {
        //todo 设置有限区域
        return true;
    }

    /**********************************
     * 用途说明: 导出巡视设备台账
     * 参数说明 stationId 变电站id
     * 参数说明 type 设备类型
     * 参数说明 patrolDeviceName 设备名称
     * 参数说明 deviceModel 设备型号
     * 参数说明 manufacturer 生产厂家
     * 参数说明 response
     * 返回值说明: void
     ***********************************/
    @Override
    public void exportPatrolDeviceList(String stationId, String type, String patrolDeviceName, String deviceModel,
                                       String manufacturer, HttpServletResponse response) throws IOException {
        LambdaQueryWrapper<SubstationPatroldevice> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(stationId)) {
            queryWrapper.eq(SubstationPatroldevice::getStationId, stationId);
        }
        if (StrUtil.isNotBlank(type)) {
            if ("10".equals(type)) {
                queryWrapper.in(SubstationPatroldevice::getType, "10", "11");
            } else {
                queryWrapper.eq(SubstationPatroldevice::getType, type);
            }
        }
        if (StrUtil.isNotBlank(patrolDeviceName)) {
            queryWrapper.like(SubstationPatroldevice::getPatroldeviceName, patrolDeviceName);
        }
        if (StrUtil.isNotBlank(deviceModel)) {
            queryWrapper.like(SubstationPatroldevice::getDeviceModel, deviceModel);
        }
        if (StrUtil.isNotBlank(manufacturer)) {
            queryWrapper.like(SubstationPatroldevice::getManufacturer, manufacturer);
        }
        queryWrapper.orderByAsc(SubstationPatroldevice::getPatroldeviceCode);
        List<SubstationPatroldevice> list = this.list(queryWrapper);
        List<Map<String, Object>> mapList = new ArrayList<>();
        Map<String, Object> patrolEquipmentType = sysDictionaryItemsService.getDeviceMapByType(
                "PatrolEquipmentType");
        JSONObject patrolEquipmentTypeMap=JSONUtil.parseObj(patrolEquipmentType.get("resultMap"));

        Map<String, Object> manuFacturer = sysDictionaryItemsService.getDeviceMapByType(
                "ManuFacturer");
        JSONObject manuFacturerMap=JSONUtil.parseObj(manuFacturer.get("resultMap"));
        for (int i = 0; i < list.size(); i++) {
            SubstationPatroldevice substationPatroldevice = list.get(i);
            String devtype = StrUtil.isNotBlank(type) ? patrolEquipmentTypeMap.getStr(type) : "";
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("序号", (i + 1));
            map.put("设备名称", substationPatroldevice.getPatroldeviceName());
            map.put("设备类型", devtype);
            map.put("设备型号", substationPatroldevice.getDeviceModel());
            map.put("设备来源", substationPatroldevice.getDeviceSource());
            String manufacturerName = StrUtil.isNotBlank(substationPatroldevice.getManufacturer()) ? manuFacturerMap.getStr(substationPatroldevice.getManufacturer()) : "";
            map.put("生产厂家", manufacturerName);
            map.put("安装位置", substationPatroldevice.getPlace());
            String online = "1".equals(substationPatroldevice.getOnline()) ? "在线" : "离线";
            map.put("实时状态", online);
            String datastatus = "1".equals(substationPatroldevice.getDatastatus()) ? "有效" : "无效";
            map.put("设备状态", datastatus);
            mapList.add(map);

        }

        //        for (SubstationPatroldevice substationPatroldevice : list) {
        //            String devtype = "";
        //            for (Map<String, Object> map : patrolEquipmentType) {
        //                String itemcode = (String) map.get("itemcode");
        //                if (itemcode.equals(type)) {
        //                    devtype = map.get("dictname").toString();
        //                    break;
        //                }
        //            }
        //            Map<String, Object> map = new LinkedHashMap<>();
        //            map.put("devtype", devtype);
        //            map.put("devname", substationPatroldevice.getPatroldeviceName());
        //            map.put("devdesc", "");
        //            map.put("devmodel", substationPatroldevice.getDeviceModel());
        //            map.put("manufacturer", substationPatroldevice.getManufacturer());
        //            map.put("madein", "");
        //            map.put("productionnum", substationPatroldevice.getProductionCode());
        //            map.put("productiondate", substationPatroldevice.getProductionDate());
        //            map.put("phyassetID", substationPatroldevice.getMaterialId());
        //            map.put("position_x", "");
        //            map.put("position_y", "");
        //            map.put("region", "");
        //            map.put("cabinet", "");
        //            map.put("hwRev", "");
        //            map.put("SwRev", "");
        //            if ("1".equals(type) || "2".equals(type) || "3".equals(type)) {
        //                map.put("SwRevCRC", "");
        //                map.put("IPAddr", substationPatroldevice.getIpaddr());
        //                map.put("MacAddr", substationPatroldevice.getMacaddr());
        //            } else if ("10".equals(type)) {
        //                map.put("SwRevCRC", "");
        //                map.put("IPAddr", substationPatroldevice.getIpaddr());
        //                map.put("MacAddr", substationPatroldevice.getMacaddr());
        //            } else if ("11".equals(type)) {
        //                map.put("SwRevCRC", "");
        //                map.put("IPAddr", substationPatroldevice.getIpaddr());
        //                map.put("MacAddr", substationPatroldevice.getMacaddr());
        //            } else if ("13".equals(type)) {
        //
        //            }
        //            mapList.add(map);
        //        }
        //        String[] headers = {"设备类型", "设备名称", "中文描述", "设备型号", "生产厂家", "生产国家", "出厂编号", "出厂日期", "实物 ID",
        //        "相对空间位置 x", "相对空间位置 y", "所属区域标识"};
        //        String[] keys = {  "devtype", "devname", "devdesc", "devmodel","manufacturer", "madein",
        //        "productionnum", "productiondate", "phyassetID","position_x", "position_y", "region"};
        //        FileUtil.excelImg(mapList, headers, keys, "", "", response);
        FileUtil.downloadExcel(mapList, response);
    }

    @Override
    public DeviceChannel queryChannelByDeviceIp(String ipaddr) {
        LambdaQueryWrapper<DeviceChannel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DeviceChannel::getAddress, ipaddr);
        List<DeviceChannel> deviceChannels = deviceChannelMapper.selectList(queryWrapper);
        if (deviceChannels == null || deviceChannels.size() == 0) {
            return null;
        }
        return deviceChannels.get(0);
    }

    @Override
    public List<Map<String, Object>> getDockInfoBySn(String dockSn) {

       return substationPatroldeviceMapper.getDockInfoBySn(dockSn);

    }

}
