package com.ruoyi.inventory.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.inventory.domain.HealthcareDrugArchive;
import com.ruoyi.inventory.domain.HealthcareDrugFiling;
import com.ruoyi.inventory.domain.HealthcareInventoryStoreroom;
import com.ruoyi.inventory.domain.charVo;
import com.ruoyi.inventory.mapper.HealthcareDrugArchiveMapper;
import com.ruoyi.inventory.mapper.HealthcareDrugFilingMapper;
import com.ruoyi.inventory.service.IHealthcareDrugArchiveService;
import com.ruoyi.inventory.service.IHealthcareDrugFilingService;
import com.ruoyi.inventory.service.IHealthcareInventoryStoreroomService;

/**
 * 药品档案Service业务层处理
 *
 * @author 蒋松霖
 * @date 2024-09-19
 */
@Service
public class HealthcareDrugArchiveServiceImpl implements IHealthcareDrugArchiveService {

    @Autowired
    private HealthcareDrugArchiveMapper healthcareDrugArchiveMapper;
    @Autowired
    private HealthcareDrugFilingMapper healthcareDrugFilingMapper;

    @Autowired
    private IHealthcareDrugFilingService healthcareDrugFilingService;
    @Autowired
    private IHealthcareInventoryStoreroomService healthcareInventoryStoreroomService;

    /**
     * 查询药品档案
     *
     * @param id 药品档案主键
     * @return 药品档案
     */
    @Override
    public HealthcareDrugArchive selectHealthcareDrugArchiveById(Long id) {
        return healthcareDrugArchiveMapper.selectHealthcareDrugArchiveById(id);
    }

    @Override
    public List<HealthcareDrugArchive> selectHealthcareDrugArchiveByBarcode(String Barcode) {
        return healthcareDrugArchiveMapper.selectHealthcareDrugArchiveByBarcode(Barcode);
    }

    /**
     * 查询药品档案列表
     *
     * @param healthcareDrugArchive 药品档案
     * @return 药品档案列表
     */
    @Override
    public List<HealthcareDrugArchive> selectHealthcareDrugArchiveList(HealthcareDrugArchive healthcareDrugArchive) {
        List<HealthcareDrugArchive> list = healthcareDrugArchiveMapper
                .selectHealthcareDrugArchiveList(healthcareDrugArchive);

        // 遍历每个 HealthCareDrugArchive 对象
        list.forEach(item -> {
            // 根据 HealthCareDrugArchive 的 ID 查询关联的 HealthCareDrugFiling 列表
            List<HealthcareDrugFiling> filings = healthcareDrugFilingService
                    .selectHealthcareDrugFilingByArchiveId(item.getId());
            // 将 packageUnit 和 splitUnit 复制到每个 filing 对象中
            filings.forEach(filing -> {
                filing.setPackageUnit(item.getPackageUnit());
                filing.setSplitUnit(item.getSplitUnit());
                filing.setMedicineName(item.getMedicineName());
                filing.setSpecification(item.getSpecification());
                filing.setBarcode(item.getBarcode());
                filing.setManufacturer(item.getManufacturer());
                HealthcareInventoryStoreroom storeroom = healthcareInventoryStoreroomService
                        .selectHealthcareInventoryStoreroomById(filing.getStoreroomId()); // 设置相对应的库房
                filing.setStoreroomName(storeroom.getStoreroomName());
            });
            // 将 HealthCareDrugFiling 列表设置到 HealthCareDrugArchive 里面的 drugFilings 对象中
            item.setDrugFilings(filings);
        });

        return list;
    }

    /**
     * 新增药品档案
     *
     * @param healthcareDrugArchive 药品档案
     * @return 结果
     */
    @Override
    public int insertHealthcareDrugArchive(HealthcareDrugArchive healthcareDrugArchive) {
        healthcareDrugArchive.setCreateTime(DateUtils.getNowDate());
        return healthcareDrugArchiveMapper.insertHealthcareDrugArchive(healthcareDrugArchive);
    }

