package com.ruoyi.app.service.impl;

import java.util.List;

import com.ruoyi.app.DTO.ImportDistributeBatchDTO;
import com.ruoyi.app.DTO.ValidDistributeListDTO;
import com.ruoyi.app.DTO.ValidSlaughterCodeDTO;
import com.ruoyi.app.domain.*;
import com.ruoyi.app.mapper.*;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.NumberUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 
{
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);
    @Autowired
    private DistributeBatchMapper distributeBatchMapper;

    @Autowired
    private SlaughterBatchMapper slaughterBatchMapper;

    @Autowired
    private PurchaserMapper purchaserMapper;

    @Autowired
    private EntranceBatchMapper entranceBatchMapper;

    @Autowired
    private PorkSideProduceMapper porkSideProduceMapper;

    @Autowired
    private PorkOtherProduceMapper porkOtherProduceMapper;

    @Autowired
    private SlaughterRelationMapper slaughterRelationMapper;
    /**
     * 查询分销批次
     * 
     * @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 importList 分销批次列表
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importDistributeBatch(List<ImportDistributeBatchDTO> importList, String operName)
    {
        if (StringUtils.isNull(importList) || importList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (ImportDistributeBatchDTO item : importList)
        {
            try
            {
                // 获取检疫证号对应的入场批次
                EntranceBatch entranceInfo = entranceBatchMapper.checkAnimalCertNoUnique(item.getAnimalCertNo());
                if (StringUtils.isNull(entranceInfo))
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、检疫证号： " + item.getAnimalCertNo() + " 不存在");
                    continue;
                }

                // 获取血码对应的供应商和肉商
                SlaughterRelation codeInfo = slaughterRelationMapper.checkCodeUnique(item.getSlaughterCode());
                if (StringUtils.isNull(codeInfo))
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、血码： " + item.getSlaughterCode() + " 不存在");
                    continue;
                }
                DistributeBatch distributeBatch = new DistributeBatch();
                distributeBatch.setEntranceBatchId(entranceInfo.getId());
                distributeBatch.setSlaughterCode(item.getSlaughterCode());
                distributeBatch.setPurchaserId(codeInfo.getPurchaserId());
                distributeBatch.setSupplierId(codeInfo.getSupplierId());
                distributeBatch.setAmount(item.getAmount());
                distributeBatch.setWeight(item.getWeight());
                distributeBatch.setPigpenName(item.getPigpenName());
                distributeBatch.setCreateBy(operName);
                distributeBatch.setCreateTime(DateUtils.getNowDate());
                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);

                successNum++;
                successMsg.append("<br/>" + successNum + "、分销批次： " + item.getAnimalCertNo()+"-"+item.getSlaughterCode() + " 导入成功");

            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、分销批次： " + item.getAnimalCertNo()+"-"+item.getSlaughterCode() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 校验分销批次的肉商是否唯一
     *
     * @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();
    }
}
