package com.fastbee.data.controller.anfang.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import com.fastbee.common.config.RuoYiConfig;
import com.fastbee.common.exception.ServiceException;
import com.fastbee.common.model.bto.DoorAlertBto;
import com.fastbee.common.utils.DevParamsUtils;
import com.fastbee.common.utils.StringUtils;
import com.fastbee.common.utils.file.FileUploadUtils;
import com.fastbee.data.controller.anfang.service.IUploadedPhotosService;
import com.fastbee.iot.domain.Device;
import com.fastbee.iot.domain.DeviceAlertUser;
import com.fastbee.iot.haikang.HaikangYingshiApi;
import com.fastbee.iot.mapper.DeviceAlertUserMapper;
import com.fastbee.iot.mapper.UploadedPhotosMapper;
import com.fastbee.iot.model.anfang.UploadedPhotos;
import com.fastbee.iot.service.IDeviceService;
import com.fastbee.notify.core.service.NotifySendService;
import com.fastbee.notify.core.vo.SendParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 存储上传的照片信息Service业务层处理
 *
 * @author kerwincui
 * @date 2024-06-20
 */
@Service
public class UploadedPhotosServiceImpl implements IUploadedPhotosService {
    @Resource
    private UploadedPhotosMapper uploadedPhotosMapper;
    @Autowired
    private IDeviceService deviceService;

    @Autowired
    private NotifySendService notifySendService;

    @Autowired
    private RuoYiConfig ruoYiConfig;

    private HaikangYingshiApi haikangYingshiApi;
    @Autowired
    private DeviceAlertUserMapper deviceAlertUserMapper;

    /**
     * 查询存储上传的照片信息
     *
     * @param id 存储上传的照片信息主键
     * @return 存储上传的照片信息
     */
    @Override
    public UploadedPhotos selectUploadedPhotosById(Long id) {
        return uploadedPhotosMapper.selectUploadedPhotosById(id);
    }

    /**
     * 查询存储上传的照片信息列表
     *
     * @param uploadedPhotos 存储上传的照片信息
     * @return 存储上传的照片信息
     */
    @Override
    public List<UploadedPhotos> selectUploadedPhotosList(UploadedPhotos uploadedPhotos) {
        return uploadedPhotosMapper.selectUploadedPhotosList(uploadedPhotos);
    }

    /**
     * 新增存储上传的照片信息
     *
     * @param uploadedPhotos 存储上传的照片信息
     * @return 结果
     */
    @Override
    public int insertUploadedPhotos(UploadedPhotos uploadedPhotos) {
        return uploadedPhotosMapper.insertUploadedPhotos(uploadedPhotos);
    }

    /**
     * 修改存储上传的照片信息
     *
     * @param uploadedPhotos 存储上传的照片信息
     * @return 结果
     */
    @Override
    public int updateUploadedPhotos(UploadedPhotos uploadedPhotos) {
        return uploadedPhotosMapper.updateUploadedPhotos(uploadedPhotos);
    }

    /**
     * 批量删除存储上传的照片信息
     *
     * @param ids 需要删除的存储上传的照片信息主键
     * @return 结果
     */
    @Override
    public int deleteUploadedPhotosByIds(Long[] ids) {
        return uploadedPhotosMapper.deleteUploadedPhotosByIds(ids);
    }

    /**
     * 删除存储上传的照片信息信息
     *
     * @param id 存储上传的照片信息主键
     * @return 结果
     */
    @Override
    public int deleteUploadedPhotosById(Long id) {
        return uploadedPhotosMapper.deleteUploadedPhotosById(id);
    }

