package com.ruoyi.models.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

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.models.domain.BizModule;
import com.ruoyi.models.service.IBizModuleService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.project.domain.BizProject;
import com.ruoyi.project.service.IBizProjectService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.service.ISysUserService;

/**
 * 模块Controller
 *
 * @author ruoyi
 * @date 2025-08-28
 */
@RestController
@RequestMapping("/project/module")
public class BizModuleController extends BaseController {
    @Autowired
    private IBizModuleService bizModuleService;
    
    @Autowired
    private ISysUserService userService;

    /**
     * 测试权限接口
     */
    @GetMapping("/testPermission")
    public AjaxResult testPermission() {
        AjaxResult result = new AjaxResult();
        result.put("userId", getUserId());
        result.put("username", getUsername());
        result.put("hasPermission", true);
        return result;
    }

    /**
     * 查询模块列表
     */
    @PreAuthorize("@ss.hasPermi('project:module:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizModule bizModule) {
        startPage();
        List<BizModule> list = bizModuleService.selectBizModuleList(bizModule);
        return getDataTable(list);
    }

    @Autowired
    private IBizProjectService bizProjectService;

    /**
     * 根据项目Id查询模块列表
     */
    @GetMapping("SelectByProjectId")
    public TableDataInfo SelectByProjectId(long projectId) {
        // 使用通用列表查询以复用权限规则：
        // - 平台/项目管理员可见项目下全部模块
        // - 普通用户仅可见自己被指派（designated_user = currentUserId）的模块
        startPage();
        BizModule query = new BizModule();
        query.setProjectId(projectId);
        List<BizModule> list = bizModuleService.selectBizModuleList(query);
        return getDataTable(list);
    }

    /**
     * 导出模块列表
     */
    @PreAuthorize("@ss.hasPermi('project:module:export')")
    @Log(title = "模块", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizModule bizModule) {
        List<BizModule> list = bizModuleService.selectBizModuleList(bizModule);
        ExcelUtil<BizModule> util = new ExcelUtil<BizModule>(BizModule.class);
        util.exportExcel(response, list, "模块数据");
    }

    /**
     * 获取模块详细信息
     */
    @PreAuthorize("@ss.hasPermi('project:module:query')")
    @GetMapping(value = "/{moduleId}")
    public AjaxResult getInfo(@PathVariable("moduleId") Long moduleId) {
        return success(bizModuleService.selectBizModuleByModuleId(moduleId));
    }

    /**
     * 新增模块
     */
    @PreAuthorize("@ss.hasPermi('project:module:add')")
    @Log(title = "模块", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizModule bizModule) {
        // 仅项目管理员可在自己项目下新增模块，且项目状态不能为立项中或已完成
        Long currentUserId = getUserId();
        BizProject project = bizProjectService.selectBizProjectByProjectId(bizModule.getProjectId());
        if (project == null) {
            return AjaxResult.error("项目不存在");
        }
        if (!currentUserId.equals(project.getOwnerId())) {
            return AjaxResult.error("无权在该项目下新增模块");
        }
        // 文档定义：项目状态为立项中或已完成时不可发布新模块
        if ("1".equals(project.getStatus()) || "2".equals(project.getStatus())) {
            return AjaxResult.error("项目状态不允许新增模块");
        }
        // 设置初始状态为待接取
        bizModule.setStatus("0");
        return toAjax(bizModuleService.insertBizModule(bizModule));
    }

    /**
     * 修改模块
     */
    @PreAuthorize("@ss.hasPermi('project:module:edit')")
    @Log(title = "模块", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizModule bizModule) {
        return toAjax(bizModuleService.updateBizModule(bizModule));
    }

    /**
     * 删除模块
     */
    @PreAuthorize("@ss.hasPermi('project:module:remove')")
    @Log(title = "模块", businessType = BusinessType.DELETE)
	@DeleteMapping("/{moduleIds}")
    public AjaxResult remove(@PathVariable Long[] moduleIds) {
        for (Long moduleId : moduleIds) {
            BizModule module = bizModuleService.selectBizModuleByModuleId(moduleId);
            Long currentUserId = getUserId();

            // 检查权限：只有项目管理员可以删除，且只能删除自己项目的模块
            BizProject project = bizProjectService.selectBizProjectByProjectId(module.getProjectId());
            if (!project.getOwnerId().equals(currentUserId)) {
                return AjaxResult.error("无权删除此模块");
            }

            // 检查模块状态：进行中或已完成均不可删除
            if ("1".equals(module.getStatus()) || "2".equals(module.getStatus())) {
                return AjaxResult.error("进行中或已完成的模块无法删除");
            }
        }
        return toAjax(bizModuleService.deleteBizModuleByModuleIds(moduleIds));
    }


