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

import java.util.List;
import java.math.BigDecimal;
import java.math.RoundingMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.zhyc.common.exception.ServiceException;
import com.zhyc.module.sale.mapper.SxSheepSaleMapper;
import com.zhyc.module.sale.domain.SxSheepSale;
import com.zhyc.module.sale.service.ISxSheepSaleService;

/**
 * 羊只销售记录Service业务层处理
 *
 * @author ruoyi
 * @date 2025-08-19
 */
@Service
public class SxSheepSaleServiceImpl implements ISxSheepSaleService {
    @Autowired
    private SxSheepSaleMapper sxSheepSaleMapper;

    /**
     * 查询羊只销售记录
     *
     * @param id 羊只销售记录主键
     * @return 羊只销售记录
     */
    @Override
    public SxSheepSale selectSxSheepSaleById(Long id) {
        return sxSheepSaleMapper.selectSxSheepSaleById(id);
    }

    /**
     * 查询羊只销售记录列表
     *
     * @param sxSheepSale 羊只销售记录
     * @return 羊只销售记录
     */
    @Override
    public List<SxSheepSale> selectSxSheepSaleList(SxSheepSale sxSheepSale) {
        return sxSheepSaleMapper.selectSxSheepSaleList(sxSheepSale);
    }

    /**
     * 新增羊只销售记录
     *
     * @param sxSheepSale 羊只销售记录
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class) // 事务控制
    public int insertSxSheepSale(SxSheepSale sxSheepSale) {
        // 1. 业务验证
        validateSalesFields(sxSheepSale);

        // 2. 自动计算逻辑
        calculateSalesFields(sxSheepSale);

        // 3. 设置默认事件类型
        if (sxSheepSale.getEventType() == null) {
            sxSheepSale.setEventType("销售");
        }

        // 4. 处理耳号列表（多个耳号用逗号分隔）
        if (sxSheepSale.getBsManageTagsList() != null && !sxSheepSale.getBsManageTagsList().isEmpty()) {
            sxSheepSale.setBsManageTags(String.join(",", sxSheepSale.getBsManageTagsList()));
        }

        // 5. 调用Mapper插入数据
        return sxSheepSaleMapper.insertSxSheepSale(sxSheepSale);
    }

    /**
     * 修改羊只销售记录
     *
     * @param sxSheepSale 羊只销售记录
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateSxSheepSale(SxSheepSale sxSheepSale) {
        // 1. 业务验证
        validateSalesFields(sxSheepSale);

        // 2. 自动计算逻辑
        calculateSalesFields(sxSheepSale);

        // 3. 处理耳号列表
        if (sxSheepSale.getBsManageTagsList() != null && !sxSheepSale.getBsManageTagsList().isEmpty()) {
            sxSheepSale.setBsManageTags(String.join(",", sxSheepSale.getBsManageTagsList()));
        }

        // 4. 调用Mapper更新数据
        return sxSheepSaleMapper.updateSxSheepSale(sxSheepSale);
    }

    /**
     * 批量删除羊只销售记录
     *
     * @param ids 需要删除的羊只销售记录主键
     * @return 结果
     */
    @Override
    public int deleteSxSheepSaleByIds(Long[] ids) {
        return sxSheepSaleMapper.deleteSxSheepSaleByIds(ids);
    }

    /**
     * 删除羊只销售记录信息
     *
     * @param id 羊只销售记录主键
     * @return 结果
     */
    @Override
    public int deleteSxSheepSaleById(Long id) {
        return sxSheepSaleMapper.deleteSxSheepSaleById(id);
    }

    /**
     * 根据耳号查询羊只信息
     */
    @Override
    public SxSheepSale selectSheepInfoByTag(String bsManageTags) {
        return sxSheepSaleMapper.selectSheepInfoByTag(bsManageTags);
    }

    /**
     * 自动计算总价、平均体重、平均单只价格
     */
    private void calculateSalesFields(SxSheepSale sxSheepSale) {
        String pricingMethod = sxSheepSale.getPricingMethod();
        BigDecimal unitPrice = sxSheepSale.getUnitPrice();

        // 获取羊只数量
        int sheepCount = 1;
        if (sxSheepSale.getBsManageTagsList() != null && !sxSheepSale.getBsManageTagsList().isEmpty()) {
            sheepCount = sxSheepSale.getBsManageTagsList().size();
        } else if (sxSheepSale.getBsManageTags() != null && !sxSheepSale.getBsManageTags().isEmpty()) {
            sheepCount = sxSheepSale.getBsManageTags().split(",").length;
        }

        if ("按个体".equals(pricingMethod)) {
            if (unitPrice != null) {
                sxSheepSale.setTotalPrice(unitPrice.multiply(new BigDecimal(sheepCount)));
            }
            sxSheepSale.setAvgPricePerSheep(unitPrice);
        } else if ("按体重".equals(pricingMethod)) {
            BigDecimal totalWeight = sxSheepSale.getTotalWeight();
            if (unitPrice != null && totalWeight != null) {
                sxSheepSale.setTotalPrice(unitPrice.multiply(totalWeight));
            }
            if (totalWeight != null && sheepCount > 0) {
                sxSheepSale.setAvgWeight(totalWeight.divide(new BigDecimal(sheepCount), 2, RoundingMode.HALF_UP));
            }
            if (sxSheepSale.getTotalPrice() != null && sheepCount > 0) {
                sxSheepSale.setAvgPricePerSheep(sxSheepSale.getTotalPrice().divide(new BigDecimal(sheepCount), 2, RoundingMode.HALF_UP));
            }
        }
    }

    /**
     * 业务字段验证 (使用 ServiceException)
     */
    private void validateSalesFields(SxSheepSale sxSheepSale) {
        if (sxSheepSale.getSaleDate() == null) {
            throw new ServiceException("销售日期不能为空！");
        }

        String saleType = sxSheepSale.getSaleType();
        if ("淘汰销售".equals(saleType) || "淘汰屠宰".equals(saleType)) {
            if (sxSheepSale.getDiseaseType() == null) {
                throw new ServiceException("淘汰销售或淘汰屠宰必须选择疾病类型！");
            }
            if (sxSheepSale.getGroupCode() == null) {
                throw new ServiceException("淘汰销售或淘汰屠宰必须选择班组！");
            }
        }
        if ("病残羊".equals(sxSheepSale.getDiseaseType())) {
            if (sxSheepSale.getSecondaryReason() == null || sxSheepSale.getSecondaryReason().trim().isEmpty()) {
                throw new ServiceException("疾病类型为病残羊时，必须填写次要原因！");
            }
        }
    }
}