    /**
     * 修改药品档案
     *
     * @param healthcareDrugArchive 药品档案
     * @return 结果
     */
    @Override
    public int updateHealthcareDrugArchive(HealthcareDrugArchive healthcareDrugArchive) {
        healthcareDrugArchive.setUpdateTime(DateUtils.getNowDate());

        // 获取与药品档案关联的药品备案信息
        List<HealthcareDrugFiling> filings = healthcareDrugFilingService
                .selectHealthcareDrugFilingByArchiveId(healthcareDrugArchive.getId());
        if (filings != null && !filings.isEmpty()) {
            for (HealthcareDrugFiling filing : filings) {
                try {
                    // 确保 minNumber 不为零
                    String minNumber = healthcareDrugArchive.getMinNumber();
                    if (minNumber == null) {
                        throw new IllegalArgumentException("Minimum number cannot be zero");
                    }

                    // 使用 BigDecimal 进行精确计算
                    BigDecimal retailPrice = BigDecimal.valueOf(filing.getRetailPrice());
                    BigDecimal minNumberBD = BigDecimal.valueOf(Long.parseLong(minNumber));

                    // 计算新的最小单位价格
                    BigDecimal newMinPrice = retailPrice.divide(minNumberBD, 2, RoundingMode.CEILING);

                    // 前端传来参数可拆分则设置包数默认值为0
                    if (healthcareDrugArchive.getIsSplit().equals("Y")) {
                        // 获取数据库中的包数判断是否重置为0
                        List<HealthcareDrugFiling> filing1 = healthcareDrugFilingService
                                .selectHealthcareDrugFilingByArchiveId(healthcareDrugArchive.getId());
                        for (HealthcareDrugFiling item : filing1) {
                            if (item.getPackCount() == null) { // 当前药品的包数为null的时候才默认为0
                                filing.setPackCount(0);
                            }
                        }
                    }
                    // 更新药品备案信息
                    filing.setMinPrice(newMinPrice.doubleValue());
                    healthcareDrugFilingService.updateHealthcareDrugFiling(filing);
                } catch (IllegalArgumentException e) {
                    // 处理除零错误
                    continue;
                } catch (ArithmeticException e) {
                    // 处理除法运算中的其他错误
                    continue;
                } catch (Exception e) {
                    // 处理其他意外错误
                    continue;
                }
            }
        }

        try {
            return healthcareDrugArchiveMapper.updateHealthcareDrugArchive(healthcareDrugArchive);
        } catch (Exception e) {
            // 处理更新药品档案时的错误
            throw new RuntimeException("Failed to update healthcare drug archive", e);
        }
    }

    /**
     * 批量删除药品档案
     *
     * @param ids 需要删除的药品档案主键
     * @return 结果
     */
    @Override
    public int deleteHealthcareDrugArchiveByIds(Long[] ids) {
        healthcareDrugFilingService.deleteHealthcareDrugArchiveByIds(ids);
        return healthcareDrugArchiveMapper.deleteHealthcareDrugArchiveByIds(ids);
    }

    /**
     * 删除药品档案信息
     *
     * @param id 药品档案主键
     * @return 结果
     */
    @Override
    public int deleteHealthcareDrugArchiveById(Long id) {
        return healthcareDrugArchiveMapper.deleteHealthcareDrugArchiveById(id);
    }

    /**
     * 批量新增药品档案
     *
     * @param archiveList
     * @return 结果
     */
    @Override
    public int insertHealthcareDrugArchives(List<HealthcareDrugArchive> archiveList) {
        // 判断导入的excel药品建档是否已存在数据库
        for (HealthcareDrugArchive item : archiveList) {
            List<HealthcareDrugArchive> archive = healthcareDrugArchiveMapper
                    .selectHealthcareDrugArchiveByBarcode(item.getBarcode());
            if (archive == null && archive.isEmpty()) {
                healthcareDrugArchiveMapper.insertHealthcareDrugArchives(archiveList);
            }
        }
        return archiveList.size();
    }

