package com.yhy.module.core.controller.admin.resource;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import com.yhy.module.core.dal.dataobject.resource.ResourceInfoPriceMappingDO;
import com.yhy.module.core.dal.mysql.resource.ResourceInfoPriceMappingMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@Tag(name = "管理后台 - 工料机-信息价关联")
@RestController
@RequestMapping("/core/resource/info-price-mapping")
@Validated
public class ResourceInfoPriceMappingController {

    @Resource
    private ResourceInfoPriceMappingMapper mappingMapper;
    
    @Resource
    private com.yhy.module.core.dal.mysql.infoprice.InfoPriceResourcePriceMapper infoPriceResourcePriceMapper;

    @PostMapping("/create")
    @Operation(summary = "创建工料机-信息价关联")
    @Parameters({
            @Parameter(name = "resourceItemId", description = "工料机ID", required = true),
            @Parameter(name = "infoPriceResourceId", description = "信息价工料机ID", required = true),
            @Parameter(name = "projectId", description = "项目ID（价格来源影响项目级别）"),
            @Parameter(name = "formula", description = "价格计算公式"),
            @Parameter(name = "selectedPriceId", description = "选中的价格历史ID"),
            @Parameter(name = "isCurrent", description = "是否为当前价格来源")
    })
    @PreAuthorize("@ss.hasPermission('core:resource:update')")
    public CommonResult<Long> createMapping(@RequestParam("resourceItemId") Long resourceItemId,
                                            @RequestParam("infoPriceResourceId") Long infoPriceResourceId,
                                            @RequestParam(value = "projectId", required = false) Long projectId,
                                            @RequestParam(value = "formula", required = false) String formula,
                                            @RequestParam(value = "selectedPriceId", required = false) Long selectedPriceId,
                                            @RequestParam(value = "isCurrent", required = false) Integer isCurrent) {
        // 检查是否已存在（按 projectId + resourceItemId 检查）
        if (projectId != null) {
            List<ResourceInfoPriceMappingDO> existing = mappingMapper.selectListByProjectAndResourceItem(projectId, resourceItemId);
            boolean exists = existing.stream().anyMatch(m -> m.getInfoPriceResourceId().equals(infoPriceResourceId));
            if (exists) {
                return success(0L); // 已存在，返回0表示未新增
            }
        } else if (mappingMapper.existsByResourceAndInfoPrice(resourceItemId, infoPriceResourceId)) {
            return success(0L); // 已存在，返回0表示未新增
        }
        
        // 先物理删除已软删除的记录（避免唯一约束冲突）
        mappingMapper.physicalDeleteByResourceAndInfoPrice(resourceItemId, infoPriceResourceId);
        
        // 公式逻辑（项目级）：如果公式为空，查询同租户下该工料机+信息价组合最后修改的公式
        String finalFormula;
        if (formula == null || formula.trim().isEmpty()) {
            String lastFormula = mappingMapper.selectLastFormulaByResourceAndInfoPrice(resourceItemId, infoPriceResourceId);
            finalFormula = (lastFormula != null && !lastFormula.trim().isEmpty()) ? lastFormula : "xxj";
        } else {
            finalFormula = formula;
        }
        
        ResourceInfoPriceMappingDO mapping = ResourceInfoPriceMappingDO.builder()
                .resourceItemId(resourceItemId)
                .infoPriceResourceId(infoPriceResourceId)
                .projectId(projectId)
                .formula(finalFormula)
                .selectedPriceId(selectedPriceId)
                .isCurrent(isCurrent != null ? isCurrent : 0)
                .build();
        mappingMapper.insert(mapping);
        return success(mapping.getId());
    }

