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

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.vo.IotInfoPageReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.vo.IotInfoRespVO;
import cn.iocoder.yudao.module.pms.controller.admin.vo.IotInfoSaveReqVO;
import cn.iocoder.yudao.module.pms.dal.dataobject.IotDeviceDO;
import cn.iocoder.yudao.module.pms.dal.dataobject.IotInfoDO;
import cn.iocoder.yudao.module.pms.service.IotDeviceService;
import cn.iocoder.yudao.module.pms.service.IotInfoService;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO;
import com.xingyuv.captcha.util.StringUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
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 java.util.stream.Collectors;

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/iot-info")
@Validated
public class IotInfoController {

    @Resource
    private IotInfoService iotInfoService;
    @Autowired
    private IotDeviceService iotDeviceService;
    @Autowired
    private DeptApi deptApi;

    @PostMapping("/create")
    @Operation(summary = "创建资料")
    @PreAuthorize("@ss.hasPermission('rq:iot-info:create')")
    public CommonResult<Boolean> createIotInfo(@Valid @RequestBody IotInfoSaveReqVO createReqVO) {
        iotInfoService.createIotInfo(createReqVO);
        return success(true);
    }

    @PutMapping("/update")
    @Operation(summary = "更新资料")
    @PreAuthorize("@ss.hasPermission('rq:iot-info:update')")
    public CommonResult<Boolean> updateIotInfo(@Valid @RequestBody IotInfoSaveReqVO updateReqVO) {
        iotInfoService.updateIotInfo(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除资料")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('rq:iot-info:delete')")
    public CommonResult<Boolean> deleteIotInfo(@RequestParam("id") Long id) {
        iotInfoService.deleteIotInfo(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得资料")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('rq:iot-info:query')")
    public CommonResult<IotInfoRespVO> getIotInfo(@RequestParam("id") Long id) {
        IotInfoDO iotInfo = iotInfoService.getIotInfo(id);
        return success(BeanUtils.toBean(iotInfo, IotInfoRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得资料分页")
    @PreAuthorize("@ss.hasPermission('rq:iot-info:query')")
    public CommonResult<PageResult<IotInfoRespVO>> getIotInfoPage(@Valid IotInfoPageReqVO pageReqVO) {
//        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
//        pageReqVO.setCreator(String.valueOf(loginUserId));
        PageResult<IotInfoDO> pageResult = iotInfoService.getIotInfoPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, IotInfoRespVO.class));
    }

    @PostMapping("/file/page")
    @Operation(summary = "获得资料分页")
    @PreAuthorize("@ss.hasPermission('rq:iot-info:query')")
    public CommonResult<PageResult<IotInfoRespVO>> getIotInfoFilePage(@Valid IotInfoPageReqVO pageReqVO) {
        PageResult<IotInfoDO> pageResult = iotInfoService.getIotInfoFilePage(pageReqVO);
        List<IotInfoDO> list = pageResult.getList();
        List<IotInfoRespVO> collect = list.stream().map(e -> {
            IotInfoRespVO vo = BeanUtils.toBean(e, IotInfoRespVO.class);
            if (Objects.nonNull(e.getDeviceId())) {
                IotDeviceDO iotDevice = iotDeviceService.getIotDevice(e.getDeviceId());
                if (Objects.nonNull(iotDevice)) {
                    vo.setDeviceCode(iotDevice.getDeviceCode());
                }
            }
            if (Objects.nonNull(e.getDeptId())) {
                DeptRespDTO dept = deptApi.getDept(e.getDeptId());
                if (Objects.nonNull(dept)) {
                    vo.setDeptName(dept.getName());
                }
            }
            return vo;
        }).collect(Collectors.toList());
        return success(new PageResult<>(collect, pageResult.getTotal()));
    }

    @PostMapping("/child/content-file")
    @Operation(summary = "获得资料库的分类目录及文件")
    @PreAuthorize("@ss.hasPermission('rq:iot-info:query')")
    public CommonResult<List<IotInfoRespVO>> getChildContentFile(@Valid IotInfoPageReqVO pageReqVO) {
        Long classId = pageReqVO.getClassId();
        List<IotInfoRespVO> contentFiles = iotInfoService.getChildContentFile(classId).stream().filter(e ->{
            if (StringUtils.isNotBlank(pageReqVO.getFilename())) {
                return e.getFilename().contains(pageReqVO.getFilename());
            } else {
                return true;
            }
        }).collect(Collectors.toList());
        return success(contentFiles);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出资料 Excel")
    @PreAuthorize("@ss.hasPermission('rq:iot-info:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportIotInfoExcel(@Valid IotInfoPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<IotInfoDO> list = iotInfoService.getIotInfoPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "资料.xls", "数据", IotInfoRespVO.class,
                        BeanUtils.toBean(list, IotInfoRespVO.class));
    }

    @PostMapping("/all/content-file")
    @Operation(summary = "获得资料库下的所有分类目录及文件")
    @PreAuthorize("@ss.hasPermission('rq:iot-info:query')")
    public CommonResult<List<IotInfoRespVO>> getAllContentFile(@Valid IotInfoPageReqVO pageReqVO) {
        Long classId = pageReqVO.getClassId();
        List<IotInfoRespVO> contentFiles = iotInfoService.getAllChildContentFile(classId).stream().filter(e ->{
            if (StringUtils.isNotBlank(pageReqVO.getAllName())) {
                return e.getFilename().contains(pageReqVO.getAllName());
            } else {
                return true;
            }
        }).collect(Collectors.toList());
        return success(contentFiles);
    }

}
