package com.sundot.airport.web.controller.system;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.collection.CollUtil;
import com.sundot.airport.system.domain.vo.CheckProjectItemTreeVo;
import com.sundot.airport.system.domain.vo.CheckProjectItemVo;
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.sundot.airport.common.annotation.Log;
import com.sundot.airport.common.core.controller.BaseController;
import com.sundot.airport.common.core.domain.AjaxResult;
import com.sundot.airport.common.enums.BusinessType;
import com.sundot.airport.system.domain.BaseProject;
import com.sundot.airport.system.service.IBaseProjectService;
import com.sundot.airport.common.utils.poi.ExcelUtil;
import com.sundot.airport.common.core.page.TableDataInfo;

/**
 * 检查项目Controller
 *
 * @author ruoyi
 * @date 2025-07-11
 */
@RestController
@RequestMapping("/system/project")
public class BaseProjectController extends BaseController {
    @Autowired
    private IBaseProjectService baseProjectService;

    /**
     * 查询检查项目列表
     */
    @PreAuthorize("@ss.hasPermi('system:project:list')")
    @GetMapping("/list")
    public TableDataInfo list(BaseProject baseProject) {
        startPage();
        List<BaseProject> list = baseProjectService.selectBaseProjectList(baseProject);
        return getDataTable(list);
    }

    /**
     * 导出检查项目列表
     */
    @PreAuthorize("@ss.hasPermi('system:project:export')")
    @Log(title = "检查项目", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BaseProject baseProject) {
        List<BaseProject> list = baseProjectService.selectBaseProjectList(baseProject);
        ExcelUtil<BaseProject> util = new ExcelUtil<BaseProject>(BaseProject.class);
        util.exportExcel(response, list, "检查项目数据");
    }

    /**
     * 获取检查项目详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:project:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(baseProjectService.selectBaseProjectById(id));
    }

    /**
     * 新增检查项目
     */
    @PreAuthorize("@ss.hasPermi('system:project:add')")
    @Log(title = "检查项目", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BaseProject baseProject) {
        baseProject.setCreateBy(getUsername());
        return toAjax(baseProjectService.insertBaseProject(baseProject));
    }

    /**
     * 修改检查项目
     */
    @PreAuthorize("@ss.hasPermi('system:project:edit')")
    @Log(title = "检查项目", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BaseProject baseProject) {
        baseProject.setUpdateBy(getUsername());
        return toAjax(baseProjectService.updateBaseProject(baseProject));
    }

    /**
     * 删除检查项目
     */
    @PreAuthorize("@ss.hasPermi('system:project:remove')")
    @Log(title = "检查项目", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(baseProjectService.deleteBaseProjectByIds(ids));
    }

    /**
     * 根据分类编码查询检查项目列表
     */
    @PreAuthorize("@ss.hasPermi('system:project:list')")
    @GetMapping(value = "/list/{categoryCode}")
    public AjaxResult list(@PathVariable("categoryCode") String categoryCode) {
        return success(baseProjectService.selectProjectListByCategoryCode(categoryCode));
    }

    /**
     * 根据检查级别查询检查项目列表
     */
    @PreAuthorize("@ss.hasPermi('system:project:list')")
    @GetMapping(value = "/listByCheckLevel/{checkLevel}")
    public AjaxResult listByCheckedLevel(@PathVariable("checkLevel") String checkLevel) {
        List<CheckProjectItemVo> result = baseProjectService.listByCheckLevel(checkLevel);
        return success(convertToTree(result));
    }

    /**
     * 转换为树形结构
     */
    public List<CheckProjectItemTreeVo> convertToTree(List<CheckProjectItemVo> itemList) {
        if (CollUtil.isEmpty(itemList)) {
            return Collections.emptyList();
        }
        List<CheckProjectItemTreeVo> result = new ArrayList<>();

        // 第一层分组：按一级分类
        Map<String, List<CheckProjectItemVo>> levelOneMap = itemList.stream()
                .collect(Collectors.groupingBy(CheckProjectItemVo::getCategoryCodeOne));


        // 处理一级分类
        for (Map.Entry<String, List<CheckProjectItemVo>> levelOneEntry : levelOneMap.entrySet()) {
            String levelOneCode = levelOneEntry.getKey();
            List<CheckProjectItemVo> levelOneItems = levelOneEntry.getValue();

            // 获取一级分类名称（取第一个元素的名称）
            String levelOneName = levelOneItems.get(0).getCategoryNameOne();

            // 创建一级节点
            CheckProjectItemTreeVo levelOneNode = new CheckProjectItemTreeVo();
            levelOneNode.setCode(levelOneCode);
            levelOneNode.setName(levelOneName);

            // 第二层分组：按二级分类
            Map<String, List<CheckProjectItemVo>> levelTwoMap = levelOneItems.stream()
                    .collect(Collectors.groupingBy(CheckProjectItemVo::getCategoryCodeTwo));

            List<CheckProjectItemTreeVo> levelTwoNodes = new ArrayList<>();

            // 处理二级分类
            for (Map.Entry<String, List<CheckProjectItemVo>> levelTwoEntry : levelTwoMap.entrySet()) {
                String levelTwoCode = levelTwoEntry.getKey();
                List<CheckProjectItemVo> levelTwoItems = levelTwoEntry.getValue();

                // 获取二级分类名称（取第一个元素的名称）
                String levelTwoName = levelTwoItems.get(0).getCategoryNameTwo();

                // 创建二级节点
                CheckProjectItemTreeVo levelTwoNode = new CheckProjectItemTreeVo();
                levelTwoNode.setCode(levelTwoCode);
                levelTwoNode.setName(levelTwoName);

                // 处理检查项目
                List<CheckProjectItemTreeVo> projectNodes = levelTwoItems.stream()
                        .map(item -> {
                            CheckProjectItemTreeVo projectNode = new CheckProjectItemTreeVo();
                            projectNode.setCode(item.getProjectCode());
                            projectNode.setName(item.getProjectName());
                            projectNode.setList(null); // 项目没有子节点
                            return projectNode;
                        })
                        .collect(Collectors.toList());

                levelTwoNode.setList(projectNodes);
                levelTwoNodes.add(levelTwoNode);
            }

            levelOneNode.setList(levelTwoNodes);
            result.add(levelOneNode);
        }
        return result;
    }

}
