package com.zhyc.module.base.controller;

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

import com.zhyc.module.base.domain.BasSheep;
import com.zhyc.module.base.domain.BasSheepVariety;
import com.zhyc.module.base.service.IBasSheepService;
import com.zhyc.module.base.service.IBasSheepVarietyService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.zhyc.common.annotation.Log;
import com.zhyc.common.core.controller.BaseController;
import com.zhyc.common.core.domain.AjaxResult;
import com.zhyc.common.enums.BusinessType;
import com.zhyc.common.utils.poi.ExcelUtil;
import com.zhyc.common.core.page.TableDataInfo;

/**
 * 羊只基本信息Controller
 *
 * @author ruoyi
 * @date 2025-07-15
 */
@RestController
@RequestMapping("/sheep/sheep")
public class BasSheepController extends BaseController {
    @Autowired
    private IBasSheepService basSheepService;

    @Autowired
    private IBasSheepVarietyService basSheepVarietyService;

    /**
     * 查询羊只基本信息列表
     */
    @PreAuthorize("@ss.hasPermi('sheep:sheep:list')")
    @GetMapping("/list")
    public TableDataInfo list(BasSheep basSheep) {
        startPage();
        List<BasSheep> list = basSheepService.selectBasSheepList(basSheep);
        return getDataTable(list);
    }

//查询耳号列表
    @GetMapping("/earNumbers")
    public AjaxResult searchEarNumbers(@RequestParam("query") String query) {
        try {
            List<String> earNumbers =basSheepService.searchEarNumbers(query);
            return success(earNumbers);
        } catch (Exception e) {
            logger.error("搜索耳号异常", e);
            return error("搜索耳号失败：" + e.getMessage());
        }
    }

    /**
     * 导出羊只基本信息列表
     */
    @PreAuthorize("@ss.hasPermi('sheep:sheep:export')")
    @Log(title = "羊只基本信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BasSheep basSheep) {
        List<BasSheep> list = basSheepService.selectBasSheepList(basSheep);
        ExcelUtil<BasSheep> util = new ExcelUtil<BasSheep>(BasSheep.class);
        util.exportExcel(response, list, "羊只基本信息数据");
    }

    /**
     * 获取羊只基本信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('sheep:sheep:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(basSheepService.selectBasSheepById(id));
    }

    /**
     * 新增羊只基本信息
     */
    @PreAuthorize("@ss.hasPermi('sheep:sheep:add')")
    @Log(title = "羊只基本信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BasSheep basSheep) {
        return toAjax(basSheepService.insertBasSheep(basSheep));
    }

    /**
     * 修改羊只基本信息
     */
    @PreAuthorize("@ss.hasPermi('sheep:sheep:edit')")
    @Log(title = "羊只基本信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BasSheep basSheep) {
        return toAjax(basSheepService.updateBasSheep(basSheep));
    }

    /**
     * 删除羊只基本信息
     */
    @PreAuthorize("@ss.hasPermi('sheep:sheep:remove')")
    @Log(title = "羊只基本信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(basSheepService.deleteBasSheepByIds(ids));
    }

