package com.ruoyi.models.controller;

import java.util.List;
import java.util.Map;
import java.util.HashMap;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.models.domain.BizSubModule;
import com.ruoyi.models.domain.BizModule;
import com.ruoyi.models.service.IBizSubModuleService;
import com.ruoyi.models.service.IBizModuleService;
import com.ruoyi.project.service.IBizProjectService;

/**
 * 子模块Controller
 */
@RestController
@RequestMapping("/project/submodule")
public class BizSubModuleController extends BaseController
{
    @Autowired
    private IBizSubModuleService subService;

    @Autowired
    private IBizModuleService moduleService;

    @Autowired
    private IBizProjectService projectService;

    /**
     * 查询子模块列表（按条件）
     */
    @PreAuthorize("@ss.hasPermi('project:module:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizSubModule subModule)
    {
        startPage();
        List<BizSubModule> list = subService.selectBizSubModuleList(subModule);
        return getDataTable(list);
    }

    /**
     * 按模块ID查询子模块
     */
    @PreAuthorize("@ss.hasPermi('project:module:list')")
    @GetMapping("/byModule/{moduleId}")
    public TableDataInfo listByModule(@PathVariable Long moduleId)
    {
        startPage();
        List<BizSubModule> list = subService.selectByModuleId(moduleId);
        return getDataTable(list);
    }

    /** 获取详情 */
    @PreAuthorize("@ss.hasPermi('project:module:query')")
    @GetMapping(value = "/{subId}")
    public AjaxResult getInfo(@PathVariable("subId") Long subId)
    {
        return success(subService.selectBizSubModuleBySubId(subId));
    }

    /** 新增子模块（仅父模块接取人，且父模块需处于进行中）*/
    @PreAuthorize("@ss.hasPermi('project:module:add')")
    @Log(title = "子模块", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizSubModule subModule)
    {
        if (subModule.getModuleId() == null)
        {
            return AjaxResult.error("缺少所属模块");
        }
        BizModule module = moduleService.selectBizModuleByModuleId(subModule.getModuleId());
        if (module == null)
        {
            return AjaxResult.error("父模块不存在");
        }
        // 仅模块接取人可新增子模块
        if (!String.valueOf(getUserId()).equals(module.getAssignee()))
        {
            return AjaxResult.error("仅接取人可在该模块下新增子模块");
        }
        // 父模块需处于进行中
        if (!"1".equals(module.getStatus()))
        {
            return AjaxResult.error("父模块未处于进行中，无法新增子模块");
        }
        subModule.setStatus("0");
        return toAjax(subService.insertBizSubModule(subModule));
    }

    /** 修改子模块（仅模块接取人） */
    @PreAuthorize("@ss.hasPermi('project:module:edit')")
    @Log(title = "子模块", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizSubModule subModule)
    {
        BizSubModule current = subService.selectBizSubModuleBySubId(subModule.getSubId());
        if (current == null)
        {
            return AjaxResult.error("子模块不存在");
        }
        BizModule module = moduleService.selectBizModuleByModuleId(current.getModuleId());
        if (!String.valueOf(getUserId()).equals(module.getAssignee()))
        {
            return AjaxResult.error("仅接取人可修改子模块");
        }
        return toAjax(subService.updateBizSubModule(subModule));
    }

    /** 删除子模块（软删除，且仅模块接取人，有状态限制：非进行中/已完成可删或随需） */
    @PreAuthorize("@ss.hasPermi('project:module:remove')")
    @Log(title = "子模块", businessType = BusinessType.DELETE)
    @DeleteMapping("/{subIds}")
    public AjaxResult remove(@PathVariable Long[] subIds)
    {
        for (Long subId : subIds)
        {
            BizSubModule sub = subService.selectBizSubModuleBySubId(subId);
            if (sub == null)
            {
                return AjaxResult.error("子模块不存在");
            }
            BizModule module = moduleService.selectBizModuleByModuleId(sub.getModuleId());
            if (!String.valueOf(getUserId()).equals(module.getAssignee()))
            {
                return AjaxResult.error("仅接取人可删除子模块");
            }
        }
        return toAjax(subService.deleteBizSubModuleBySubIds(subIds));
    }

    /** 接取子模块（仅模块接取人） */
    @PreAuthorize("@ss.hasPermi('project:module:claim')")
    @Log(title = "子模块接取", businessType = BusinessType.UPDATE)
    @PostMapping("/receive/{subId}")
    public AjaxResult receive(@PathVariable Long subId)
    {
        return toAjax(subService.receiveSubModule(subId, getUserId()));
    }

    /** 完成子模块（仅模块接取人） */
    @PreAuthorize("@ss.hasPermi('project:module:complete')")
    @Log(title = "子模块完成", businessType = BusinessType.UPDATE)
    @PostMapping("/complete/{subId}")
    public AjaxResult complete(@PathVariable Long subId)
    {
        return toAjax(subService.completeSubModule(subId, getUserId()));
    }

    /**
     * 管理员或项目管理员：查看项目下模块及其子模块
     */
    @PreAuthorize("@ss.hasPermi('project:module:list')")
    @GetMapping("/treeByProject/{projectId}")
    public AjaxResult treeByProject(@PathVariable Long projectId)
    {
        com.ruoyi.project.domain.BizProject project = projectService.selectBizProjectByProjectId(projectId);
        if (project == null)
        {
            return AjaxResult.error("项目不存在");
        }
        Long currentUserId = getUserId();
        boolean isOwner = project.getOwnerId() != null && project.getOwnerId().equals(currentUserId);
        boolean isAdmin = com.ruoyi.common.utils.SecurityUtils.isAdmin(currentUserId);
        if (!isOwner && !isAdmin)
        {
            return AjaxResult.error("无权查看该项目结构");
        }

        com.ruoyi.models.domain.BizModule query = new com.ruoyi.models.domain.BizModule();
        query.setProjectId(projectId);
        List<com.ruoyi.models.domain.BizModule> modules = moduleService.selectBizModuleList(query);
        java.util.List<java.util.Map<String, Object>> result = new java.util.ArrayList<>();
        for (com.ruoyi.models.domain.BizModule m : modules)
        {
            Map<String, Object> item = new HashMap<>();
            item.put("module", m);
            item.put("subModules", subService.selectByModuleId(m.getModuleId()));
            result.add(item);
        }
        return AjaxResult.success(result);
    }
}


