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

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.zhyc.module.produce.breed.mapper.ScLambingRecordMapper;
import com.zhyc.module.produce.breed.mapper.ScLambDetailMapper;
import com.zhyc.module.produce.breed.domain.ScLambingRecord;
import com.zhyc.module.produce.breed.domain.ScLambDetail;
import com.zhyc.module.produce.breed.service.IScLambingRecordService;

/**
 * 产羔记录Service业务层处理
 */
@Service
public class ScLambingRecordServiceImpl implements IScLambingRecordService {

    @Autowired
    private ScLambingRecordMapper scLambingRecordMapper;

    @Autowired
    private ScLambDetailMapper scLambDetailMapper;

    /**
     * 查询产羔记录列表
     */
    @Override
    public List<ScLambingRecord> selectScLambingRecordList(ScLambingRecord scLambingRecord) {
        return scLambingRecordMapper.selectScLambingRecordList(scLambingRecord);
    }

    /**
     * 根据母羊耳号查询最新配种记录
     */
    @Override
    public Map<String, Object> getLatestBreedingByEarNumber(String earNumber) {
        return scLambingRecordMapper.getLatestBreedingByEarNumber(earNumber);
    }

    @Override
    public List<String> searchEarNumbers(String query) {
        return scLambingRecordMapper.searchEarNumbers(query);
    }
    /**
     * 新增产羔记录（包含羔羊详情）
     */
    @Override
    @Transactional
    public int insertScLambingRecord(ScLambingRecord scLambingRecord) {
        // 1. 插入产羔记录
        int result = scLambingRecordMapper.insertScLambingRecord(scLambingRecord);

        // 2. 如果有羔羊详情，则批量插入羔羊详情
        if (scLambingRecord.getLambDetails() != null && !scLambingRecord.getLambDetails().isEmpty()) {
            insertLambDetails(scLambingRecord);
        }

        return result;
    }

    /**
     * 批量插入羔羊详情
     */
    private void insertLambDetails(ScLambingRecord scLambingRecord) {
        // 遍历羔羊详情列表，逐个插入
        for (ScLambDetail lambDetail : scLambingRecord.getLambDetails()) {
            // 设置产羔记录ID
            lambDetail.setLambingRecordId(scLambingRecord.getId());

            // 设置创建信息
            lambDetail.setCreateBy(scLambingRecord.getCreateBy());
            lambDetail.setCreateTime(scLambingRecord.getCreateTime());

            // 数据验证和转换
            validateAndConvertLambDetail(lambDetail);

            // 插入羔羊详情
            scLambDetailMapper.insertScLambDetail(lambDetail);
            scLambDetailMapper.insertBasSheep(lambDetail);
        }
    }

    /**
     * 验证和转换羔羊详情
     */
    private void validateAndConvertLambDetail(ScLambDetail lambDetail) {
        // 验证必填字段
        if (lambDetail.getLambEarNumber() == null || lambDetail.getLambEarNumber().trim().isEmpty()) {
            throw new RuntimeException("羔羊耳号不能为空");
        }

        if (lambDetail.getGender() == null) {
            throw new RuntimeException("羔羊性别不能为空");
        }

        // 验证性别值的有效性：1-母，2-公，3-阉羊，4-兼性
        if (lambDetail.getGender() < 1 || lambDetail.getGender() > 4) {
            throw new RuntimeException("羔羊性别值无效，请使用1（母）、2（公）、3（阉羊）或4（兼性）");
        }

        // 检查耳号是否已存在
        int count = scLambDetailMapper.checkLambEarNumberExists(lambDetail.getLambEarNumber().trim(), null);
        if (count > 0) {
            throw new RuntimeException("羔羊耳号 [" + lambDetail.getLambEarNumber() + "] 已存在，请使用其他耳号");
        }

        // 设置默认值
        if (lambDetail.getIsRetained() == null) {
            lambDetail.setIsRetained(false);  // 默认为0（否）
        }

        // 验证是否留养值的有效性：0-否，1-是
        if (lambDetail.getIsRetained() != false && lambDetail.getIsRetained() != true) {
            throw new RuntimeException("是否留养值无效，请使用0（否）或1（是）");
        }

        if (lambDetail.getBirthday() == null) {
            lambDetail.setBirthday(new java.util.Date());
        }

        // 处理体重（前端可能传来的是number类型）
        if (lambDetail.getBirthWeight() == null) {
            lambDetail.setBirthWeight(BigDecimal.ZERO);
        }

        // 验证品种ID
        if (lambDetail.getLambBreed() == null) {
            throw new RuntimeException("羔羊品种不能为空");
        }

        // 去除空格
        lambDetail.setLambEarNumber(lambDetail.getLambEarNumber().trim());
        if (lambDetail.getLineage() != null) {
            lambDetail.setLineage(lambDetail.getLineage().trim());
        }
    }

    /**
     * 修改产羔记录
     */
    @Override
    @Transactional
    public int updateScLambingRecord(ScLambingRecord scLambingRecord) {
        // 更新产羔记录
        int result = scLambingRecordMapper.updateScLambingRecord(scLambingRecord);

        // 如果包含羔羊详情，先删除原有的，再插入新的
        if (scLambingRecord.getLambDetails() != null) {
            // 删除原有羔羊详情
            scLambDetailMapper.deleteScLambDetailByLambingRecordId(scLambingRecord.getId());

            // 插入新的羔羊详情
            if (!scLambingRecord.getLambDetails().isEmpty()) {
                insertLambDetails(scLambingRecord);
            }
        }

        return result;
    }

    /**
     * 批量删除产羔记录
     */
    @Override
    @Transactional
    public int deleteScLambingRecordByIds(Long[] ids) {
        // 先删除关联的羔羊详情
        for (Long id : ids) {
            scLambDetailMapper.deleteScLambDetailByLambingRecordId(id);
        }
        // 再删除产羔记录
        return scLambingRecordMapper.deleteScLambingRecordByIds(ids);
    }

    /**
     * 删除产羔记录信息
     */
    @Override
    @Transactional
    public int deleteScLambingRecordById(Long id) {
        // 先删除关联的羔羊详情
        scLambDetailMapper.deleteScLambDetailByLambingRecordId(id);
        // 再删除产羔记录
        return scLambingRecordMapper.deleteScLambingRecordById(id);
    }

    /**
     * 查询产羔记录基础信息
     */
    @Override
    public ScLambingRecord selectScLambingRecordById(Long id) {
        return scLambingRecordMapper.selectScLambingRecordById(id);
    }

    /**
     * 查询产羔记录详细信息（包含关联信息）- 新增方法
     * 用于修改时获取完整的产羔记录信息，包括母羊耳号、公羊耳号、配种日期等关联字段
     */
    @Override
    public ScLambingRecord selectScLambingRecordDetailById(Long id) {
        return scLambingRecordMapper.selectScLambingRecordDetailById(id);
    }

    /**
     * 查询羔羊详情
     */
    @Override
    public List<ScLambDetail> selectLambDetailByLambingRecordId(Long lambingRecordId) {
        return scLambDetailMapper.selectScLambDetailByLambingRecordId(lambingRecordId);
    }
}