package com.yzt.airconditionersystem.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.*;
import com.yzt.airconditionersystem.bean.Device;
import com.yzt.airconditionersystem.bean.DeviceData;
import com.yzt.airconditionersystem.bean.FacilityAlarm;
import com.yzt.airconditionersystem.result.Result;
import com.yzt.airconditionersystem.service.*;
import com.yzt.airconditionersystem.util.AirconditionerStatus;
import com.yzt.airconditionersystem.util.BasePageVoUtil;
import com.yzt.airconditionersystem.util.MyUtils;
import com.yzt.airconditionersystem.vo.BasePageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author TzZach
 * @since 2022-04-18 11:10
 */
@Controller
public class FacilityMobileController {

    private static final String PREFIX = "facility/";

    @Autowired
    private FacilityAlarmService facilityAlarmService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private DeviceDataService deviceDataService;
//    @Autowired
//    private MqttProducer mqttProducer;

    @GetMapping("/mobile/status")
    @ResponseBody
    public DeviceData status(@RequestParam("id") String id) {
        LambdaQueryWrapper<Device> deviceLambdaQueryWrapper = new LambdaQueryWrapper<>();
        deviceLambdaQueryWrapper.eq(Device::getGatewayId, id)
                .orderByDesc(Device::getTime);
        //获取最近的一个作为状态显示
        Device device = deviceService.list(deviceLambdaQueryWrapper).get(0);
        LambdaQueryWrapper<DeviceData> dataLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        dataLambdaQueryWrapper.eq(DeviceData::getId, device.getDeviceDataId());
        DeviceData deviceData = deviceDataService.getOne(dataLambdaQueryWrapper);

        String m_bit1 = MyUtils.decToBin(deviceData.getM_bit1());
        String m_bit2 = MyUtils.decToBin(deviceData.getM_bit2());
        String q_bit3 = MyUtils.decToBin(deviceData.getQ_bit3());
        deviceData.setM_bit1BinStr(m_bit1);
        deviceData.setM_bit2BinStr(m_bit2);
        deviceData.setQ_bit3BinStr(q_bit3);


        return deviceData;
    }

//    @GetMapping("/mobile/system-parameter")
    public String systemParameter(Model model, HttpSession session) {

        Device deviceSession = (Device) session.getAttribute("device");
        String gatewayId = deviceSession.getGatewayId();
        //得到最新的device信息，并根据device中的deviceDataId获取对应deviceData
        LambdaQueryWrapper<Device> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Device::getGatewayId, gatewayId)
                .orderByDesc(Device::getTime).last("limit 1");
        Device device = deviceService.getOne(lambdaQueryWrapper);
//        DeviceData deviceData = deviceDataService.getById(device.getDeviceDataId());
//        model.addAttribute("deviceData", deviceData);
        return PREFIX + "system-parameter";
    }

//    @GetMapping("/mobile/parameter-settings")
    public String parameterSettings(Model model, HttpSession session) {
        Device deviceSession = (Device) session.getAttribute("device");
        String gatewayId = deviceSession.getGatewayId();
        //得到最新的device信息，并根据device中的deviceDataId获取对应deviceData
        LambdaQueryWrapper<Device> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Device::getGatewayId, gatewayId)
                        .orderByDesc(Device::getTime).last("limit 1");
        Device device = deviceService.getOne(lambdaQueryWrapper);
//        DeviceData deviceData = deviceDataService.getById(device.getDeviceDataId());
//        deviceData.setM_bit1(MyUtils.decToBin(deviceData.getM_bit1()));
//        deviceData.setM_bit2(MyUtils.decToBin(deviceData.getM_bit2()));
//        deviceData.setQ_bit3(MyUtils.decToBin(deviceData.getQ_bit3()));
//        model.addAttribute("deviceData", deviceData);
        return PREFIX + "parameter-settings";
    }



    @GetMapping("/mobile/dataCurves")
    @ResponseBody
    public Map dataCurves(@RequestParam("gatewayId") String gatewayId) {
//        Device deviceSession = (Device) session.getAttribute("device");
//        String gatewayId = deviceSession.getGatewayId();
        LambdaQueryWrapper<Device> deviceLambdaQueryWrapper = new LambdaQueryWrapper<>();
        deviceLambdaQueryWrapper.eq(Device::getGatewayId, gatewayId)
                .orderByDesc(Device::getTime).last("limit 10");
        List<Device> devices = deviceService.list(deviceLambdaQueryWrapper);
        List<Double> tempReadList = new ArrayList<>();
        List<Double> humiReadList = new ArrayList<>();
        List<String> timeList = new ArrayList<>();
        for (Device device : devices) {
//            DeviceData deviceData = deviceDataService.getById(device.getDeviceDataId());
//            tempReadList.add(deviceData.getTemp_read());
//            humiReadList.add(deviceData.getHumi_read());
            //去掉LocalDateTime中的T
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//            LocalDateTime date = deviceData.getTime();
//            date = LocalDateTime.of(date.getYear(), date.getMonth(), date.getDayOfMonth(),
//                    date.getHour(), date.getMinute(), date.getSecond());
//            String time = date.format(dateTimeFormatter);
//            timeList.add(time);
        }

        HashMap<String, Object> map = new HashMap<>();
        map.put("tempReadList", tempReadList);
        map.put("humiReadList", humiReadList);
        map.put("timeList", timeList);

        return map;
    }

