package com.ruoyi.web.stock.service.impl;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.stock.domain.WarehouseRelatedFee;
import com.ruoyi.web.stock.domain.WarehouseRelatedFeeItem;
import com.ruoyi.web.stock.mapper.WarehouseRelatedFeeMapper;
import com.ruoyi.web.stock.service.IWarehouseRelatedFeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class WarehouseRelatedFeeServiceImpl implements IWarehouseRelatedFeeService {

    @Autowired
    private WarehouseRelatedFeeMapper warehouseRelatedFeeMapper;

    @Override
    public WarehouseRelatedFee selectById(Long id) {
        WarehouseRelatedFee entity = warehouseRelatedFeeMapper.selectById(id);
        if (entity != null) {
            entity.setGoodsList(warehouseRelatedFeeMapper.selectItemsByFeeId(id));
        }
        return entity;
    }

    @Override
    public List<WarehouseRelatedFee> selectList(WarehouseRelatedFee query) {
        return warehouseRelatedFeeMapper.selectList(query);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int submitFee(WarehouseRelatedFee entity, String operator) {
        validate(entity);
        entity.setSheetNo(generateSheetNo(entity.getOrgId(), entity.getBizDate()));
        entity.setCreateBy(operator);
        entity.setUpdateBy(operator);
        entity.setDelFlag("0");
        warehouseRelatedFeeMapper.insert(entity);

        Integer lineNo = 1;
        Set<String> lineDupCheck = new HashSet<>();
        for (WarehouseRelatedFeeItem item : entity.getGoodsList()) {
            if (StringUtils.isEmpty(item.getSubjectLevel1()) || StringUtils.isEmpty(item.getSubjectLevel2())) {
                throw new ServiceException("提交失败，费用科目名称不能为空");
            }
            BigDecimal amt = item.getAmount();
            if (amt == null) {
                item.setAmount(BigDecimal.ZERO);
            }
            item.setFeeId(entity.getId());
            item.setSheetNo(entity.getSheetNo());
            item.setLineNo(lineNo++);
            item.setOrgId(entity.getOrgId());
            item.setDelFlag("0");
            item.setCreateBy(operator);
            item.setUpdateBy(operator);

            // 轻量重复校验：同一行级别科目+金额重复（仅防明显误填）
            String key = item.getSubjectLevel1() + "|" + item.getSubjectLevel2() + "|" + item.getAmount();
            if (!lineDupCheck.add(key)) {
                // 允许业务允许重复的话可移除此校验
            }
        }
        warehouseRelatedFeeMapper.insertItemsBatch(entity.getGoodsList());
        return 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeById(Long id, String operator) {
        warehouseRelatedFeeMapper.deleteItemsByFeeId(id, operator);
        return warehouseRelatedFeeMapper.deleteById(id, operator);
    }

    private void validate(WarehouseRelatedFee entity) {
        if (entity == null) {
            throw new ServiceException("提交失败，参数不能为空");
        }
        if (entity.getBizDate() == null) {
            throw new ServiceException("提交失败，业务日期不能为空");
        }
        if (StringUtils.isEmpty(entity.getOrgId())) {
            throw new ServiceException("提交失败，企业标识不能为空");
        }
        if (entity.getGoodsList() == null || entity.getGoodsList().isEmpty()) {
            throw new ServiceException("提交失败，至少需要一条费用明细");
        }
    }

    private String generateSheetNo(String orgId, Date bizDate) {
        String dateText = new SimpleDateFormat("yyyyMMdd").format(bizDate);
        Integer maxSeq = warehouseRelatedFeeMapper.selectTodayMaxSeq(orgId, dateText);
        int nextSeq = (maxSeq == null ? 0 : maxSeq) + 1;
        return dateText + String.format("%04d", nextSeq);
    }
}

