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

import cn.hutool.core.collection.CollUtil;
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.pms.controller.admin.vo.IotTreeListReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.vo.IotTreePageReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.vo.IotTreeRespVO;
import cn.iocoder.yudao.module.pms.controller.admin.vo.IotTreeSaveReqVO;
import cn.iocoder.yudao.module.pms.dal.dataobject.IotTreeDO;
import cn.iocoder.yudao.module.pms.service.IotTreeService;
import cn.iocoder.yudao.module.system.controller.admin.dept.vo.dept.DeptSimpleRespVO;
import cn.iocoder.yudao.module.system.dal.dataobject.dept.DeptDO;
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.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

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


@Tag(name = "管理后台 - pms树")
@RestController
@RequestMapping("/rq/iot-tree")
@Validated
public class IotTreeController {

    @Resource
    private IotTreeService iotTreeService;

    @PostMapping("/create")
    @Operation(summary = "创建pms树")
    @PreAuthorize("@ss.hasPermission('rq:iot-tree:create')")
    public CommonResult<Long> createIotTree(@Valid @RequestBody IotTreeSaveReqVO createReqVO) {
        return success(iotTreeService.createIotTree(createReqVO));
    }

    @PostMapping("/add-dept-deal")
    public void createDeptDeal(@RequestBody DeptDO dept) {
        iotTreeService.addDeptDeal(dept);
    }
    @PostMapping("/update-dept-deal")
    public void updateDeptDeal(@RequestBody DeptDO dept) {
        iotTreeService.updateDeptDeal(dept);
    }
    @PostMapping("/delete-dept-deal")
    public void updateDeptDeal(String id) {
        iotTreeService.deleteDeptDeal(id);
    }
    @PutMapping("/update")
    @Operation(summary = "更新pms树")
    @PreAuthorize("@ss.hasPermission('rq:iot-tree:update')")
    public CommonResult<Boolean> updateIotTree(@Valid @RequestBody IotTreeSaveReqVO updateReqVO) {
        iotTreeService.updateIotTree(updateReqVO);
        return success(true);
    }


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

    @GetMapping("/get")
    @Operation(summary = "获得pms树")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('rq:iot-tree:query')")
    public CommonResult<IotTreeRespVO> getIotTree(@RequestParam("id") Long id) {
        IotTreeDO iotTree = iotTreeService.getIotTree(id);
        return success(BeanUtils.toBean(iotTree, IotTreeRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得pms树分页")
    @PreAuthorize("@ss.hasPermission('rq:iot-tree:query')")
    public CommonResult<PageResult<IotTreeRespVO>> getIotTreePage(@Valid IotTreePageReqVO pageReqVO) {
        PageResult<IotTreeDO> pageResult = iotTreeService.getIotTreePage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, IotTreeRespVO.class));
    }

    @GetMapping(value = {"/list-all-simple", "/simple-list"})
    @Operation(summary = "获取部门精简信息列表", description = "只包含被开启的部门，主要用于前端的下拉选项")
    @PermitAll
    public CommonResult<List<DeptSimpleRespVO>> getSimpleDeptList() {
        List<IotTreeDO> list = iotTreeService.getIotTreeList(new IotTreeListReqVO());
        return success(BeanUtils.toBean(list, DeptSimpleRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出pms树 Excel")
    @PreAuthorize("@ss.hasPermission('rq:iot-tree:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportIotTreeExcel(@Valid IotTreePageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<IotTreeDO> list = iotTreeService.getIotTreePage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "pms树.xls", "数据", IotTreeRespVO.class,
                        BeanUtils.toBean(list, IotTreeRespVO.class));
    }

    @GetMapping("/init/tree")
    @PermitAll
    public void initTree() {
        iotTreeService.initTree();
    }


    @GetMapping("/ids/{id}")
    @Operation(summary = "获取某个节点的所有上级节点")
    public CommonResult<LinkedList<Map<String, Object>>> getTreeIds(@PathVariable("id") Long id) {
        List<IotTreeDO> allParentIds = iotTreeService.getAllParentIds(id);
        LinkedList<Map<String, Object>> list = new LinkedList<>();
        allParentIds.forEach(e -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", e.getId());
            map.put("name", e.getName());
            if (e.getName().contains("科瑞石油技术")) {
                map.put("type", "root");
            }
            list.add(map);
        });
        IotTreeDO iotTree = iotTreeService.getIotTree(id);
        Map<String, Object> map = new HashMap<>();
        map.put("id", iotTree.getId());
        map.put("name", iotTree.getName());
        if (iotTree.getName().contains("科瑞石油技术")){
            map.put("type", "root");
        }
        list.add(map);
        return success(list);
    }

    @GetMapping("/device/{id}")
    @PreAuthorize("@ss.hasPermission('rq:iot-tree:query')")
    public CommonResult<Long> getDeviceTree(@PathVariable("id") Long deviceId) {
        List<IotTreeDO> iotDeviceTree = iotTreeService.getIotDeviceTree(deviceId);
        if (CollUtil.isEmpty(iotDeviceTree)) {
            return success(null);
        }
        return success(iotDeviceTree.get(0).getId());
    }

    @GetMapping("/init/code")
    @PermitAll
    public void initTreeCode() {
        iotTreeService.initTreeCode();
    }



}