    /**
     * 更新model
     * @param bizModule
     * @return
     */
    @PostMapping("/updateModels")
    public AjaxResult updateModels(@RequestBody BizModule bizModule) {
        AjaxResult ajaxResult = new AjaxResult();
        bizModuleService.updateBizModule(bizModule);
        ajaxResult.put("code", 200);
        return ajaxResult;
    }

    /**
     * 指派模块给用户
     */
    @PreAuthorize("@ss.hasPermi('project:module:assign')")
    @Log(title = "模块指派", businessType = BusinessType.UPDATE)
    @PostMapping("/assign")
    public AjaxResult assignModule(@RequestBody BizModule bizModule) {
        // 仅项目管理员可指派自己项目的模块，且模块必须处于待接取，项目状态不可为立项中/已完成
        if (bizModule.getProjectId() == null || bizModule.getModuleId() == null) {
            return AjaxResult.error("缺少必要的项目或模块信息");
        }
        Long currentUserId = getUserId();
        BizProject project = bizProjectService.selectBizProjectByProjectId(bizModule.getProjectId());
        if (project == null) {
            return AjaxResult.error("项目不存在");
        }
        if (!currentUserId.equals(project.getOwnerId())) {
            return AjaxResult.error("无权指派该项目的模块");
        }
        if ("1".equals(project.getStatus()) || "2".equals(project.getStatus())) {
            return AjaxResult.error("项目状态不允许指派模块");
        }
        BizModule current = bizModuleService.selectBizModuleByModuleId(bizModule.getModuleId());
        if (current == null) {
            return AjaxResult.error("模块不存在");
        }
        if (!"0".equals(current.getStatus())) {
            return AjaxResult.error("仅可指派待接取的模块");
        }
        // 前端传递的是用户名，需要转换为用户ID
        if (bizModule.getAssignee() != null && !bizModule.getAssignee().isEmpty()) {
            try {
                // 先尝试解析为数字（用户ID）
                Long userId = Long.parseLong(bizModule.getAssignee());
                bizModule.setDesignatedUser(userId);
            } catch (NumberFormatException e) {
                // 如果不是数字，说明是用户名，需要查询用户ID
                SysUser user = userService.selectUserByUserName(bizModule.getAssignee());
                if (user != null) {
                    bizModule.setDesignatedUser(user.getUserId());
                } else {
                    return AjaxResult.error("用户不存在");
                }
            }
        }
        return toAjax(bizModuleService.assignModule(bizModule));
    }

    /**
     * 用户接取模块
     */
    @PreAuthorize("@ss.hasPermi('project:module:claim')")
    @Log(title = "模块接取", businessType = BusinessType.UPDATE)
    @PostMapping("/receive/{moduleId}")
    public AjaxResult receiveModule(@PathVariable Long moduleId) {
        return toAjax(bizModuleService.receiveModule(moduleId, getUserId()));
    }

    /**
     * 用户放弃模块
     */
    @PreAuthorize("@ss.hasPermi('project:module:giveup')")
    @Log(title = "模块放弃", businessType = BusinessType.UPDATE)
    @PostMapping("/abandon/{moduleId}")
    public AjaxResult abandonModule(@PathVariable Long moduleId) {
        return toAjax(bizModuleService.abandonModule(moduleId, getUserId()));
    }

    /**
     * 用户完成模块
     */
    @PreAuthorize("@ss.hasPermi('project:module:complete')")
    @Log(title = "模块完成", businessType = BusinessType.UPDATE)
    @PostMapping("/complete/{moduleId}")
    public AjaxResult completeModule(@PathVariable Long moduleId) {
        return toAjax(bizModuleService.completeModule(moduleId, getUserId()));
    }

    /**
     * 查询用户可接取的模块列表
     */
    @PreAuthorize("@ss.hasPermi('project:module:list')")
    @GetMapping("/assignedList")
    public TableDataInfo assignedList(BizModule bizModule) {
        startPage();
        List<BizModule> list = bizModuleService.selectAssignedModules(getUserId());
        return getDataTable(list);
    }
}