    /**
     * 批量查询羊只耳号状态
     */
    @GetMapping("/byManageTags/{manageTags}")
    public AjaxResult byManageTags(@PathVariable String manageTags) {
        if (manageTags == null || manageTags.trim().isEmpty()) {
            return error("管理耳号不能为空");
        }

        // 批量查询模式 - 使用空格或逗号分割
        String[] tags = manageTags.split("[\\s,，]+");

        try {
            // 过滤掉空值并去重
            List<String> validTags = Arrays.stream(tags)
                    .map(String::trim)
                    .filter(tag -> !tag.isEmpty())
                    .distinct()
                    .collect(Collectors.toList());

            if (validTags.isEmpty()) {
                return error("有效的耳号不能为空");
            }

            // 查询所有存在的羊只
            List<BasSheep> existingSheep = basSheepService.selectBasSheepByManageTagsList(validTags);

            Set<String> existingTagSet = existingSheep.stream()
                    .map(BasSheep::getManageTags)
                    .collect(Collectors.toSet());

            // 分别统计在羊群和不在羊群的耳号
            List<String> inHerd = new ArrayList<>();
            List<String> notInHerd = new ArrayList<>();

            for (String tag : validTags) {
                if (existingTagSet.contains(tag)) {
                    inHerd.add(tag);
                } else {
                    notInHerd.add(tag);
                }
            }

            Map<String, Object> result = new HashMap<>();
            result.put("inHerd", inHerd);
            result.put("notInHerd", notInHerd);
            result.put("total", validTags.size());
            result.put("inHerdCount", inHerd.size());
            result.put("notInHerdCount", notInHerd.size());
            result.put("sheepDetails", existingSheep);

            return success(result);
        } catch (Exception e) {
            logger.error("批量查询羊只状态异常", e);
            return error("批量查询失败：" + e.getMessage());
        }
    }

    /**
     * 根据羊只类型ID查询羊只列表
     */
//    @PreAuthorize("@ss.hasPermi('sheep:sheep:queryByType')")
    @GetMapping("/listByTypeId")
    public TableDataInfo listByTypeId(Integer typeId) {
        if (typeId == null) {
            return getDataTable(new ArrayList<>());
        }
        BasSheep query = new BasSheep();
        query.setTypeId(typeId.longValue());
        List<BasSheep> list = basSheepService.selectBasSheepList(query);
        return getDataTable(list);
    }

    /**
     * 根据羊舍ID和羊只类型ID组合查询羊只列表
     */
    @PreAuthorize("@ss.hasPermi('sheep:sheep:query')")
    @GetMapping("/listBySheepfoldAndType")
    public TableDataInfo listBySheepfoldAndType(Integer sheepfoldId, Integer typeId) {
        if (sheepfoldId == null || typeId == null) {
            return getDataTable(new ArrayList<>());
        }
        BasSheep query = new BasSheep();
        query.setSheepfoldId(sheepfoldId.longValue());
        query.setTypeId(typeId.longValue());
        List<BasSheep> list = basSheepService.selectBasSheepList(query);
        return getDataTable(list);
    }


    /**
     * 根据耳号（管理耳号或电子耳号）+ 耳号类型 查询羊只信息
     * earType：0-电子耳号，1-管理耳号
     */
    @GetMapping("/byEarNumber")
    public AjaxResult byEarNumber(@RequestParam String earNumber, @RequestParam Integer earType) {
        BasSheep query = new BasSheep();
        query.setManageTags(earNumber);
        List<BasSheep> list = basSheepService.selectBasSheepList(query);

        if (list.isEmpty()) {
            query.setManageTags(null);
            query.setElectronicTags(earNumber);
            list = basSheepService.selectBasSheepList(query);
        }

        if (list.isEmpty()) {
            return error("未找到对应的羊只");
        }

        BasSheep sheep = list.get(0);

        String oldTag = earType == 0 ? sheep.getElectronicTags() : sheep.getManageTags();

        Map<String, Object> result = new HashMap<>();
        result.put("sheep", sheep);
        result.put("oldTag", oldTag);

        return success(result);
    }

    /**
     * 判断耳号是否存在（用于新增羊只时校验）
     */
    @GetMapping("/existsByManageTags/{manageTags}")
    public AjaxResult existsByManageTags(@PathVariable String manageTags) {
        BasSheep sheep = basSheepService.selectBasSheepByManageTags(manageTags.trim());
        if (sheep != null) {
            return success(true);
        }
        return success(false);
    }


    @GetMapping("/existsByTag")
    public AjaxResult existsByTag(@RequestParam String tag, @RequestParam Integer earType) {
        boolean exists = basSheepService.existsByTag(tag, earType);
        Map<String, Object> result = new HashMap<>();
        result.put("exists", exists);
        return success(result);
    }
}
