package com.ruoyi.web.base.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.ProductionShipmentNotification;
import com.ruoyi.web.base.domain.param.ProductionRegularPlanParam;
import com.ruoyi.web.base.domain.param.ProductionRegularPlanRequest;
import com.ruoyi.web.base.domain.param.TreeNode;
import com.ruoyi.web.base.service.IProductionShipmentNotificationService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

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

@RestController
@RequestMapping("/production-shipment-notification")
public class ProductionShipmentNotificationController {

    @Autowired
    private IProductionShipmentNotificationService productionShipmentNotificationService;
    @Autowired
    private TokenService tokenService;

    @ApiOperation("出货通知添加")
    @PostMapping("/add")
    public AjaxResult add(@RequestBody ProductionShipmentNotification notification, HttpServletRequest request) throws Exception {
        String loginOrgId = tokenService.getLoginOrgId(request);

        notification.setOrgId(loginOrgId);
        notification.setCreateBy(getUsername());
        return success(productionShipmentNotificationService.save(notification));
    }

    @ApiOperation("出货通知修改")
    @PostMapping("/edit")
    public AjaxResult edit(@RequestBody ProductionShipmentNotification notification, HttpServletRequest request) throws Exception {
        String loginOrgId = tokenService.getLoginOrgId(request);

        notification.setUpdateBy(getUsername());
        return success(productionShipmentNotificationService.updateById(notification));
    }

    @ApiOperation("出货通知删除")
    @PostMapping("/delete")
    public AjaxResult delete(@RequestBody Map<String, String> paramsMap) {
        String ids = paramsMap.get("ids");
        for (String id : ids.split(",")) {
            productionShipmentNotificationService.removeById(id);
        }
        return success();
    }



    @ApiOperation("出货通知列表")
    @PostMapping("/listTree")
    public AjaxResult listTree(  @RequestBody ProductionRegularPlanRequest planRequest,HttpServletRequest request) {
        String productionTypes = planRequest.getProductTypes();
        QueryWrapper<ProductionShipmentNotification> wrapper = new QueryWrapper<ProductionShipmentNotification>()
                .eq("a.org_id", tokenService.getLoginOrgId(request));
        if (StringUtils.isNotEmpty(productionTypes)){
            wrapper.in("a.product_num", Arrays.asList(productionTypes.split(",")));
        }
        wrapper.eq(StringUtils.isNotEmpty(planRequest.getDeliveryDate()),"a.delivery_date",planRequest.getDeliveryDate());
        List<ProductionRegularPlanParam> listTree = productionShipmentNotificationService.listTree(wrapper);

        System.out.println(listTree.toString());
        return success( buildTree(listTree));
    }
    public static void main(String[] args) {
        // 测试数据
        List<ProductionRegularPlanParam> dataList = new ArrayList<>();
        dataList.add(new ProductionRegularPlanParam("客户A", "市场1", "线路X", "C1", "L1", "M1"));
        dataList.add(new ProductionRegularPlanParam("客户B", "市场1", "线路X", "C2", "L1", "M1"));
        dataList.add(new ProductionRegularPlanParam("客户C", "市场2", "线路Y", "C3", "L2", "M2"));

        // 构建树
        List<TreeNode> tree = buildTree(dataList);

        // 打印树结构
        for (TreeNode treeNode : tree) {
            System.out.println(treeNode);
        }
    }
        public static List<TreeNode> buildTree(List<ProductionRegularPlanParam> dataList) {
            // 存储根节点（按lineNum分组）
            Map<String, TreeNode> lineNodeMap = new HashMap<>();
            // 存储市场节点（按marketNum分组）
            Map<String, TreeNode> marketNodeMap = new HashMap<>();

            // 第一步：构建所有节点并建立层级关系
            for (ProductionRegularPlanParam data : dataList) {
                // 创建或获取line节点
                TreeNode lineNode = lineNodeMap.computeIfAbsent(data.getLineNum(),
                        k -> new TreeNode(TreeNode.NodeType.LINE, data.getLineNum(), data.getLineName()));

                // 创建或获取market节点
                TreeNode marketNode = marketNodeMap.computeIfAbsent(data.getMarketNum(),
                        k -> new TreeNode(TreeNode.NodeType.MARKET, data.getMarketNum(), data.getMarketName()));

                // 确保market节点属于正确的line节点
                if (!lineNode.getChildren().contains(marketNode)) {
                    lineNode.addChild(marketNode);

                }


                if (!marketNode.getAllCustomerNums().contains(data.getCustomerNum())) {
                    TreeNode customerNode = new TreeNode(TreeNode.NodeType.CUSTOMER,
                            data.getCustomerNum(), data.getCustomer());
                    marketNode.addChild(customerNode);
                    customerNode.addCustomerNum(data.getCustomerNum());
                }
                marketNode.addCustomerNum(data.getCustomerNum());
                lineNode.addCustomerNum(data.getCustomerNum());
            }


//            for (TreeNode lineNode : lineNodeMap.values()) {
//                for (TreeNode marketNode : lineNode.getChildren()) {
//                    for (TreeNode customerNode : marketNode.getChildren()) {
//                        customerNode.addCustomerNum(customerNode.getNum());
//                        // 收集market节点的customerNum
//                        marketNode.getAllCustomerNums().add(customerNode.getNum());
//                    }
//
//                    // 收集line节点的customerNum
//                    lineNode.getAllCustomerNums().addAll(marketNode.getAllCustomerNums());
//                }
//            }

            return new ArrayList<>(lineNodeMap.values());
        }