    @PutMapping("/set-current")
    @Operation(summary = "设置当前价格来源")
    @Parameters({
            @Parameter(name = "resourceItemId", description = "工料机ID", required = true),
            @Parameter(name = "projectId", description = "项目ID（价格来源影响项目级别）"),
            @Parameter(name = "infoPriceResourceId", description = "信息价工料机ID", required = true),
            @Parameter(name = "selectedPriceId", description = "选中的价格历史ID", required = true)
    })
    @PreAuthorize("@ss.hasPermission('core:resource:update')")
    public CommonResult<Boolean> setCurrentPrice(@RequestParam("resourceItemId") Long resourceItemId,
                                                  @RequestParam(value = "projectId", required = false) Long projectId,
                                                  @RequestParam("infoPriceResourceId") Long infoPriceResourceId,
                                                  @RequestParam("selectedPriceId") Long selectedPriceId) {
        // 优先使用 projectId
        if (projectId != null) {
            // 1. 先将该项目下该工料机的所有关联的 isCurrent 设为 0
            mappingMapper.clearCurrentByProjectAndResourceItem(projectId, resourceItemId);
            // 2. 设置指定关联为当前价
            mappingMapper.setCurrentPriceByProject(projectId, resourceItemId, infoPriceResourceId, selectedPriceId);
        } else {
            // 兼容旧逻辑（租户级别）
            mappingMapper.clearCurrentByResourceItemId(resourceItemId);
            mappingMapper.setCurrentPrice(resourceItemId, infoPriceResourceId, selectedPriceId);
        }
        
        return success(true);
    }

