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

import java.util.List;
import java.util.Map;
import com.zhyc.common.utils.DateUtils;
import com.zhyc.common.utils.bean.BeanUtils;
import com.zhyc.module.biosafety.domain.Diagnosis;
import com.zhyc.module.biosafety.domain.Treatment;
import com.zhyc.module.biosafety.mapper.DiagnosisMapper;
import com.zhyc.module.biosafety.mapper.TreatmentMapper;
import com.zhyc.module.biosafety.service.impl.TreatmentServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zhyc.module.produce.breed.mapper.ScSheepDeathMapper;
import com.zhyc.module.produce.breed.domain.ScSheepDeath;
import com.zhyc.module.produce.breed.service.IScSheepDeathService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 羊只死淘记录Service业务层处理
 *
 * @author ruoyi
 * @date 2025-08-06
 */
@Service
public class ScSheepDeathServiceImpl implements IScSheepDeathService
{
    @Autowired
    private ScSheepDeathMapper scSheepDeathMapper;
    @Autowired
    private DiagnosisMapper diagnosisMapper;
    @Autowired
    private TreatmentServiceImpl treatmentService;

    @Override
    public ScSheepDeath selectScSheepDeathById(Long id)
    {
        return scSheepDeathMapper.selectScSheepDeathById(id);
    }

    @Override
    public List<ScSheepDeath> selectScSheepDeathList(ScSheepDeath scSheepDeath)
    {
        return scSheepDeathMapper.selectScSheepDeathList(scSheepDeath);
    }

    @Override
    public Map<String, Object> selectSheepFileByManageTags(String manageTags)
    {
        return scSheepDeathMapper.selectSheepFileByManageTags(manageTags);
    }

    @Override
    @Transactional
    public int insertScSheepDeath(ScSheepDeath scSheepDeath)
    {
        String manageTagsInput = scSheepDeath.getManageTags();
        if (manageTagsInput == null || manageTagsInput.trim().isEmpty()) {
            return 0;
        }

        // 支持空格、逗号分隔
        String[] tags = manageTagsInput.split("[\\s,，]+");
        int successCount = 0;

        for (String tag : tags) {
            if (tag == null || tag.trim().isEmpty()) {
                continue;
            }

            ScSheepDeath newRecord = new ScSheepDeath();
            BeanUtils.copyProperties(scSheepDeath, newRecord);
            newRecord.setManageTags(tag.trim());
            newRecord.setId(null);

            if (newRecord.getEventType() == null || newRecord.getEventType().isEmpty()) {
                newRecord.setEventType("死亡");
            }

            Map<String, Object> sheepInfo = selectSheepFileByManageTags(newRecord.getManageTags());
            if (sheepInfo != null) {
                Long sheepId = sheepInfo.get("sheepId") != null ? Long.valueOf(sheepInfo.get("sheepId").toString()) : null;
                newRecord.setSheepId(sheepId);

                // 插入死淘记录后，同时更新羊只在群状态为"不在群"（状态ID为2）
                if (sheepId != null) {
                    scSheepDeathMapper.updateSheepStatus(sheepId, "2");
                    treatmentService.updateTreatmentStatus(sheepId);
                }
            }

            newRecord.setCreateTime(DateUtils.getNowDate());
            successCount += scSheepDeathMapper.insertScSheepDeath(newRecord);
        }
        return successCount;
    }

    @Override
    public int updateScSheepDeath(ScSheepDeath scSheepDeath)
    {
        // 如果管理耳号发生变化，重新查询并设置羊只ID
        if (scSheepDeath.getManageTags() != null && !scSheepDeath.getManageTags().isEmpty()) {
            Map<String, Object> sheepInfo = selectSheepFileByManageTags(scSheepDeath.getManageTags());
            if (sheepInfo != null) {
                Long sheepId = sheepInfo.get("sheepId") != null ? Long.valueOf(sheepInfo.get("sheepId").toString()) : null;
                scSheepDeath.setSheepId(sheepId);

                // 修改死淘记录时，同时更新羊只在群状态为"不在群"（状态ID为2）
                if (sheepId != null) {
                    scSheepDeathMapper.updateSheepStatus(sheepId, "2");
                }
            }
        }
        scSheepDeath.setUpdateTime(DateUtils.getNowDate());
        return scSheepDeathMapper.updateScSheepDeath(scSheepDeath);
    }

    @Override
    public int deleteScSheepDeathByIds(Long[] ids)
    {
        // 删除死淘记录前，将对应羊只在群状态改回"在群"
        for (Long id : ids) {
            ScSheepDeath scSheepDeath = scSheepDeathMapper.selectScSheepDeathById(id);
            if (scSheepDeath != null && scSheepDeath.getSheepId() != null) {
                // 恢复羊只在群状态为"在群"（状态ID为1）
                scSheepDeathMapper.updateSheepStatus(scSheepDeath.getSheepId(), "1");
            }
        }

        return scSheepDeathMapper.deleteScSheepDeathByIds(ids);
    }

    @Override
    public int deleteScSheepDeathById(Long id)
    {
        // 删除死淘记录前，将对应羊只在群状态改回"在群"
        ScSheepDeath scSheepDeath = scSheepDeathMapper.selectScSheepDeathById(id);
        if (scSheepDeath != null && scSheepDeath.getSheepId() != null) {
            // 恢复羊只在群状态为"在群"（状态ID为1）
            scSheepDeathMapper.updateSheepStatus(scSheepDeath.getSheepId(), "1");
        }

        return scSheepDeathMapper.deleteScSheepDeathById(id);
    }

    // --- 远程搜索实现 ---
    @Override
    public List<String> selectDistinctManageTags(String query) {
        return scSheepDeathMapper.selectDistinctManageTags(query);
    }

    @Override
    public List<String> selectDistinctTechnician(String query) {
        return scSheepDeathMapper.selectDistinctTechnician(query);
    }

    @Override
    public List<String> selectDistinctHandler(String query) {
        return scSheepDeathMapper.selectDistinctHandler(query);
    }
}