//    @GetMapping("/mobile/alarm-records")
    public String alarmRecords() {
        return PREFIX + "/alarm-records";
    }

//    @GetMapping("/alarmRecords/page")
    @ResponseBody
    public BasePageVo alarmRecordsPage(@RequestParam("page") Long page,
                                       @RequestParam("limit") Long limit) {

        Page<FacilityAlarm> pageInfo = new Page<>(page, limit);
        pageInfo = facilityAlarmService.page(pageInfo);
        BasePageVo pageVo = BasePageVoUtil.getPageVo(pageInfo);
        return pageVo;
    }

//    @GetMapping("/alarmRecords/search")
    @ResponseBody
    public BasePageVo alarmRecordsSearch(@RequestParam("page") Long page,
                                         @RequestParam("limit") Long limit,
                                         FacilityAlarm facilityAlarm) {

        String startTime = facilityAlarm.getStartTime();
        String endTime = facilityAlarm.getEndTime();

        Page<FacilityAlarm> pageInfo = new Page<>(page, limit);

        LambdaQueryWrapper<FacilityAlarm> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.between(FacilityAlarm::getTime, startTime, endTime);
        pageInfo = facilityAlarmService.page(pageInfo, queryWrapper);

        BasePageVo pageVo = BasePageVoUtil.getPageVo(pageInfo);
        return pageVo;
    }

//    @PostMapping("/mobile/alarmRecords/status")
    @ResponseBody
    public Result alarmRecordsUpdateStatus(@RequestBody FacilityAlarm facilityAlarm) {
        facilityAlarm.setStatus(AirconditionerStatus.STATUS_HANDLED);
        facilityAlarmService.updateById(facilityAlarm);
        return Result.success("修改成功");
    }

//    @PostMapping("/mobile/parameterSetting/update")
    @ResponseBody
    public Result parameterSettingUpdate(@RequestBody DeviceData deviceData, HttpSession session) {
        Device deviceSession = (Device) session.getAttribute("device");
        Gson gson = new GsonBuilder().create();
        String deviceDataJsonStr = gson.toJson(deviceData);
        String deviceId = deviceSession.getDeviceId();
        //获取要发送到的空调名作为前缀
        String prefix = deviceId.substring(0, deviceId.lastIndexOf("_"));
        JsonObject deviceDataJson = JsonParser.parseString(deviceDataJsonStr).getAsJsonObject();
        JsonObject deviceDataJsonSend = new JsonObject();
        //遍历json，给key添加前缀，放入到deviceDataJsonSend中
        for (Map.Entry<String, JsonElement> stringJsonElementEntry : deviceDataJson.entrySet()) {
            String key = stringJsonElementEntry.getKey().toString();
            JsonElement value = stringJsonElementEntry.getValue();
            deviceDataJsonSend.add(prefix + "_" + key, value);
        }

        //固定json格式
        JsonObject jsonObject = new JsonObject();
        JsonArray devices = new JsonArray();
        JsonObject device = new JsonObject();
        device.add("deviceId", JsonParser.parseString(deviceId));
        device.add("deviceData", JsonParser.parseString(deviceDataJsonSend.toString()));
        devices.add(device);
        jsonObject.add("devices", devices);
//        mqttProducer.send("mqtt/" + deviceSession.getCompanyName() + "/" + deviceSession.getDeviceId() + "/plc_cmd"
//                , jsonObject.toString());

        return Result.success(jsonObject.toString());
    }

}
