package com.ruoyi.inventory.service.impl;

import java.text.SimpleDateFormat;
import java.util.*;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.inventory.domain.*;
import com.ruoyi.inventory.service.IHealthcareDrugArchiveService;
import com.ruoyi.inventory.service.IHealthcareDrugFilingService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.inventory.mapper.HealthcareInventoryDrugentryMapper;
import com.ruoyi.inventory.service.IHealthcareInventoryDrugentryService;

import static com.github.pagehelper.page.PageMethod.startPage;

/**
 * 药品入库记录Service业务层处理
 *
 * @author 蒋松霖
 * @date 2024-09-27
 */
@Service
public class HealthcareInventoryDrugentryServiceImpl implements IHealthcareInventoryDrugentryService
{
    @Autowired
    private HealthcareInventoryDrugentryMapper healthcareInventoryDrugentryMapper;

    @Autowired
    private IHealthcareDrugFilingService healthcareDrugFilingService;

    @Autowired
    private IHealthcareDrugArchiveService healthcareDrugArchiveService;
    /**
     * 查询药品入库记录
     *
     * @param id 药品入库记录主键
     * @return 药品入库记录
     */
    @Override
    public AjaxResult selectHealthcareInventoryDrugentryById(Long id)
    {

        HealthcareInventoryDrugentry drugentry = healthcareInventoryDrugentryMapper.selectHealthcareInventoryDrugentryById(id);

        // 获取入库记录药品档案详细信息

        List<HealthcareInventoryDrugentryDetails> details = drugentry.getHealthcareInventoryDrugentryDetailsList();
        if (!details.isEmpty()) {

            details.forEach(item -> {
                HealthcareDrugArchive archive = healthcareDrugArchiveService.selectHealthcareDrugArchiveById(item.getDrugArchiveId());
                if (archive != null) {
                    item.setDrugArchiveId(archive.getId());
                    item.setMedicineName(archive.getMedicineName());
                    item.setBarcode(archive.getBarcode());
                    item.setManufacturer(archive.getManufacturer());
                }
            });
        }

        return AjaxResult.success(drugentry);
    }

    /**
     * 查询药品入库记录列表
     *
     * @param healthcareInventoryDrugentry 药品入库记录
     * @return 药品入库记录
     */
    @Override
    public List<HealthcareInventoryDrugentry> selectHealthcareInventoryDrugentryList(HealthcareInventoryDrugentry healthcareInventoryDrugentry)
    {

        return healthcareInventoryDrugentryMapper.selectHealthcareInventoryDrugentryList(healthcareInventoryDrugentry);
    }



