package com.ruoyi.web.base.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.web.base.domain.BaseMaterial;
import com.ruoyi.web.base.domain.BaseProductCategory;
import com.ruoyi.web.base.service.IBaseMaterialService;
import com.ruoyi.web.base.service.IBaseProductCategoryService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

import static com.ruoyi.common.core.domain.AjaxResult.error;
import static com.ruoyi.common.core.domain.AjaxResult.success;
import static com.ruoyi.common.utils.SecurityUtils.getUsername;

/**
 * <p>
 * 货品类别 前端控制器
 * </p>
 *
 * @author author
 * @since 2026-02-04
 */
@RestController
@RequestMapping("/base-product-category")
public class BaseProductCategoryController {
    @Autowired
    private IBaseProductCategoryService baseProductCategoryService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private IBaseMaterialService baseMaterialService;

    @ApiOperation("货品类别管理添加")
    @PostMapping("/add")
    public AjaxResult add(@RequestBody BaseProductCategory baseProductCategory, HttpServletRequest request) throws Exception {
        String loginOrgId = tokenService.getLoginOrgId(request);
        if (baseProductCategoryService.count(new QueryWrapper<BaseProductCategory>().eq("org_id",loginOrgId).eq("num", baseProductCategory.getNum())) >0 ){
            throw new Exception("该编号已存在");
        }
        baseProductCategory.setOrgId(loginOrgId);
        baseProductCategory.setCreateBy(getUsername());

        return success(baseProductCategoryService.save(baseProductCategory));
    }

    @ApiOperation("货品类别管理修改")
    @PostMapping("/edit")
    public AjaxResult edit(@RequestBody BaseProductCategory baseProductCategory, HttpServletRequest request) throws Exception {
        String loginOrgId = tokenService.getLoginOrgId(request);
        if (baseProductCategoryService.count(new QueryWrapper<BaseProductCategory>().ne("id",baseProductCategory.getId()).eq("org_id",loginOrgId).eq("num", baseProductCategory.getNum())) >0 ){
            throw new Exception("该编号已存在");
        }
        baseProductCategory.setUpdateBy(getUsername());
        return success(baseProductCategoryService.updateById(baseProductCategory));
    }

    @ApiOperation("货品类别管理删除")
    @PostMapping("/delete")
    public AjaxResult delete(@RequestBody Map<String, String> paramsMap) {
        String ids = paramsMap.get("ids");
        for (String s : ids.split(",")) {
            baseProductCategoryService.removeById(s);
        }
        return success();
    }

    @ApiOperation("货品类别管理列表")
    @PostMapping("/list")
    public AjaxResult listAll( HttpServletRequest request){

        return success(baseProductCategoryService.list(new QueryWrapper<BaseProductCategory>().eq("org_id", tokenService.getLoginOrgId(request))));
    }

    @ApiOperation("货品类别管理分页")
    @GetMapping("/page")
    public AjaxResult page(@RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize
            , HttpServletRequest request) {
        return success(baseProductCategoryService.page(new Page<BaseProductCategory>(pageNum,pageSize),new QueryWrapper<BaseProductCategory>().eq("org_id", tokenService.getLoginOrgId(request))));
    }

    @ApiOperation("货品类别管理详情")
    @PostMapping("/listById")
    public AjaxResult listById(@RequestBody Map<String, String> paramsMap){
        String id = paramsMap.get("id");
        return success(baseProductCategoryService.getById(id));
    }

    @ApiOperation("货品类别结构")
    @PostMapping("/productStructure")
    @Transactional
    public AjaxResult productStructure(@RequestBody Map<String, String> paramsMap){
        String parentId = paramsMap.get("parentId");
        String ids = paramsMap.get("ids");
        if (StringUtils.isNotEmpty(parentId) && StringUtils.isNotEmpty(ids)){
            String[] split = ids.split(",");
            BaseProductCategory baseProductCategory = new BaseProductCategory();
            baseProductCategory.setParentId(Integer.parseInt(parentId));
            baseProductCategoryService.update(baseProductCategory ,new UpdateWrapper<BaseProductCategory>().in("id", split));

            return success();
        }
        return error("请传入编号");
    }

    @ApiOperation("树状货品类别管理列表")
    @PostMapping("/listTree")
    public AjaxResult listTree( HttpServletRequest request){
        List<BaseProductCategory> productCategories = baseProductCategoryService.list(new QueryWrapper<BaseProductCategory>().eq("org_id", tokenService.getLoginOrgId(request)));

        return success(buildTree(productCategories,0));
    }

    @ApiOperation("根据类别获取全部物料")
    @PostMapping("/listMaterialByGoodsType")
    public AjaxResult listAll( @RequestBody Map<String, String> paramsMap,HttpServletRequest request){
        String goodsType = paramsMap.get("goodsType");

        if (StringUtils.isEmpty(goodsType)){
            return success(baseMaterialService.list(new QueryWrapper<BaseMaterial>().eq("org_id", tokenService.getLoginOrgId(request))));
        }else {
            List<BaseProductCategory> productCategories = baseProductCategoryService.list(new QueryWrapper<BaseProductCategory>().eq("org_id", tokenService.getLoginOrgId(request)));
            BaseProductCategory num = baseProductCategoryService.getOne(new QueryWrapper<BaseProductCategory>().eq("num", goodsType));
            List<BaseProductCategory> productCategories1 = buildTree(productCategories, num.getId());
            List<String> collect = productCategories1.stream().map(BaseProductCategory::getNum).collect(Collectors.toList());
            collect.add(goodsType);

            return success(baseMaterialService
                    .list(new QueryWrapper<BaseMaterial>().eq("org_id", tokenService.getLoginOrgId(request))
                            .in("goods_type",collect)));


        }


    }


    public List<BaseProductCategory> buildTree(List<BaseProductCategory> nodes, Integer maxId ) {
        // 1. 创建ID到节点的映射
        Map<Integer, BaseProductCategory> nodeMap = new HashMap<>();
        for (BaseProductCategory node : nodes) {
            nodeMap.put(node.getId(), node);
        }

        List<BaseProductCategory> roots = new ArrayList<>();
        // 2. 构建父子关系
        for (BaseProductCategory node : nodes) {
            Integer parentId = node.getParentId();
            if (parentId.equals(maxId)) {
                roots.add(node); // 顶级节点直接加入根列表
            } else {
                BaseProductCategory parent = nodeMap.get(parentId);
                if (parent != null) {
                    if (parent.getChild() != null){
                        parent.getChild().add(node);
                    }else {
                        List<BaseProductCategory> list= new ArrayList<BaseProductCategory>();
                        list.add(node);
                        parent.setChild(list);
                    }


                } else {
                    // 处理无效parentId：可抛异常或作为根节点

//                    roots.add(node);
                }
            }
        }
        return roots;
    }

}
