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

import java.util.ArrayList;
import java.util.List;

import com.zhyc.common.annotation.DataScope;
import com.zhyc.common.utils.DateUtils;
import com.zhyc.common.utils.SecurityUtils;
import com.zhyc.common.utils.bean.BeanUtils;
import com.zhyc.module.Exception.BusinessException;
import com.zhyc.module.base.domain.SheepFile;
import com.zhyc.module.base.mapper.SheepFileMapper;
import com.zhyc.module.biosafety.domain.Diagnosis;
import com.zhyc.module.biosafety.domain.SwMedicineUsage;
import com.zhyc.module.biosafety.domain.SwMedicineUsageDetails;
import com.zhyc.module.biosafety.mapper.DiagnosisMapper;
import com.zhyc.module.biosafety.mapper.SwMedicineUsageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zhyc.module.biosafety.mapper.TreatmentMapper;
import com.zhyc.module.biosafety.domain.Treatment;
import com.zhyc.module.biosafety.service.ITreatmentService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 治疗记录Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-07-15
 */
@Service
public class TreatmentServiceImpl implements ITreatmentService 
{
    @Autowired
    private TreatmentMapper treatmentMapper;
    @Autowired
    private SwMedicineUsageServiceImpl medicineUsageService;
    @Autowired
    private SwMedicineUsageMapper medicineUsageMapper;
    @Autowired
    private SheepFileMapper sheepFileMapper;
    @Autowired
    private DiagnosisMapper diagnosisMapper;

    /**
     * 查询治疗记录
     * 
     * @param id 治疗记录主键
     * @return 治疗记录
     */
    @Override
    public Treatment selectTreatmentById(Long id)
    {
        Treatment treatment = treatmentMapper.selectTreatmentById(id);
//        获取药品使用记录
        SwMedicineUsage swMedicineUsage = medicineUsageService.selectSwMedicineUsageById(treatment.getUsageId());
        if (swMedicineUsage!=null){
            treatment.setUsageDetails(swMedicineUsage.getSwMedicineUsageDetailsList());
        }
        return treatment;
    }

    /**
     * 查询治疗记录列表
     * 
     * @param treatment 治疗记录
     * @return 治疗记录
     */
    @Override
    @DataScope(deptAlias = "t", userAlias = "t")
    public List<Treatment> selectTreatmentList(Treatment treatment)
    {
        String[] sheepNos = null;
        if (treatment.getSheepNo() != null && !treatment.getSheepNo().isEmpty()) {
            if (treatment.getSheepNo().contains(",")) {
                sheepNos = treatment.getSheepNo().split(",");
            } else {
                sheepNos = new String[]{treatment.getSheepNo()};
            }
        }
        treatment.setSheepNos(sheepNos);
        return treatmentMapper.selectTreatmentList(treatment);
    }

