package cn.iocoder.yudao.module.iot.controller.admin.gateway;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.iot.controller.admin.gateway.vo.GatewayPageReqVO;
import cn.iocoder.yudao.module.iot.controller.admin.gateway.vo.GatewayRespVO;
import cn.iocoder.yudao.module.iot.controller.admin.gateway.vo.GatewaySaveReqVO;
import cn.iocoder.yudao.module.iot.dal.dataobject.device.DeviceDO;
import cn.iocoder.yudao.module.iot.dal.dataobject.gateway.GatewayDO;
import cn.iocoder.yudao.module.iot.framework.constant.IsEnableConstant;
import cn.iocoder.yudao.module.iot.framework.mqtt.consumer.IMqttservice;
import cn.iocoder.yudao.module.iot.service.gateway.GatewayService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@Tag(name = "管理后台 - 网关")
@RestController
@RequestMapping("/iot/gateway")
@Validated
public class GatewayController {

    @Resource
    private GatewayService gatewayService;
    @Resource
    private IMqttservice mqttservice;

    @PostMapping("/create")
    @Operation(summary = "创建网关")
    @PreAuthorize("@ss.hasPermission('iot:gateway:create')")
    public CommonResult<Long> createGateway(@Valid @RequestBody GatewaySaveReqVO createReqVO) {
        Long id = gatewayService.createGateway(createReqVO);

        if (id != null && IsEnableConstant.IsEnableTrue == createReqVO.getIsEnable()
                && StringUtils.isNotBlank(createReqVO.getTopic())) {
            try {
                mqttservice.subscribeTopic(createReqVO.getTopic());
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }
        return success(id);
    }

    @PutMapping("/update")
    @Operation(summary = "更新网关")
    @PreAuthorize("@ss.hasPermission('iot:gateway:update')")
    public CommonResult<Boolean> updateGateway(@Valid @RequestBody GatewaySaveReqVO updateReqVO) {
        GatewayDO old = gatewayService.getGateway(updateReqVO.getId());
        gatewayService.updateGateway(updateReqVO);
        /**todo 订阅*/
        try {
            if (old != null && StringUtils.isNotBlank(old.getTopic()) && StringUtils.isNotBlank(updateReqVO.getTopic())) {
                boolean sameTopic = false;
                if (old.getTopic().equals(updateReqVO.getTopic())) sameTopic = true;
                if (sameTopic) {
                    //启用订阅
                    if (updateReqVO.getIsEnable().equals(IsEnableConstant.IsEnableTrue))
                        mqttservice.subscribeTopic(updateReqVO.getTopic());
                        //禁用订阅
                    else mqttservice.unsubscribeTopic(updateReqVO.getTopic());
                } else {
                    //禁用旧订阅
                    if (old.getIsEnable().equals(IsEnableConstant.IsEnableTrue))
                        mqttservice.unsubscribeTopic(old.getTopic());
                    //启用新订阅
                    if (updateReqVO.getIsEnable().equals(IsEnableConstant.IsEnableTrue))
                        mqttservice.subscribeTopic(updateReqVO.getTopic());
                }
            }
        } catch (MqttException e) {
            e.printStackTrace();
        }

        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除网关")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('iot:gateway:delete')")
    public CommonResult<Boolean> deleteGateway(@RequestParam("id") Long id) {
        gatewayService.deleteGateway(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得网关")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('iot:gateway:query')")
    public CommonResult<GatewayRespVO> getGateway(@RequestParam("id") Long id) {
        GatewayDO gateway = gatewayService.getGateway(id);
        return success(BeanUtils.toBean(gateway, GatewayRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得网关分页")
    @PreAuthorize("@ss.hasPermission('iot:gateway:query')")
    public CommonResult<PageResult<GatewayRespVO>> getGatewayPage(@Valid GatewayPageReqVO pageReqVO) {
        PageResult<GatewayDO> pageResult = gatewayService.getGatewayPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, GatewayRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出网关 Excel")
    @PreAuthorize("@ss.hasPermission('iot:gateway:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportGatewayExcel(@Valid GatewayPageReqVO pageReqVO,
                                   HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<GatewayDO> list = gatewayService.getGatewayPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "网关.xls", "数据", GatewayRespVO.class,
                BeanUtils.toBean(list, GatewayRespVO.class));
    }

    // ==================== 子表（物联设备） ====================

    @GetMapping("/device/page")
    @Operation(summary = "获得物联设备分页")
    @Parameter(name = "gatewayId", description = "网关id")
    @PreAuthorize("@ss.hasPermission('iot:gateway:query')")
    public CommonResult<PageResult<DeviceDO>> getDevicePage(PageParam pageReqVO,
                                                            @RequestParam("gatewayId") Long gatewayId) {
        return success(gatewayService.getDevicePage(pageReqVO, gatewayId));
    }

    @PostMapping("/device/create")
    @Operation(summary = "创建物联设备")
    @PreAuthorize("@ss.hasPermission('iot:gateway:create')")
    public CommonResult<Long> createDevice(@Valid @RequestBody DeviceDO device) {
        return success(gatewayService.createDevice(device));
    }

    @PutMapping("/device/update")
    @Operation(summary = "更新物联设备")
    @PreAuthorize("@ss.hasPermission('iot:gateway:update')")
    public CommonResult<Boolean> updateDevice(@Valid @RequestBody DeviceDO device) {
        gatewayService.updateDevice(device);
        return success(true);
    }

    @DeleteMapping("/device/delete")
    @Parameter(name = "id", description = "编号", required = true)
    @Operation(summary = "删除物联设备")
    @PreAuthorize("@ss.hasPermission('iot:gateway:delete')")
    public CommonResult<Boolean> deleteDevice(@RequestParam("id") Long id) {
        gatewayService.deleteDevice(id);
        return success(true);
    }

    @GetMapping("/device/get")
    @Operation(summary = "获得物联设备")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('iot:gateway:query')")
    public CommonResult<DeviceDO> getDevice(@RequestParam("id") Long id) {
        return success(gatewayService.getDevice(id));
    }

}