    @Override
    public String captureMonitorPhoto(String sn) {
        Device device = deviceService.selectDeviceBySerialNumber(sn);
        if (device == null) {
            return "";
        }
        Map<String, Object> devParams = DevParamsUtils.getDevParams(device.getDevParams());
        if (!devParams.containsKey("jiankongIds")) {
            return "";
        }
        String jiankongIds = devParams.get("jiankongIds").toString();
        Device jiankongDevice = deviceService.selectDeviceByDeviceId(Long.parseLong(jiankongIds));
        if (jiankongDevice == null) {
            return "";
        }
        Map devData = DevParamsUtils.getDevParams(jiankongDevice.getDevParams());
        if (devData.get("appKey") == null) {
            return "";
        }
        if (devData.get("appSecret") == null) {
            return "";
        }
        if (devData.get("channelNo") == null) {
            return "";
        }
        Map<String, Object> map = new HashMap<>();//存放参数
        map.put("appKey", devData.get("appKey"));
        map.put("appSecret", devData.get("appSecret"));
        cn.hutool.json.JSONObject token = HaikangYingshiApi.getToken(map);
        if (token != null && token.get("code").equals("200")) {
            Map<String, Object> params = new HashMap<>();
            token = (cn.hutool.json.JSONObject) token.get("data");
            params.put("accessToken", token.get("accessToken"));
            params.put("deviceSerial", jiankongDevice.getSerialNumber());
            params.put("channelNo", devData.get("channelNo"));
            cn.hutool.json.JSONObject token1 = HaikangYingshiApi.capture(params);
            if (token1 != null && token1.get("code").equals("200")) {
                String dirs = DateUtil.thisYear() + "/" + (DateUtil.thisMonth() + 1) + "/" + DateUtil.thisDayOfMonth();
                File dirfile = new File(RuoYiConfig.getUploadPath() + "/" + dirs);
                if (!dirfile.exists()) {
                    // 目录不存在，创建目录
                    boolean created = dirfile.mkdirs();
                    if (created) {
                    } else {
                    }
                } else {
                }
                Map data = (JSONObject) token1.get("data");
                Map<String, Object> reMap = new HashMap<>();
                reMap.put("picUrl", data.get("picUrl"));
                if (data.get("picUrl") != null) {
                    try {
                        String picUrl = data.get("picUrl").toString();
                        URL url = new URL(picUrl);
                        HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
                        int responseCode = httpConnection.getResponseCode();
                        if (responseCode == HttpURLConnection.HTTP_OK) {
                            InputStream inputStream = httpConnection.getInputStream();
                            byte[] buffer = new byte[4096];
                            int bytesRead = -1;
                            String[] split1 = picUrl.split("\\.");
                            String filename =
                                    DateUtil.date().toDateStr() + "-" + DateUtil.thisHour(true)
                                            + DateUtil.thisMinute() +
                                            "-anfangmonitor-" + device.getDeviceId() + "."
                                            + split1[split1.length - 1].split("\\?")[0];
                            String pathUrl = RuoYiConfig.getUploadPath() + "/" + dirs + "/" + filename;
                            OutputStream outputStream = new FileOutputStream(pathUrl);
                            while ((bytesRead = inputStream.read(buffer)) != -1) {
                                outputStream.write(buffer, 0, bytesRead);
                            }
                            outputStream.close();
                            inputStream.close();
                            String httpimg = FileUploadUtils.getPathFileName(RuoYiConfig.getUploadPath(), dirs +
                                    "/" + filename);
                            return httpimg;
                        } else {
                            System.out.println("读取http图片失败!");
                            return "";
                        }
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
                return "";
            } else {
                return "";
            }
        }
        return "";
    }


    @Override
    public void sendAlarmMessage(String sn, String doorState, String shakeState, String eventType) {
        //
        boolean notify = false;
        SendParams sendParams = new SendParams();
        sendParams.setId(14L);
        Map<String, String> temp = new HashMap<>();
        Device device = deviceService.selectDeviceBySerialNumber(sn);
        if (device == null) {
            return;
        }
        Map<String, Object> devParams = DevParamsUtils.getDevParams(device.getDevParams());
        Device jijingDevice = null;
        if (devParams.containsKey("jijingIds")) {
            String jijingIds = devParams.get("jijingIds").toString();
            jijingDevice = deviceService.selectDeviceByDeviceId(Long.parseLong(jijingIds));
            if (jijingDevice == null) {
                return;
            }
            temp.put("stationName", jijingDevice.getDeviceName());
        } else {
            return;
        }
        if (Integer.parseInt(eventType) == 2) {
            temp.put("warnInfo", "箱门打开");
            notify = true;
        } else if (Integer.parseInt(eventType) == 1) {
            temp.put("warnInfo", "箱门振动");
            notify = true;
        } else if (Integer.parseInt(eventType) == 3) {
            temp.put("warnInfo", "箱门持续打开");
            notify = true;
        }else if(Integer.parseInt(eventType) == 4){
            temp.put("warnInfo", "开启布放");
            notify = true;
        }else if(Integer.parseInt(eventType) == 5){
            temp.put("warnInfo", "撤防");
            notify = true;
        }
        if (notify) {
            DeviceAlertUser deviceAlertUser = new DeviceAlertUser();
            deviceAlertUser.setDeviceId(jijingDevice.getDeviceId());
            List<DeviceAlertUser> deviceAlertUsers = deviceAlertUserMapper.selectDeviceAlertUserList(deviceAlertUser);
            if (deviceAlertUsers.size() > 0) {
                String phone = "";
                for (int i = 0; i < deviceAlertUsers.size(); i++) {
                    if (i == 0) {
                        phone = deviceAlertUsers.get(i).getPhoneNumber();
                    } else {
                        phone += "," + deviceAlertUsers.get(i).getPhoneNumber();
                    }
                }
                if (StringUtils.isEmpty(phone)) {
                    return;
                }
                sendParams.setSendAccount(phone);
                JSONObject jsonObject = new JSONObject(temp);
                String jsonString = jsonObject.toString();
                sendParams.setVariables(jsonString);
                notifySendService.send(sendParams);
            }
        }
    }

    @Override
    public String doorAlert(DoorAlertBto doorAlertBto) throws Exception {
        Device device = deviceService.selectDeviceByDeviceId(doorAlertBto.getDeviceId());
        if (device == null) {
            throw new Exception("未找到设备");
        }
        int doorState = 0;
        int shakeState = 0;
        int anFangStatus = 0;
        int eventType = doorAlertBto.getEventType();
        if (doorAlertBto.getEventType() > 0) {
            if (eventType == 1) {
                shakeState = doorAlertBto.getEventType();
                doorState = 0;
                anFangStatus = 1;
            } else if (eventType == 2 || eventType == 3) {
                doorState = 1;
                shakeState = 0;
                anFangStatus = 1;
            }else if(eventType == 4 ){
                anFangStatus = 1;
                doorState = 0;
                shakeState = 0;
            }else if(eventType == 5){
                anFangStatus = 0;
                doorState = 0;
                shakeState = 0;
            }
            sendAlarmMessage(device.getSerialNumber(), doorState + "", shakeState + "", eventType + "");
        }
        //抓拍监控，并返回路径
        String monitorPath = captureMonitorPhoto(device.getSerialNumber());
        UploadedPhotos uploadedPhotos = new UploadedPhotos(
                null, "", monitorPath, "", device.getSerialNumber(),
                device.getLatitude() != null ? device.getLatitude().doubleValue() : 0d,
                device.getLongitude() != null ? device.getLatitude().doubleValue() : 0d,
                18.23d, doorState + "", shakeState + "", 32.3, doorAlertBto.getEventType().toString(),anFangStatus + "", new Date()
        );
        int count = insertUploadedPhotos(uploadedPhotos);
        if (count > 0) {
            return "生成成功";
        } else {
            return "生成失败";
        }
    }

    @Override
    public int uploadPicByTime(UploadedPhotos uploadedPhotos) {
        //根据时间和sn进行复制图片链接
        return uploadedPhotosMapper.updateBySnAndTime(uploadedPhotos);
    }
}