    /**
     * 新增治疗记录
     *
     * @param treatment 治疗记录
     * @return 结果
     */
    @Override
    @Transactional
    public int insertTreatment(Treatment treatment) {
        String username = SecurityUtils.getLoginUser().getUser().getNickName();

        // 药品使用记录公共字段
        SwMedicineUsage medicineUsage = new SwMedicineUsage();
        medicineUsage.setSwMedicineUsageDetailsList(treatment.getUsageDetails());
        medicineUsage.setName("羊只治疗");
        medicineUsage.setUseType("4");
        medicineUsage.setDatetime(treatment.getDatetime());
        medicineUsage.setCreateBy(username);
        medicineUsage.setCreateTime(DateUtils.getNowDate());

        /* ---------------- 单只插入 ---------------- */
        if (treatment.getSheepId() != null) {
            // 1. 重复校验
            Treatment query = new Treatment();
            query.setDiseaseId(treatment.getDiseaseId());
            query.setDiseasePid(treatment.getDiseasePid());
            query.setSheepId(treatment.getSheepId());
            query.setStatus("0");



            // 2. 羊只档案信息
            SheepFile sheepFile = sheepFileMapper.selectSheepFileById(treatment.getSheepId());

            if (!treatmentMapper.selectTreatmentList(query).isEmpty()) {
                throw new BusinessException("该羊只已存在相同疾病的治疗记录，不能重复添加");
            }
            // 3. 保存药品使用记录
            medicineUsage.setSheepId(Math.toIntExact(treatment.getSheepId()));
            Integer usageId = medicineUsageService.insertSwMedicineUsage(medicineUsage);

            // 4. 组装治疗记录
            treatment.setUsageId(usageId);
            treatment.setCreateTime(DateUtils.getNowDate());
            treatment.setVariety(sheepFile.getVariety());
            treatment.setSheepType(sheepFile.getName());
            treatment.setMonthAge(sheepFile.getMonthAge());
            treatment.setGender(String.valueOf(sheepFile.getGender()));
            treatment.setBreed(sheepFile.getBreed());
            treatment.setParity(sheepFile.getParity());
            treatment.setLactDay(sheepFile.getLactationDay());
            treatment.setGestDay(sheepFile.getGestationDay());

            // 5. 插入
            return treatmentMapper.insertTreatment(treatment);
        }

        /* ---------------- 批量插入 ---------------- */
        // 1. 收集所有重复耳号
        List<String> duplicateSheepIds = new ArrayList<>();
        for (String sheepId : treatment.getSheepIds()) {
            Treatment query = new Treatment();
            query.setDiseaseId(treatment.getDiseaseId());
            query.setDiseasePid(treatment.getDiseasePid());
            query.setSheepId(Long.valueOf(sheepId));
            query.setStatus("0");

            if (!treatmentMapper.selectTreatmentList(query).isEmpty()) {
                String bsManageTags = sheepFileMapper.selectSheepFileById(Long.valueOf(sheepId)).getBsManageTags();
                duplicateSheepIds.add(bsManageTags);
            }
        }

        // 2. 存在重复则一次性提示
        if (!duplicateSheepIds.isEmpty()) {

            throw new BusinessException("以下耳号已存在相同疾病记录，无法添加：" + String.join("、", duplicateSheepIds));
        }

        // 3. 全部合法，开始批量组装
        List<Treatment> treatments = new ArrayList<>();
        treatment.setCreateTime(DateUtils.getNowDate());

        for (String sheepId : treatment.getSheepIds()) {
            SheepFile sheepFile = sheepFileMapper.selectSheepFileById(Long.valueOf(sheepId));

            Treatment treat = new Treatment();
            BeanUtils.copyProperties(treatment, treat);

            treat.setSheepId(Long.valueOf(sheepId));
            treat.setVariety(sheepFile.getVariety());
            treat.setSheepType(sheepFile.getName());
            treat.setMonthAge(sheepFile.getMonthAge());
            treat.setGender(String.valueOf(sheepFile.getGender()));
            treat.setBreed(sheepFile.getBreed());
            treat.setParity(sheepFile.getParity());
            treat.setLactDay(sheepFile.getLactationDay());
            treat.setGestDay(sheepFile.getGestationDay());

            // 药品使用记录
            medicineUsage.setSheepId(Integer.valueOf(sheepId));
            Integer usageId = medicineUsageService.insertSwMedicineUsage(medicineUsage);
            treat.setUsageId(usageId);

            treatments.add(treat);
        }

        // 4. 批量插入
        return treatmentMapper.insertTreatmentList(treatments);
    }
    /**
     * 修改治疗记录
     * 
     * @param treatment 治疗记录
     * @return 结果
     */
    @Override
    @Transactional
    public int updateTreatment(Treatment treatment)
    {
        String username = SecurityUtils.getLoginUser().getUser().getNickName();
        for (SwMedicineUsageDetails usageDetail : treatment.getUsageDetails()) {
            usageDetail.setMediUsage(treatment.getUsageId());
        }
        medicineUsageMapper.deleteSwMedicineUsageDetailsByMediUsage(treatment.getUsageId());
        SwMedicineUsage swMedicineUsage = new SwMedicineUsage();
        swMedicineUsage.setId(treatment.getUsageId());
        swMedicineUsage.setUpdateBy(username);
        medicineUsageMapper.updateSwMedicineUsage(swMedicineUsage);
        if (!treatment.getUsageDetails().isEmpty() || treatment.getUsageDetails().size() != 0){
            medicineUsageMapper.batchSwMedicineUsageDetails(treatment.getUsageDetails());
        }
        treatment.setUpdateBy(username);
        treatment.setUpdateTime(DateUtils.getNowDate());
        return treatmentMapper.updateTreatment(treatment);
    }

    /**
     * 批量删除治疗记录
     * 
     * @param ids 需要删除的治疗记录主键
     * @return 结果
     */
    @Override
    public int deleteTreatmentByIds(Long[] ids)
    {
        return treatmentMapper.deleteTreatmentByIds(ids);
    }

    /**
     * 删除治疗记录信息
     * 
     * @param id 治疗记录主键
     * @return 结果
     */
    @Override
    public int deleteTreatmentById(Long id)
    {
        return treatmentMapper.deleteTreatmentById(id);
    }

    public void updateTreatmentStatus(Long sheepId) {
        List<Treatment>  treatments=treatmentMapper.selectTreatmentStatus(sheepId);
        Diagnosis diagnosis = new Diagnosis();
        for (Treatment treatment : treatments) {
            if (treatment.getDiagId()!=null){
                diagnosis.setId(treatment.getDiagId());
                diagnosis.setResult("-1");
                diagnosisMapper.updateDiagnosis(diagnosis);
                if (treatment.getDiagId()!=null){
                    Treatment treat = new Treatment();
                    treat.setId(treatment.getId());
                    treatmentMapper.updateTreatment(treat);
                }
            }
        }
    }
}
