package cn.iocoder.yudao.module.pms.controller.admin.yanfan.device;

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.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.pms.controller.admin.yanfan.device.vo.DeviceShortOutput;
import cn.iocoder.yudao.module.pms.controller.admin.yanfan.device.vo.YfIotDevicePageReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.yanfan.device.vo.YfIotDeviceRespVO;
import cn.iocoder.yudao.module.pms.controller.admin.yanfan.device.vo.YfIotDeviceSaveReqVO;
import cn.iocoder.yudao.module.pms.dal.dataobject.IotDeviceDO;
import cn.iocoder.yudao.module.pms.dal.dataobject.yanfan.device.YfIotDeviceDO;
import cn.iocoder.yudao.module.pms.service.IotDeviceService;
import cn.iocoder.yudao.module.pms.service.yanfan.device.YfIotDeviceService;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
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 java.util.Objects;

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("/rq/yf-iot-device")
@Validated
public class YfIotDeviceController {

    @Resource
    private YfIotDeviceService yfIotDeviceService;
    @Autowired
    private DeptApi deptApi;
    @Autowired
    private IotDeviceService iotDeviceService;

    @PostMapping
    @Operation(summary = "创建设备")
    @PreAuthorize("@ss.hasPermission('rq:yf-iot-device:create')")
    public CommonResult<YfIotDeviceDO> createYfIotDevice(@Valid @RequestBody YfIotDeviceSaveReqVO createReqVO) {
        return success(yfIotDeviceService.createYfIotDevice(createReqVO));
    }

    @PutMapping
    @Operation(summary = "更新设备")
    @PreAuthorize("@ss.hasPermission('rq:yf-iot-device:update')")
    public CommonResult<Boolean> updateYfIotDevice(@Valid @RequestBody YfIotDeviceSaveReqVO updateReqVO) {
        yfIotDeviceService.updateYfIotDevice(updateReqVO);
        return success(true);
    }

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

    @GetMapping("/get")
    @Operation(summary = "获得设备")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('rq:yf-iot-device:query')")
    public CommonResult<YfIotDeviceRespVO> getYfIotDevice(@RequestParam("id") Long id) {
        YfIotDeviceDO yfIotDevice = yfIotDeviceService.getYfIotDevice(id);
        return success(BeanUtils.toBean(yfIotDevice, YfIotDeviceRespVO.class));
    }

    @GetMapping(value = "/{deviceId}")
    @Operation(summary = "获取设备详情")
    public CommonResult<YfIotDeviceRespVO> getInfo(@PathVariable("deviceId") Long deviceId) {
        YfIotDeviceRespVO device = yfIotDeviceService.selectDeviceByDeviceId(deviceId);
        // 判断当前用户是否有设备分享权限 （设备所属机构管理员和设备所属用户有权限）
        //todo yf
//        LoginUser loginUser = getLoginUser();
//        List<SysRole> roles = loginUser.getUser().getRoles();
//        //判断当前用户是否为设备所属机构管理员
//        if (roles.stream().anyMatch(a -> "admin".equals(a.getRoleKey()))) {
//            device.setIsOwner(1);
//        } else {
//            //判断当前用户是否是设备所属用户
//            if (Objects.equals(device.getTenantId(), loginUser.getUserId())) {
//                device.setIsOwner(1);
//            } else {
//                device.setIsOwner(0);
//            }
//        }
        return success(device);
    }

    @GetMapping("/list")
    @Operation(summary = "获得设备分页")
    @PreAuthorize("@ss.hasPermission('rq:yf-iot-device:query')")
    public CommonResult<PageResult<YfIotDeviceRespVO>> getYfIotDevicePage(@Valid YfIotDevicePageReqVO pageReqVO) {
        PageResult<YfIotDeviceDO> pageResult = yfIotDeviceService.getYfIotDevicePage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, YfIotDeviceRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出设备 Excel")
    @PreAuthorize("@ss.hasPermission('rq:yf-iot-device:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportYfIotDeviceExcel(@Valid YfIotDevicePageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<YfIotDeviceDO> list = yfIotDeviceService.getYfIotDevicePage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "设备.xls", "数据", YfIotDeviceRespVO.class,
                        BeanUtils.toBean(list, YfIotDeviceRespVO.class));
    }

    @GetMapping("/generator")
    @Operation(summary = "生成设备编号")
    public CommonResult<String> generatorDeviceNum(Integer type) {
        return success(yfIotDeviceService.generationDeviceNum(type));
//        return AjaxResult.success(MessageUtils.message("operate.success"), yfIotDeviceService.generationDeviceNum(type));
    }


    @GetMapping("/shortList")
    @Operation(summary = "设备分页简短列表")
    public CommonResult<List<DeviceShortOutput>> shortList(YfIotDeviceSaveReqVO device) {
        if (null == device.getDeptId()) {
            device.setDeptId(SecurityFrameworkUtils.getLoginUserDeptId());
        }
        if (null == device.getShowChild()) {
            device.setShowChild(false);
        }
        List<DeviceShortOutput> deviceShortOutputs = yfIotDeviceService.selectDeviceShortList(device);
        deviceShortOutputs.forEach(e ->{
            DeptRespDTO dept = deptApi.getDept(e.getDeptId());
            if (!Objects.isNull(dept)) {
                e.setDeptName(dept.getName());
            }
            IotDeviceDO iotDevice = iotDeviceService.getIotDevice(e.getPmsDevice());
            if (!Objects.isNull(iotDevice)) {
                e.setDeviceCode(iotDevice.getDeviceCode());
            }
        });
        return success(deviceShortOutputs);
    }
    @DeleteMapping("/{deviceIds}")
    @Operation(summary = "批量删除设备")
    public CommonResult<Boolean> remove(@PathVariable Long[] deviceIds) throws SchedulerException {
        yfIotDeviceService.deleteDeviceByDeviceId(deviceIds[0]);
        return success(true);
    }
}