    //定义一个方法用来生成入库记录单号
    private String generateOrderNo(){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); //获取当前时间年月日时分秒
        String currentDataTime = simpleDateFormat.format(new Date());
        Random rd = new Random();
        int rdNumber = rd.nextInt(9000)+1000; // 获取四位随机数
        return currentDataTime+rdNumber;
    };

    /**
     * 新增药品入库记录
     *
     * @param healthcareInventoryDrugentry 药品入库记录
     * @return 结果
     */
    @Transactional
    @Override
    public int insertHealthcareInventoryDrugentry(HealthcareInventoryDrugentry healthcareInventoryDrugentry)
    {

        healthcareInventoryDrugentry.setCreateTime(DateUtils.getNowDate());
        healthcareInventoryDrugentry.setStatus(0); //已完成
        // 调用generateOrderNo（）生成单号
        String orderNo = generateOrderNo();
        healthcareInventoryDrugentry.setOrderNumber(orderNo);

        // 获取当前登录用户的信息并插入
        String currentUser = SecurityUtils.getUsername();
        healthcareInventoryDrugentry.setEntryPerson(currentUser);
        // 根据前端传来的入库数量做增加库存操作
         // 查找需要增加的库存，注意：不同的档案可能会有相同的批次号码，所以需要先找出当前的药品档案，然后在往里面找需要累加的库存批次
        List<HealthcareInventoryDrugentryDetails> details = healthcareInventoryDrugentry.getHealthcareInventoryDrugentryDetailsList();
        // 检查批次号码是否重复
        Set<String> batchNumbers = new HashSet<>();
        for (HealthcareInventoryDrugentryDetails item : details) {
            if (!batchNumbers.add(item.getBatch())) {
                throw new RuntimeException("批次号码重复！");
            }
        }
        for (HealthcareInventoryDrugentryDetails item : details){
            HealthcareDrugFiling filing = healthcareDrugFilingService.selectHealthcareDrugFilingById(item.getDrugFilingId());
            if (filing != null){
                filing.setBoxCount(filing.getBoxCount() + item.getQuantity());
                healthcareDrugFilingService.updateHealthcareDrugFiling(filing);
            }else {
                // // 检查该批次号码是否已经存在于同一个卫生所中
                HealthcareDrugFiling filing2 = new HealthcareDrugFiling();
                filing2.setStoreroomId(item.getStoreroomId());
                filing2.setBatch(item.getBatch());
                HealthcareDrugFiling isBatch = healthcareDrugFilingService.findByBatchAndStoreroomId(filing2);
                if (isBatch != null){
                    if (isBatch != null) {
                        throw new RuntimeException("该卫生所已存在相同批次号码");
                    }
                }else {
                    HealthcareDrugFiling filing1 = new HealthcareDrugFiling();
                    filing1.setBoxCount(item.getQuantity());
                    filing1.setArchiveId(item.getDrugArchiveId());
                    filing1.setBatch(item.getBatch());
                    filing1.setExpiryDate(item.getExpiryDate());
                    filing1.setRetailPrice(item.getPrice());
                    filing1.setStoreroomId(item.getStoreroomId());
                    healthcareDrugFilingService.insertHealthcareDrugFiling(filing1);
                }
;
            }
        }
        int rows = healthcareInventoryDrugentryMapper.insertHealthcareInventoryDrugentry(healthcareInventoryDrugentry);
        insertHealthcareInventoryDrugentryDetails(healthcareInventoryDrugentry);
        return rows;
    }

    /**
     * 修改药品入库记录
     *
     * @param healthcareInventoryDrugentry 药品入库记录
     * @return 结果
     */
    @Transactional
    @Override
    public int updateHealthcareInventoryDrugentry(HealthcareInventoryDrugentry healthcareInventoryDrugentry)
    {
        healthcareInventoryDrugentry.setStatus(0); // 已完成
        healthcareInventoryDrugentry.setUpdateTime(DateUtils.getNowDate());
        // 根据前端传来的入库数量做增加库存操作
        // 查找需要增加的库存，注意：不同的档案可能会有相同的批次号码，所以需要先找出当前的药品档案，然后在往里面找需要累加的库存批次
        List<HealthcareInventoryDrugentryDetails> details = healthcareInventoryDrugentry.getHealthcareInventoryDrugentryDetailsList();
        // 检查批次号码是否重复
        Set<String> batchNumbers = new HashSet<>();
        for (HealthcareInventoryDrugentryDetails item : details) {
            if (!batchNumbers.add(item.getBatch())) {
                throw new RuntimeException("批次号码重复！");
            }
        }
        for (HealthcareInventoryDrugentryDetails item : details){
            HealthcareDrugFiling filing = healthcareDrugFilingService.selectHealthcareDrugFilingById(item.getDrugFilingId());
            if (filing != null){
                filing.setBoxCount(filing.getBoxCount() + item.getQuantity());
                healthcareDrugFilingService.updateHealthcareDrugFiling(filing);
            }else {
                HealthcareDrugFiling filing1 = new HealthcareDrugFiling();
                filing1.setBoxCount(item.getQuantity());
                filing1.setArchiveId(item.getDrugArchiveId());
                filing1.setBatch(item.getBatch());
                filing1.setExpiryDate(item.getExpiryDate());
                filing1.setRetailPrice(item.getPrice());
                filing1.setStoreroomId(item.getStoreroomId());
                healthcareDrugFilingService.insertHealthcareDrugFiling(filing1);
            }
        }
        healthcareInventoryDrugentryMapper.deleteHealthcareInventoryDrugentryDetailsByEntryRecordId(healthcareInventoryDrugentry.getId());
        insertHealthcareInventoryDrugentryDetails(healthcareInventoryDrugentry);
        return healthcareInventoryDrugentryMapper.updateHealthcareInventoryDrugentry(healthcareInventoryDrugentry);
    }

    /**
     * 批量删除药品入库记录
     *
     * @param ids 需要删除的药品入库记录主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteHealthcareInventoryDrugentryByIds(Long[] ids)
    {
        healthcareInventoryDrugentryMapper.deleteHealthcareInventoryDrugentryDetailsByEntryRecordIds(ids);
        return healthcareInventoryDrugentryMapper.deleteHealthcareInventoryDrugentryByIds(ids);
    }

    /**
     * 删除药品入库记录信息
     *
     * @param id 药品入库记录主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteHealthcareInventoryDrugentryById(Long id)
    {
        healthcareInventoryDrugentryMapper.deleteHealthcareInventoryDrugentryDetailsByEntryRecordId(id);
        return healthcareInventoryDrugentryMapper.deleteHealthcareInventoryDrugentryById(id);
    }

    @Override
    public int saveHealthcareInventoryDrugentry(HealthcareInventoryDrugentry healthcareInventoryDrugentry) {
        if (healthcareInventoryDrugentry.getId() == null){
            healthcareInventoryDrugentry.setStatus(1); // 未完成
            // 调用generateOrderNo（）生成单号
            String orderNo = generateOrderNo();
            healthcareInventoryDrugentry.setOrderNumber(orderNo); // 生成单号
            // 插入当前用户
            // 获取当前登录用户的信息并插入
            String currentUser = SecurityUtils.getUsername();
            healthcareInventoryDrugentry.setEntryPerson(currentUser);
            // 插入当前时间
            healthcareInventoryDrugentry.setCreateTime(DateUtils.getNowDate());
            int rows = healthcareInventoryDrugentryMapper.insertHealthcareInventoryDrugentry(healthcareInventoryDrugentry);
            insertHealthcareInventoryDrugentryDetails(healthcareInventoryDrugentry);
            return rows;
        }else {
            healthcareInventoryDrugentry.setUpdateTime(DateUtils.getNowDate());
            healthcareInventoryDrugentryMapper.deleteHealthcareInventoryDrugentryDetailsByEntryRecordId(healthcareInventoryDrugentry.getId());
            insertHealthcareInventoryDrugentryDetails(healthcareInventoryDrugentry);
           return healthcareInventoryDrugentryMapper.updateHealthcareInventoryDrugentry(healthcareInventoryDrugentry);
        }
    }


    /**
     * 新增入库详情，用于记录药品入库的详细信息
     *
     * @param healthcareInventoryDrugentry 药品入库记录对象
     */
    public void insertHealthcareInventoryDrugentryDetails(HealthcareInventoryDrugentry healthcareInventoryDrugentry) {
        List<HealthcareInventoryDrugentryDetails> healthcareInventoryDrugentryDetailsList = healthcareInventoryDrugentry.getHealthcareInventoryDrugentryDetailsList();
        Long id = healthcareInventoryDrugentry.getId();

        if (StringUtils.isNotNull(healthcareInventoryDrugentryDetailsList)) {
            List<HealthcareInventoryDrugentryDetails> list = new ArrayList<>();
            for (HealthcareInventoryDrugentryDetails healthcareInventoryDrugentryDetails : healthcareInventoryDrugentryDetailsList) {
                if (healthcareInventoryDrugentryDetails.getDrugArchiveId() == null) {
                    throw new IllegalArgumentException("drug_archive_id cannot be null");
                }
                healthcareInventoryDrugentryDetails.setEntryRecordId(id);
                list.add(healthcareInventoryDrugentryDetails);
            }
            if (!list.isEmpty()) {
                healthcareInventoryDrugentryMapper.batchHealthcareInventoryDrugentryDetails(list);
            }
        }
    }
}

