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 com.zhyc.common.annotation.DataScope;
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);
    }

    /**
     * 查询羊只销售记录列表
     * deptAlias = "s": 对应 Mapper.xml 中表 sx_sheep_sale 的别名 s
     * userAlias = "s": 对应 Mapper.xml 中表 sx_sheep_sale 的别名 s
     *
     * @param sxSheepSale 羊只销售记录
     * @return 羊只销售记录
     */
    @Override
    @DataScope(deptAlias = "s", userAlias = "s")
    public List<SxSheepSale> selectSxSheepSaleList(SxSheepSale sxSheepSale) {
        return sxSheepSaleMapper.selectSxSheepSaleList(sxSheepSale);
    }

    /**
     * 新增羊只销售记录
     *
     * @param sxSheepSale 羊只销售记录
     * @return 结果
     */
    @Override
    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
    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);
    }

    @Override
    public List<String> selectSheepTagsBySheepfoldId(Long sheepfoldId) {
        return sxSheepSaleMapper.selectSheepTagsBySheepfoldId(sheepfoldId);
    }

    /**
     * 【新增】实现模糊查询耳号
     */
    @Override
    public List<String> searchEarNumbers(String query) {
        return sxSheepSaleMapper.searchEarNumbers(query);
    }

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

        // 获取羊只数量，默认为1防止除零
        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);

            // 按个体时，无需计算平均体重，清空相关字段避免混淆（可视需求决定是否保留）
            sxSheepSale.setAvgWeight(null);

        } 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));
            }
        }
    }

    /**
     * 业务字段验证
     */
    private void validateSalesFields(SxSheepSale sxSheepSale) {
        // 1. 基础必填校验
        if (sxSheepSale.getSaleDate() == null) {
            throw new RuntimeException("销售日期不能为空！");
        }
        if (sxSheepSale.getTechnicianId() == null) {
            throw new RuntimeException("技术员不能为空！");
        }
        if (sxSheepSale.getHandlerId() == null) {
            throw new RuntimeException("处理人不能为空！");
        }
        if (sxSheepSale.getGroupCode() == null || sxSheepSale.getGroupCode().trim().isEmpty()) {
            throw new RuntimeException("班组不能为空！");
        }
        if (sxSheepSale.getPricingMethod() == null || sxSheepSale.getPricingMethod().trim().isEmpty()) {
            throw new RuntimeException("计价方式不能为空！");
        }

        // 2. 级联校验
        String saleType = sxSheepSale.getSaleType();
        // 如果销售类别是"淘汰销售"或"淘汰屠宰"，则疾病类型不能为空
        if ("淘汰销售".equals(saleType) || "淘汰屠宰".equals(saleType)) {
            if (sxSheepSale.getDiseaseType() == null || sxSheepSale.getDiseaseType().trim().isEmpty()) {
                throw new RuntimeException("淘汰销售或淘汰屠宰必须选择疾病类型！");
            }
        }

        // 如果疾病类型是"病残羊"，则次要原因不能为空
        if ("病残羊".equals(sxSheepSale.getDiseaseType())) {
            if (sxSheepSale.getSecondaryReason() == null || sxSheepSale.getSecondaryReason().trim().isEmpty()) {
                throw new RuntimeException("疾病类型为病残羊时，必须填写次要原因！");
            }
        }
    }
}