    @Override
    public charVo selectcharMedicine(Date startDate, Date endDate) {
        charVo charMedicin = new charVo();

        // 库房药品统计
        Integer countMedicine = healthcareDrugArchiveMapper.selectcountMedicine(startDate, endDate);
        charMedicin.setCountMedicine(countMedicine == null ? 0 : countMedicine);

        // 药品金额统计
        Integer countAmount = healthcareDrugFilingMapper.selectcountAmount(startDate, endDate);
        charMedicin.setCountAmount(countAmount == null ? 0 : countAmount);

        // 临期药品统计
        Integer countAdvent = healthcareDrugFilingMapper.selectcountAdvent(startDate, endDate);
        charMedicin.setCountAdvent(countAdvent == null ? 0 : countAdvent);

        // 库存预警统计
        Integer countAlerts = healthcareDrugFilingMapper.selectcountAlerts(startDate, endDate);
        charMedicin.setCountAlerts(countAlerts == null ? 0 : countAlerts);

        return charMedicin;
    }

    @Override
    public List<HealthcareDrugArchive> selectHealthcareDrugArchiveAdevntList(
            HealthcareDrugArchive healthcareDrugArchive) {
        List<HealthcareDrugArchive> list = healthcareDrugArchiveMapper
                .selectHealthcareDrugArchiveAdevntList(healthcareDrugArchive);

        // 遍历每个 HealthCareDrugArchive 对象
        list.forEach(item -> {
            // 根据 HealthCareDrugArchive 的 ID 查询关联的 HealthCareDrugFiling 列表
            List<HealthcareDrugFiling> filings = healthcareDrugFilingService
                    .selectHealthcareDrugFilingByArchiveId(item.getId());

            // 获取当前日期加上一个月的日期
            Calendar currentPlusOneMonth = Calendar.getInstance();
            currentPlusOneMonth.add(Calendar.MONTH, 1);
            Date currentDatePlusOneMonth = currentPlusOneMonth.getTime();

            // 过滤有效期至当前日期少于一个月的药品库存
            List<HealthcareDrugFiling> validFilings = filings.stream()
                    .filter(filing -> filing.getExpiryDate().before(currentDatePlusOneMonth))
                    .collect(Collectors.toList());

            // 将 packageUnit 和 splitUnit 复制到每个 filing 对象中
            validFilings.forEach(filing -> {
                filing.setPackageUnit(item.getPackageUnit());
                filing.setSplitUnit(item.getSplitUnit());
                filing.setMedicineName(item.getMedicineName());
                filing.setSpecification(item.getSpecification());
                filing.setBarcode(item.getBarcode());
                filing.setManufacturer(item.getManufacturer());

                // 设置相对应的库房
                HealthcareInventoryStoreroom storeroom = healthcareInventoryStoreroomService
                        .selectHealthcareInventoryStoreroomById(filing.getStoreroomId());
                filing.setStoreroomName(storeroom.getStoreroomName());
            });

            // 将 HealthCareDrugFiling 列表设置到 HealthCareDrugArchive 里面的 drugFilings 对象中
            item.setDrugFilings(validFilings);
        });

        return list;
    }

    @Override
    public List<HealthcareDrugArchive> selectHealthcareDrugArchiveAertsList(
            HealthcareDrugArchive healthcareDrugArchive) {
        List<HealthcareDrugArchive> list = healthcareDrugArchiveMapper
                .selectHealthcareDrugArchiveAertsList(healthcareDrugArchive);
        // 遍历每个 HealthCareDrugArchive 对象
        list.forEach(item -> {
            // 根据 HealthCareDrugArchive 的 ID 查询关联的 HealthCareDrugFiling 列表
            List<HealthcareDrugFiling> filings = healthcareDrugFilingService
                    .selectHealthcareDrugFilingByArchiveId(item.getId());
            // 将 packageUnit 和 splitUnit 复制到每个 filing 对象中
            filings.forEach(filing -> {
                filing.setPackageUnit(item.getPackageUnit());
                filing.setSplitUnit(item.getSplitUnit());
                filing.setMedicineName(item.getMedicineName());
                filing.setSpecification(item.getSpecification());
                filing.setBarcode(item.getBarcode());
                filing.setManufacturer(item.getManufacturer());
                HealthcareInventoryStoreroom storeroom = healthcareInventoryStoreroomService
                        .selectHealthcareInventoryStoreroomById(filing.getStoreroomId()); // 设置相对应的库房
                filing.setStoreroomName(storeroom.getStoreroomName());
            });
            // 将 HealthCareDrugFiling 列表设置到 HealthCareDrugArchive 里面的 drugFilings 对象中
            item.setDrugFilings(filings);
        });

        return list;
    }

}