    @PutMapping("/update-formula")
    @Operation(summary = "更新公式")
    @Parameters({
            @Parameter(name = "resourceItemId", description = "工料机ID", required = true),
            @Parameter(name = "infoPriceResourceId", description = "信息价工料机ID", required = true),
            @Parameter(name = "projectId", description = "项目ID（价格来源影响项目级别）"),
            @Parameter(name = "formula", description = "价格计算公式", required = true)
    })
    @PreAuthorize("@ss.hasPermission('core:resource:update')")
    public CommonResult<Boolean> updateFormula(@RequestParam("resourceItemId") Long resourceItemId,
                                               @RequestParam("infoPriceResourceId") Long infoPriceResourceId,
                                               @RequestParam(value = "projectId", required = false) Long projectId,
                                               @RequestParam("formula") String formula) {
        // 公式不允许为空，默认为 xxj
        String finalFormula = (formula == null || formula.trim().isEmpty()) ? "xxj" : formula;
        
        if (projectId != null) {
            mappingMapper.updateFormulaByProject(resourceItemId, infoPriceResourceId, projectId, finalFormula);
        } else {
            mappingMapper.updateFormula(resourceItemId, infoPriceResourceId, finalFormula);
        }
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除工料机-信息价关联")
    @Parameters({
            @Parameter(name = "resourceItemId", description = "工料机ID", required = true),
            @Parameter(name = "infoPriceResourceId", description = "信息价工料机ID", required = true)
    })
    @PreAuthorize("@ss.hasPermission('core:resource:update')")
    public CommonResult<Boolean> deleteMapping(@RequestParam("resourceItemId") Long resourceItemId,
                                               @RequestParam("infoPriceResourceId") Long infoPriceResourceId) {
        mappingMapper.delete(new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ResourceInfoPriceMappingDO>()
                .eq(ResourceInfoPriceMappingDO::getResourceItemId, resourceItemId)
                .eq(ResourceInfoPriceMappingDO::getInfoPriceResourceId, infoPriceResourceId));
        return success(true);
    }

    @GetMapping("/list")
    @Operation(summary = "获取工料机关联的信息价列表")
    @Parameters({
            @Parameter(name = "resourceItemId", description = "工料机ID", required = true),
            @Parameter(name = "projectId", description = "项目ID（价格来源影响项目级别）")
    })
    @PreAuthorize("@ss.hasPermission('core:resource:query')")
    public CommonResult<List<ResourceInfoPriceMappingDO>> getListByResourceItemId(
            @RequestParam("resourceItemId") Long resourceItemId,
            @RequestParam(value = "projectId", required = false) Long projectId) {
        // 优先使用 projectId 查询
        List<ResourceInfoPriceMappingDO> list;
        if (projectId != null) {
            list = mappingMapper.selectListByProjectAndResourceItem(projectId, resourceItemId);
        } else {
            list = mappingMapper.selectListByResourceItemId(resourceItemId);
        }
        return success(list);
    }

    @GetMapping("/list-with-detail")
    @Operation(summary = "获取工料机关联的信息价列表（含详情）")
    @Parameters({
            @Parameter(name = "resourceItemId", description = "工料机ID", required = true),
            @Parameter(name = "projectId", description = "项目ID（价格来源影响项目级别）")
    })
    @PreAuthorize("@ss.hasPermission('core:resource:query')")
    public CommonResult<List<java.util.Map<String, Object>>> getListWithDetailByResourceItemId(
            @RequestParam("resourceItemId") Long resourceItemId,
            @RequestParam(value = "projectId", required = false) Long projectId) {
        // 优先使用 projectId 查询
        List<ResourceInfoPriceMappingDO> mappings;
        if (projectId != null) {
            mappings = mappingMapper.selectListByProjectAndResourceItem(projectId, resourceItemId);
        } else {
            mappings = mappingMapper.selectListByResourceItemId(resourceItemId);
        }
        if (mappings.isEmpty()) {
            return success(java.util.Collections.emptyList());
        }
        
        // 获取信息价工料机详情
        List<Long> infoPriceResourceIds = mappings.stream()
                .map(ResourceInfoPriceMappingDO::getInfoPriceResourceId)
                .collect(java.util.stream.Collectors.toList());
        
        List<com.yhy.module.core.dal.dataobject.infoprice.InfoPriceResourceDO> resources = 
                infoPriceResourceMapper.selectBatchIds(infoPriceResourceIds);
        
        java.util.Map<Long, com.yhy.module.core.dal.dataobject.infoprice.InfoPriceResourceDO> resourceMap = 
                resources.stream().collect(java.util.stream.Collectors.toMap(
                        com.yhy.module.core.dal.dataobject.infoprice.InfoPriceResourceDO::getId, 
                        r -> r));
        
        // 获取工料机基础信息（名称、规格、单位）
        List<Long> sourceResourceItemIds = resources.stream()
                .map(com.yhy.module.core.dal.dataobject.infoprice.InfoPriceResourceDO::getSourceResourceItemId)
                .filter(java.util.Objects::nonNull)
                .distinct()
                .collect(java.util.stream.Collectors.toList());
        
        java.util.Map<Long, com.yhy.module.core.dal.dataobject.resource.ResourceItemDO> resourceItemMap = new java.util.HashMap<>();
        if (!sourceResourceItemIds.isEmpty()) {
            List<com.yhy.module.core.dal.dataobject.resource.ResourceItemDO> resourceItems = 
                    resourceItemMapper.selectBatchIds(sourceResourceItemIds);
            resourceItemMap = resourceItems.stream().collect(java.util.stream.Collectors.toMap(
                    com.yhy.module.core.dal.dataobject.resource.ResourceItemDO::getId, 
                    r -> r));
        }
        
        // 组装结果
        List<java.util.Map<String, Object>> result = new java.util.ArrayList<>();
        for (ResourceInfoPriceMappingDO mapping : mappings) {
            java.util.Map<String, Object> item = new java.util.HashMap<>();
            item.put("id", mapping.getId());
            item.put("resourceItemId", mapping.getResourceItemId());
            item.put("infoPriceResourceId", mapping.getInfoPriceResourceId());
            item.put("formula", mapping.getFormula());
            item.put("selectedPriceId", mapping.getSelectedPriceId());
            item.put("isCurrent", mapping.getIsCurrent());
            
            com.yhy.module.core.dal.dataobject.infoprice.InfoPriceResourceDO resource = resourceMap.get(mapping.getInfoPriceResourceId());
            if (resource != null) {
                item.put("code", resource.getCode());
                
                // 优先使用selectedPriceId对应的价格历史记录的价格信息
                if (mapping.getSelectedPriceId() != null) {
                    com.yhy.module.core.dal.dataobject.infoprice.InfoPriceResourcePriceDO selectedPrice = 
                            infoPriceResourcePriceMapper.selectById(mapping.getSelectedPriceId());
                    if (selectedPrice != null) {
                        item.put("priceTaxExcl", selectedPrice.getPriceTaxExcl());
                        item.put("taxRate", selectedPrice.getTaxRate());
                        item.put("priceTaxIncl", selectedPrice.getPriceTaxIncl());
                        item.put("priceStartTime", selectedPrice.getStartTime());
                        item.put("priceEndTime", selectedPrice.getEndTime());
                    } else {
                        // selectedPriceId对应的记录不存在，使用资源默认价格
                        item.put("priceTaxExcl", resource.getPriceTaxExcl());
                        item.put("taxRate", resource.getTaxRate());
                        item.put("priceTaxIncl", resource.getPriceTaxIncl());
                    }
                } else {
                    // 没有selectedPriceId，使用资源默认价格
                    item.put("priceTaxExcl", resource.getPriceTaxExcl());
                    item.put("taxRate", resource.getTaxRate());
                    item.put("priceTaxIncl", resource.getPriceTaxIncl());
                }
                
                // 从工料机基础表获取名称、规格、单位
                if (resource.getSourceResourceItemId() != null) {
                    com.yhy.module.core.dal.dataobject.resource.ResourceItemDO resourceItem = 
                            resourceItemMap.get(resource.getSourceResourceItemId());
                    if (resourceItem != null) {
                        item.put("name", resourceItem.getName());
                        item.put("spec", resourceItem.getSpec());
                        item.put("unit", resourceItem.getUnit());
                    }
                }
                
                // 获取信息价专业和地区
                if (resource.getCategoryTreeId() != null) {
                    com.yhy.module.core.dal.dataobject.infoprice.InfoPriceCategoryTreeDO categoryTree = 
                            infoPriceCategoryTreeMapper.selectById(resource.getCategoryTreeId());
                    if (categoryTree != null && categoryTree.getBookId() != null) {
                        com.yhy.module.core.dal.dataobject.infoprice.InfoPriceBookDO book = 
                                infoPriceBookMapper.selectById(categoryTree.getBookId());
                        if (book != null && book.getTreeNodeId() != null) {
                            com.yhy.module.core.dal.dataobject.infoprice.InfoPriceTreeDO treeNode = 
                                    infoPriceTreeMapper.selectById(book.getTreeNodeId());
                            if (treeNode != null) {
                                // 信息价专业
                                item.put("professionType", treeNode.getEnumType());
                                // 完整地区路径
                                item.put("fullRegion", buildFullRegionPath(treeNode));
                            }
                        }
                    }
                }
            }
            result.add(item);
        }
        return success(result);
    }
    
    /**
     * 构建完整地区路径
     */
    private String buildFullRegionPath(com.yhy.module.core.dal.dataobject.infoprice.InfoPriceTreeDO treeNode) {
        if (treeNode == null) {
            return "";
        }
        String[] pathIds = treeNode.getPath();
        if (pathIds == null || pathIds.length == 0) {
            return treeNode.getName();
        }
        StringBuilder pathBuilder = new StringBuilder();
        for (String pathId : pathIds) {
            try {
                Long id = Long.parseLong(pathId);
                com.yhy.module.core.dal.dataobject.infoprice.InfoPriceTreeDO pathNode = infoPriceTreeMapper.selectById(id);
                if (pathNode != null && pathNode.getName() != null && !pathNode.getName().isEmpty()) {
                    if (pathBuilder.length() > 0) {
                        pathBuilder.append(" / ");
                    }
                    pathBuilder.append(pathNode.getName());
                }
            } catch (NumberFormatException e) {
                // 忽略无效的ID
            }
        }
        if (pathBuilder.length() > 0) {
            pathBuilder.append(" / ");
        }
        pathBuilder.append(treeNode.getName());
        return pathBuilder.toString();
    }

    @GetMapping("/tenant-associated-ids")
    @Operation(summary = "获取租户级已关联的信息价ID列表（用于弹窗置顶）")
    @Parameters({
            @Parameter(name = "resourceItemId", description = "工料机ID", required = true)
    })
    @PreAuthorize("@ss.hasPermission('core:resource:query')")
    public CommonResult<java.util.Set<Long>> getTenantAssociatedIds(
            @RequestParam("resourceItemId") Long resourceItemId) {
        java.util.Set<Long> ids = mappingMapper.selectAssociatedInfoPriceIdsByResourceItem(resourceItemId);
        return success(ids);
    }

    @Resource
    private com.yhy.module.core.dal.mysql.infoprice.InfoPriceResourceMapper infoPriceResourceMapper;
    
    @Resource
    private com.yhy.module.core.dal.mysql.resource.ResourceItemMapper resourceItemMapper;
    
    @Resource
    private com.yhy.module.core.dal.mysql.infoprice.InfoPriceCategoryTreeMapper infoPriceCategoryTreeMapper;
    
    @Resource
    private com.yhy.module.core.dal.mysql.infoprice.InfoPriceBookMapper infoPriceBookMapper;
    
    @Resource
    private com.yhy.module.core.dal.mysql.infoprice.InfoPriceTreeMapper infoPriceTreeMapper;
}
