package com.zhyc.module.produce.manage_sheep.service.impl;

import java.util.Date;
import java.util.List;

import com.zhyc.common.annotation.DataScope;
import com.zhyc.common.utils.SecurityUtils;
import com.zhyc.common.utils.StringUtils;
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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zhyc.module.produce.manage_sheep.mapper.ScChangeVarietyMapper;
import com.zhyc.module.produce.manage_sheep.domain.ScChangeVariety;
import com.zhyc.module.produce.manage_sheep.service.IScChangeVarietyService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 改品种记录Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-07-24
 */
@Service
public class ScChangeVarietyServiceImpl implements IScChangeVarietyService 
{
    @Autowired
    private ScChangeVarietyMapper scChangeVarietyMapper;
    @Autowired
    private IBasSheepService basSheepService;
    @Autowired
    private IBasSheepVarietyService varietyService;
    /**
     * 查询改品种记录
     * 
     * @param id 改品种记录主键
     * @return 改品种记录
     */
    @Override
    public ScChangeVariety selectScChangeVarietyById(Integer id)
    {
        return scChangeVarietyMapper.selectScChangeVarietyById(id);
    }

    /**
     * 查询改品种记录列表
     * 
     * @param scChangeVariety 改品种记录
     * @return 改品种记录
     */
    @Override
    @DataScope(deptAlias = "scv", userAlias = "scv")
    public List<ScChangeVariety> selectScChangeVarietyList(ScChangeVariety scChangeVariety)
    {
        return scChangeVarietyMapper.selectScChangeVarietyList(scChangeVariety,
                scChangeVariety.getManageTagsList());
    }

    /**
     * 新增改品种记录
     * 
     * @param scChangeVariety 改品种记录
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertScChangeVariety(ScChangeVariety scChangeVariety)
    {
        // ✅ 第1步：先查羊只（移到 insert 之前！）
        String manageTags = scChangeVariety.getManageTags();
        BasSheep sheep = basSheepService.selectBasSheepByManageTags(manageTags);
        if (sheep == null) {
            throw new RuntimeException("未找到耳号为【" + manageTags + "】的羊只，无法更新品种");
        }

        // ✅ 第2步：设置所有字段（关键！）
        scChangeVariety.setSheepId(sheep.getId().intValue());  // 设置羊只ID

        // 查询当前品种作为旧品种（如果前端没传）
        if (StringUtils.isBlank(scChangeVariety.getVarietyOld())) {
            // ✅ 修正：使用正确的方法名 selectBasSheepVarietyById
            BasSheepVariety oldVariety = varietyService.selectBasSheepVarietyById(sheep.getVarietyId());
            if (oldVariety != null) {
                scChangeVariety.setVarietyOld(oldVariety.getVariety());
            }
        }

        scChangeVariety.setCreateTime(new Date());
        scChangeVariety.setCreateBy(SecurityUtils.getUsername());

        // 校验
        if (StringUtils.isBlank(scChangeVariety.getTechnician())) {
            throw new RuntimeException("技术员不能为空");
        }
        if (scChangeVariety.getEventDate() == null) {
            throw new RuntimeException("事件日期不能为空");
        }

        // ✅ 第3步：再执行 insert（此时所有字段都有值了）
        int rows = scChangeVarietyMapper.insertScChangeVariety(scChangeVariety);
        if (rows <= 0) {
            return rows;
        }

        // 第4步：更新羊只品种（保持你的原逻辑）
        String newVarietyName = scChangeVariety.getVarietyNew();
        BasSheepVariety newVariety = varietyService.selectByVarietyName(newVarietyName);
        if (newVariety == null) {
            throw new RuntimeException("未找到品种【" + newVarietyName + "】的信息，请检查品种名称");
        }

        sheep.setVarietyId(newVariety.getId());
        basSheepService.updateBasSheep(sheep);

        return rows;
    }

    /**
     * 修改改品种记录
     * 
     * @param scChangeVariety 改品种记录
     * @return 结果
     */
    @Override
    public int updateScChangeVariety(ScChangeVariety scChangeVariety)
    {
        return scChangeVarietyMapper.updateScChangeVariety(scChangeVariety);
    }

    /**
     * 批量删除改品种记录
     * 
     * @param ids 需要删除的改品种记录主键
     * @return 结果
     */
    @Override
    public int deleteScChangeVarietyByIds(Integer[] ids)
    {
        return scChangeVarietyMapper.deleteScChangeVarietyByIds(ids);
    }

    /**
     * 删除改品种记录信息
     * 
     * @param id 改品种记录主键
     * @return 结果
     */
    @Override
    public int deleteScChangeVarietyById(Integer id)
    {
        return scChangeVarietyMapper.deleteScChangeVarietyById(id);
    }

    @Override
    public List<String> searchEarNumbers(String query) {
        return scChangeVarietyMapper.searchEarNumbers(query.trim());
    }
}
