/*
 * Copyright [2022] [https://www.baiduc.com]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.baiduc.com
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.baiduc.com
 */
package vip.xiaonuo.sale.controller;


import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import vip.xiaonuo.common.pojo.CommonResult;
import vip.xiaonuo.common.pojo.CommonValidList;
import vip.xiaonuo.sale.entity.ErpBaseMaterial;
import vip.xiaonuo.sale.param.*;
import vip.xiaonuo.sale.service.ErpBaseMaterialService;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * erp_base_material控制器
 *
 * @author 1
 * @date  2025/02/18 13:54
 */
@Api(tags = "erp_base_material控制器")
@ApiSupport(author = "SNOWY_TEAM", order = 1)
@RestController
@Validated
public class ErpBaseMaterialController {

    @Resource
    private ErpBaseMaterialService erpBaseMaterialService;
    @Autowired
    private RestTemplate restTemplate;
    /**
     * 获取erp_base_material分页
     *
     * @author 1
     * @date  2025/02/18 13:54
     */
    @ApiOperationSupport(order = 1)
    @ApiOperation("获取erp_base_material分页")
    @PostMapping("/huimv-farm/basematerial/page")
    public CommonResult<Page<ErpBaseMaterial>> page(@RequestBody ErpBaseMaterialPageParam erpBaseMaterialPageParam) {
        return CommonResult.data(erpBaseMaterialService.page(erpBaseMaterialPageParam));
    }


    /**
     * 添加erp_base_material
     *
     * @author 1
     * @date  2025/02/18 13:54
     */
    @ApiOperationSupport(order = 2)
    @ApiOperation("添加erp_base_material")
    @PostMapping("/huimv-farm/basematerial/add")
    public CommonResult<String> add(@RequestBody @Valid ErpBaseMaterialAddParam erpBaseMaterialAddParam) {
        return erpBaseMaterialService.add(erpBaseMaterialAddParam);

    }
    @ApiOperationSupport(order = 1)
    @ApiOperation("根据id查询下级列表")
    @PostMapping("/huimv-farm/basematerial/listByParten")
    public CommonResult<List<ErpBaseMaterial>> listByParten(@RequestBody ErpBaseMaterialEditParam erpBaseMaterialPageParam) {
        List<ErpBaseMaterial> parentId = erpBaseMaterialService.list(new QueryWrapper<ErpBaseMaterial>().eq(StringUtils.isNotBlank(erpBaseMaterialPageParam.getOrgId()),"org_id",erpBaseMaterialPageParam.getOrgId()).eq("parent_id", erpBaseMaterialPageParam.getId()));
        return CommonResult.data(parentId);
    }

    @ApiOperationSupport(order = 2 )
    @ApiOperation("树形列表")
    @PostMapping("/huimv-farm/basematerial/treeAll")
    public CommonResult<List<ErpBaseMaterial>> treeAll(@RequestBody  ErpBaseMaterialEditParam erpBaseMaterialPageParam) {
        List<ErpBaseMaterial>  treeList= erpBaseMaterialService.list(new QueryWrapper<ErpBaseMaterial>().eq(StringUtils.isNotBlank(erpBaseMaterialPageParam.getOrgId()),"org_id", erpBaseMaterialPageParam.getOrgId()));
        for (ErpBaseMaterial erpBaseMaterial : treeList) {
            erpBaseMaterial.setChilder(new ArrayList<>());
        }
        return CommonResult.data(buildTree(treeList, 0));
    }


//    @ApiOperationSupport(order = 2 )
//    @ApiOperation("更新erpId")
//    @GetMapping("/huimv-farm/basematerial/getErpId")
//    public CommonResult<List<ErpBaseMaterial>> getErpId(ErpBaseMaterialEditParam erpBaseMaterialPageParam) {
//
//        ResponseEntity<List<ShiJiChanLiang>> response = restTemplate.exchange(
//                "http://127.0.0.1:9200/erp-shengChan/getShiJiChanLiang?date=",
//                HttpMethod.GET,
//                null,
//                new ParameterizedTypeReference<List<ShiJiChanLiang>>() {}
//        );
//    }
    public static List<ErpBaseMaterial> buildTree(List<ErpBaseMaterial> nodes, int rootParentId) {
        Map<Integer, ErpBaseMaterial> nodeMap = new HashMap<>();
        List<ErpBaseMaterial> rootNodes = new ArrayList<>();

        // 将所有节点放入 Map 中，方便通过 ID 查找
        for (ErpBaseMaterial node : nodes) {
            nodeMap.put(node.getId(), node);
        }

        // 构建树
        for (ErpBaseMaterial node : nodes) {
            if (node.getParentId() == 0) {
                // 顶级节点，直接加入根节点列表
                rootNodes.add(node);
            } else {
                // 查找父节点，并将当前节点加入父节点的子节点列表
                ErpBaseMaterial parentNode = nodeMap.get(node.getParentId());
                if (parentNode != null) {
                    parentNode.addChild(node);
                }
            }
        }
        return rootNodes;
    }

    /**
     * 编辑erp_base_material
     *
     * @author 1
     * @date  2025/02/18 13:54
     */
    @ApiOperationSupport(order = 3)
    @ApiOperation("编辑erp_base_material")
    @PostMapping("/huimv-farm/basematerial/edit")
    public CommonResult<String> edit(@RequestBody @Valid ErpBaseMaterialEditParam erpBaseMaterialEditParam) {
        erpBaseMaterialService.edit(erpBaseMaterialEditParam);
        return CommonResult.ok();

    }

    /**
     * 删除erp_base_material
     *
     * @author 1
     * @date  2025/02/18 13:54
     */
    @ApiOperationSupport(order = 4)
    @ApiOperation("删除erp_base_material")
    @PostMapping("/huimv-farm/basematerial/delete")
    public CommonResult<String> delete(@RequestBody @Valid @NotEmpty(message = "集合不能为空")
                                                   CommonValidList<ErpBaseMaterialIdParam> erpBaseMaterialIdParamList) {
        erpBaseMaterialService.delete(erpBaseMaterialIdParamList);
        return CommonResult.ok();
    }

    /**
     * 获取erp_base_material详情
     *
     * @author 1
     * @date  2025/02/18 13:54
     */
    @ApiOperationSupport(order = 5)
    @ApiOperation("获取erp_base_material详情")
    @PostMapping("/huimv-farm/basematerial/detail")
    public CommonResult<ErpBaseMaterial> detail(@Valid ErpBaseMaterialIdParam erpBaseMaterialIdParam) {
        return CommonResult.data(erpBaseMaterialService.detail(erpBaseMaterialIdParam));
    }

    @ApiOperationSupport(order = 5)
    @ApiOperation("获取所有换算物料")
    @PostMapping("/huimv-farm/basematerial/getHuan")
    public CommonResult<List<ErpBaseMaterial>> getHuan(@Valid ErpBaseMaterialAddParam erpBaseMaterialIdParam) {
        return CommonResult.data(erpBaseMaterialService.list(new QueryWrapper<ErpBaseMaterial>().eq(StringUtils.isNotBlank(erpBaseMaterialIdParam.getOrgId()),"org_id",erpBaseMaterialIdParam.getOrgId()).eq("attr",0)));
    }
}
