package io.gisbi.application.module.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.gisbi.application.module.domain.Module;
import io.gisbi.application.module.service.IModuleService;
import io.gisbi.config.ResponseResult;
import io.gisbi.utils.AuthUtils;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 应用_系统模块 前端控制器
 * </p>
 *
 * @author zhengsl
 * @since 2025-03-25
 */
@RestController
@RequestMapping("/application/module")
public class ModuleController {

    // 添加Service注入
    @Resource
    private IModuleService moduleService;

    // 分页查询模块列表
    @GetMapping("/list")
    public ResponseResult page(@RequestParam String appId) {
        QueryWrapper<Module> wrapper = new QueryWrapper<>();
        wrapper.eq("app_id", appId);
        wrapper.orderByAsc("pid", "sort"); // 按编码倒序排列
        List<Map<String, Object>> list = moduleService.listMaps(wrapper);
        return ResponseResult.successData(list);
    }

    // 新增模块
    @PostMapping("/save")
    public ResponseResult save(@RequestBody Module module) {
        module.setCreateTime(LocalDateTime.now());
        module.setCreateBy(AuthUtils.getUser().getUserId().toString());
        return ResponseResult.successData(moduleService.createModule(module));
    }

    // 复制模块
    @PostMapping("/copy/{id}")
    public ResponseResult copy(@PathVariable String id) {
        LambdaQueryWrapper<Module> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Module::getId, id);
        Map<String, Object> moduleMap = moduleService.getMap(wrapper);

        if (moduleMap == null || moduleMap.isEmpty()) {
            return ResponseResult.error("模块不存在");
        }

        try {
            Module module = BeanUtil.toBean(moduleMap, Module.class);
            module.setId(null);
            module.setName(module.getName() + "(复制)");
            module.setCreateTime(LocalDateTime.now());
            module.setCreateBy(AuthUtils.getUser().getUserId().toString());

            boolean result = moduleService.createModule(module);
            if (result) {
                return ResponseResult.success("模块复制成功");
            } else {
                return ResponseResult.error("模块复制失败");
            }
        } catch (Exception e) {
            return ResponseResult.error("复制模块失败，请联系管理员");
        }
    }

    // 修改模块
    @PostMapping("/update")
    public ResponseResult update(@RequestBody Module module) {
        return ResponseResult.successData(moduleService.updateById(module));
    }

    // 删除模块
    @DeleteMapping("/{id}")
    public ResponseResult remove(@PathVariable String id) {
        return ResponseResult.successData(moduleService.removeById(id));
    }

    // 获取模块详情
    @GetMapping("/{id}")
    public ResponseResult getById(@PathVariable String id) {
        Map<String, Object> moduleMap = null;
        try {
            LambdaQueryWrapper<Module> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Module::getId, id);
            moduleMap = moduleService.getMap(wrapper);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.successData(moduleMap);
    }

    // 新增：根据pid判断是否有子节点
    @GetMapping("/checkHasChildren")
    public boolean checkHasChildren(@RequestParam String appId, @RequestParam String pid) {
        boolean hasChildren = moduleService.existsChildrenByPid(appId, pid);
        return hasChildren;
    }
}
