package com.zhyc.module.base.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.zhyc.common.core.domain.AjaxResult;
import com.zhyc.module.base.domain.BasGroupTreeVo;
import com.zhyc.module.base.domain.BasSheepGroupMapping;
import com.zhyc.module.base.mapper.BasSheepGroupMappingMapper;
import com.zhyc.module.base.service.IBasSheepGroupMappingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * 羊只分组关联Service业务层处理
 * 
 * @author wyt
 * @date 2025-07-16
 */
@Service
public class BasSheepGroupMappingServiceImpl implements IBasSheepGroupMappingService
{
    @Autowired
    private BasSheepGroupMappingMapper basSheepGroupMappingMapper;

    /**
     * 查询羊只分组关联
     * 
     * @param id 羊只分组关联主键
     * @return 羊只分组关联
     */
    @Override
    public BasSheepGroupMapping selectBasSheepGroupMappingById(Long id)
    {
        return basSheepGroupMappingMapper.selectBasSheepGroupMappingById(id);
    }

    /**
     * 查询羊只分组关联列表
     * 
     * @param basSheepGroupMapping 羊只分组关联
     * @return 羊只分组关联
     */
    @Override
    public List<BasSheepGroupMapping> selectBasSheepGroupMappingList(BasSheepGroupMapping basSheepGroupMapping)
    {
        return basSheepGroupMappingMapper.selectBasSheepGroupMappingList(basSheepGroupMapping);
    }


    @Override
    public List<Map<String, Object>> selectBasSheepGroupMappingList(
            Long sheepId, Long groupId, List<String> bsManageTags) {
        return basSheepGroupMappingMapper.selectBasSheepGroupMappingList(sheepId, groupId, bsManageTags);
    }

    /**
     * 新增羊只分组关联
     * 
     * @param basSheepGroupMapping 羊只分组关联
     * @return 结果
     */
    @Override
    public int insertBasSheepGroupMapping(BasSheepGroupMapping basSheepGroupMapping)
    {
        return basSheepGroupMappingMapper.insertBasSheepGroupMapping(basSheepGroupMapping);
    }

    /**
     * 修改羊只分组关联
     * 
     * @param basSheepGroupMapping 羊只分组关联
     * @return 结果
     */
//    @Override
//    public int updateBasSheepGroupMapping(BasSheepGroupMapping basSheepGroupMapping)
//    {
//        return basSheepGroupMappingMapper.updateBasSheepGroupMapping(basSheepGroupMapping);
//    }
    @Override
    public int updateBasSheepGroupMapping(BasSheepGroupMapping basSheepGroupMapping) {

        Long SheepId = basSheepGroupMapping.getSheepId();
        Long GroupId = basSheepGroupMapping.getGroupId();
        existsInGroup(SheepId,GroupId);

        if (existsInGroup(basSheepGroupMapping.getSheepId(), basSheepGroupMapping.getGroupId())) {
            throw new RuntimeException("该羊已在此分组，无需修改");
        }
        return basSheepGroupMappingMapper.updateBasSheepGroupMapping(basSheepGroupMapping);
    }

    /**
     * 批量删除羊只分组关联
     * 
     * @param ids 需要删除的羊只分组关联主键
     * @return 结果
     */
    @Override
    public int deleteBasSheepGroupMappingByIds(Long[] ids)
    {
        return basSheepGroupMappingMapper.deleteBasSheepGroupMappingByIds(ids);
    }

    /**
     * 删除羊只分组关联信息
     * 
     * @param id 羊只分组关联主键
     * @return 结果
     */
    @Override
    public int deleteBasSheepGroupMappingById(Long id)
    {
        return basSheepGroupMappingMapper.deleteBasSheepGroupMappingById(id);
    }



    @Override
    public AjaxResult addByEarTags(List<String> earTags, Long groupId) {
        // 1. 参数判空
        if (earTags == null || earTags.isEmpty()) {
            return AjaxResult.error("耳号列表不能为空");
        }

        // 2. 根据耳号查询羊只（manage_tags -> id）
        List<Map<String, Object>> sheepList = basSheepGroupMappingMapper.selectSheepIdsByEarTags(earTags);
        Map<String, Long> tagToId = new HashMap<>();
        for (Map<String, Object> s : sheepList) {
            tagToId.put((String) s.get("manage_tags"), ((Number) s.get("id")).longValue());
        }

        // 3. 不存在的耳号
        List<String> missing = new ArrayList<>();
        for (String tag : earTags) {
            if (!tagToId.containsKey(tag)) {
                missing.add(tag);
            }
        }
        if (!missing.isEmpty()) {
            Map<String, Object> res = new HashMap<>();
            res.put("success", false);
            res.put("missing", missing);
            return AjaxResult.success(res);
        }

        // 4. 查询该分组下已存在的羊只ID
        List<BasSheepGroupMapping> existingRows = basSheepGroupMappingMapper.selectListByGroupId(groupId);
        System.out.println("🔍 existingRows 类型 = " + existingRows.getClass());

        Set<Long> existingIds = existingRows.stream()
                .map(BasSheepGroupMapping::getSheepId)
                .collect(Collectors.toSet());

        System.out.println("🔍 existingIds = " + existingIds);

        // 5. 过滤出未在该分组的羊只
        List<BasSheepGroupMapping> toInsert = new ArrayList<>();
        for (Map.Entry<String, Long> e : tagToId.entrySet()) {
            Long sheepId = e.getValue();
            if (!existingIds.contains(sheepId)) {
                BasSheepGroupMapping m = new BasSheepGroupMapping();
                m.setSheepId(sheepId);
                m.setGroupId(groupId);
                toInsert.add(m);
            }
        }

        if (toInsert.isEmpty()) {
            return AjaxResult.success("所选羊只已全部在该分组中");
        }

        // 6. 批量插入
        int rows = basSheepGroupMappingMapper.batchInsert(toInsert);
        Map<String, Object> res = new HashMap<>();
        res.put("success", true);
        res.put("inserted", rows);
        return AjaxResult.success(res);
    }

    private boolean existsInGroup(Long sheepId, Long groupId) {
        BasSheepGroupMapping param = new BasSheepGroupMapping();
        List<Map<String, Object>> list = basSheepGroupMappingMapper
                .selectBasSheepGroupMappingList(sheepId, groupId, null);
        return !list.isEmpty();
    }


    private List<BasGroupTreeVo> buildTree(List<BasGroupTreeVo> all) {
        Map<Long, BasGroupTreeVo> map = all.stream()
                .collect(Collectors.toMap(BasGroupTreeVo::getGroupId, v -> v));
        List<BasGroupTreeVo> tree = new ArrayList<>();
        for (BasGroupTreeVo n : all) {
            if (n.getParentId() == null || n.getParentId() == 0L) {
                tree.add(n);
            } else {
                BasGroupTreeVo parent = map.get(n.getParentId());
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(n);
                }
            }
        }
        return tree;
    }
    @Override
    public List<BasGroupTreeVo> selectGroupTree() {
        List<BasGroupTreeVo> list = basSheepGroupMappingMapper.selectGroupTree();
        return buildTree(list);
    }

}