    @ApiOperation("出货通知分页")
    @PostMapping("/page")
    public AjaxResult page(
            @RequestBody ProductionRegularPlanRequest planRequest,
            HttpServletRequest request
    ) {
        String productionTypes = planRequest.getProductTypes();
        String customerNums = planRequest.getCustomerNums();
        QueryWrapper<ProductionShipmentNotification> wrapper = new QueryWrapper<ProductionShipmentNotification>()
                .eq("org_id", tokenService.getLoginOrgId(request));
        if (StringUtils.isNotEmpty(productionTypes)){
            wrapper.in("product_type", Arrays.asList(productionTypes.split(",")));
        }
        if (StringUtils.isNotEmpty(customerNums)){
            wrapper.in("customer_number", Arrays.asList(customerNums.split(",")));
        }

        wrapper.eq(StringUtils.isNotEmpty(planRequest.getDeliveryDate()),"delivery_date",planRequest.getDeliveryDate());



        return success( productionShipmentNotificationService.page(new Page<>(planRequest.getPageNum(),planRequest.getPageSize()),wrapper));
    }
    @ApiOperation("出货通知列表")
    @PostMapping("/list")
    public AjaxResult listAll(  @RequestBody ProductionRegularPlanRequest planRequest,HttpServletRequest request) {
        String productionTypes = planRequest.getProductTypes();
        String customerNums = planRequest.getCustomerNums();
        QueryWrapper<ProductionShipmentNotification> wrapper = new QueryWrapper<ProductionShipmentNotification>()
                .eq("org_id", tokenService.getLoginOrgId(request));
        if (StringUtils.isNotEmpty(productionTypes)){
            wrapper.in("product_type", Arrays.asList(productionTypes.split(",")));
        }
        if (StringUtils.isNotEmpty(customerNums)){
            wrapper.in("customer_number", Arrays.asList(customerNums.split(",")));
        }

        wrapper.eq(StringUtils.isNotEmpty(planRequest.getDeliveryDate()),"delivery_date",planRequest.getDeliveryDate());


        return success( productionShipmentNotificationService.list(wrapper));
    }

    @ApiOperation("出货通知详情")
    @PostMapping("/listById")
    public AjaxResult listById(@RequestBody Map<String, String> paramsMap) {
        String id = paramsMap.get("id");
        return success(productionShipmentNotificationService.getById(id));
    }
}
