package com.ruoyi.app.service.impl;

import java.util.List;

import com.ruoyi.app.DTO.ValidDistributeListDTO;
import com.ruoyi.app.DTO.ValidSlaughterCodeDTO;
import com.ruoyi.app.model.*;
import com.ruoyi.app.mapper.*;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.NumberUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.app.service.IDistributeBatchService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 分销批次Service业务层处理
 * 
 * @author coede
 * @date 2025-03-19
 */
@Service
public class DistributeBatchServiceImpl implements IDistributeBatchService 
{
    @Autowired
    private DistributeBatchMapper distributeBatchMapper;

    @Autowired
    private SlaughterBatchMapper slaughterBatchMapper;

    @Autowired
    private PurchaserMapper purchaserMapper;

    @Autowired
    private EntranceBatchMapper entranceBatchMapper;

    @Autowired
    private PorkSideProduceMapper porkSideProduceMapper;

    @Autowired
    private PorkOtherProduceMapper porkOtherProduceMapper;
    /**
     * 查询分销批次
     * 
     * @param id 分销批次主键
     * @return 分销批次
     */
    @Override
    public DistributeBatch selectDistributeBatchById(Long id)
    {
        return distributeBatchMapper.selectDistributeBatchById(id);
    }

    /**
     * 查询分销批次列表
     * 
     * @param distributeBatch 分销批次
     * @return 分销批次
     */
    @Override
    public List<DistributeBatch> selectDistributeBatchList(DistributeBatch distributeBatch)
    {
        return distributeBatchMapper.selectDistributeBatchList(distributeBatch);
    }

    /**
     * 校验分销批次的肉商是否唯一
     *
     * @param distributeBatch 分销批次
     * @return 结果
     */
    @Override
    public DistributeBatch checkPurchaserUnique(DistributeBatch distributeBatch)
    {
        return distributeBatchMapper.checkPurchaserUnique(distributeBatch);

    }

    /**
     * 校验数量是否超出了准宰数量
     *
     * @param distributeBatch 分销批次
     * @return 结果
     */
    public boolean checkTotalLessThanAmount(DistributeBatch distributeBatch){
        EntranceBatch entranceInfo = entranceBatchMapper.selectEntranceBatchById(distributeBatch.getEntranceBatchId());
        if(entranceInfo==null){
            return false;
        }
        //准宰数量  = 基本信息中的数量-病死头数-病害头数
        int total = NumberUtil.getIntValue(entranceInfo.getAmount()) -
                NumberUtil.getIntValue(entranceInfo.getHarmlessTreatment().getIllnessDeadAmount()) -
                NumberUtil.getIntValue(entranceInfo.getHarmlessTreatment().getIllnessDiseaseAmount());
        //已有数量
        long has = NumberUtil.getLongValue(distributeBatchMapper.getTotalByEntranceBatch(distributeBatch));

        return (total - has) >= NumberUtil.getIntValue(distributeBatch.getAmount());
    }

    /**
     * 获取血码关联的未完成屠宰的分销批次
     *
     * @param distributeBatch 分销批次
     * @return 结果
     */
    public List<ValidDistributeListDTO> selectValidDistribute(DistributeBatch distributeBatch){
        return distributeBatchMapper.selectValidDistribute(distributeBatch.getSlaughterCode());
    }

    /**
     * 新增分销批次
     * 
     * @param distributeBatch 分销批次
     * @return 结果
     */
    @Override
    public int insertDistributeBatch(DistributeBatch distributeBatch)
    {
        distributeBatch.setCreateTime(DateUtils.getNowDate());
        return distributeBatchMapper.insertDistributeBatch(distributeBatch);
    }

    /**
     * 批量新增分销批次 并创建屠宰记录
     *
     * @param list 分销批次
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertDistributeBatchByBatch(List<DistributeBatch> list)
    {
        //这里不能批量插入了，因为创建屠宰批次还需要分销记录的ID
        for (DistributeBatch distributeBatch : list){
            //批量创建分销批次
            distributeBatchMapper.insertDistributeBatch(distributeBatch);
            SlaughterBatch slaughterBatch = new SlaughterBatch();
            //屠宰日期目前就默认创建分销批次的时间
            slaughterBatch.setSlaughterTime(distributeBatch.getCreateTime());//屠宰时间
            slaughterBatch.setDistributeBatchId(distributeBatch.getId());//分销批次
            slaughterBatch.setEntranceBatchId(distributeBatch.getEntranceBatchId());//进场批次
            slaughterBatch.setCreateTime(DateUtils.getNowDate());
            slaughterBatch.setCreateBy(distributeBatch.getCreateBy());
            //查询肉商信息
            Purchaser purchaser = purchaserMapper.selectPurchaserById(distributeBatch.getPurchaserId());
            if(purchaser != null){
                slaughterBatch.setSalePlace(purchaser.getSalePlace());//salePlace 销售去向
            }

            slaughterBatchMapper.insertSlaughterBatch(slaughterBatch);//插入屠宰批次数据
        }
        return list.size();
    }

    /**
     * 修改分销批次
     * 
     * @param distributeBatch 分销批次
     * @return 结果
     */
    @Override
    public int updateDistributeBatch(DistributeBatch distributeBatch)
    {
        distributeBatch.setUpdateTime(DateUtils.getNowDate());
        return distributeBatchMapper.updateDistributeBatch(distributeBatch);
    }

    /**
     * 批量删除分销批次
     * 
     * @param ids 需要删除的分销批次主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteDistributeBatchByIds(Long[] ids)
    {
        for (Long id : ids)
        {
            if(id !=null){
                if (porkSideProduceMapper.countRecordByDistributeId(id) > 0)
                {
                    throw new ServiceException("有关联生产记录，不能删除");
                }

                if (porkOtherProduceMapper.countRecordByDistributeId(id) > 0)
                {
                    throw new ServiceException("有关联生产记录，不能删除");
                }

            }
        }
        slaughterBatchMapper.deleteSlaughterBatchByDistributeIds(ids);
        return distributeBatchMapper.deleteDistributeBatchByIds(ids);
    }

    /**
     * 删除分销批次信息
     * 
     * @param id 分销批次主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteDistributeBatchById(Long id)
    {
        if(id !=null){
            if (porkSideProduceMapper.countRecordByDistributeId(id) > 0)
            {
                throw new ServiceException("有关联生产记录，不能删除");
            }

            if (porkOtherProduceMapper.countRecordByDistributeId(id) > 0)
            {
                throw new ServiceException("有关联生产记录，不能删除");
            }
        }
        slaughterBatchMapper.deleteSlaughterBatchByDistributeId(id);
        return distributeBatchMapper.deleteDistributeBatchById(id);
    }

    /**
     * 获取存在未完成（24小时内）的分销批次的血码
     *
     * @return 结果
     */
    @Override
    public List<ValidSlaughterCodeDTO> selectValidCode(){
        return distributeBatchMapper.selectValidCode();
    }
}
