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.WarehouseCheck;
import com.ruoyi.web.stock.domain.WarehouseCheckGoods;
import com.ruoyi.web.stock.domain.WarehouseInventory;
import com.ruoyi.web.stock.domain.vo.InventoryLineOptionVo;
import com.ruoyi.web.stock.mapper.WarehouseCheckMapper;
import com.ruoyi.web.stock.mapper.WarehouseInventoryMapper;
import com.ruoyi.web.stock.service.IWarehouseCheckService;
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.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 仓库盘点 Service 实现。
 * <p>
 * 提交时以提交瞬间的账面库存为准计算差异，并将 warehouse_inventory 更新为实盘数量。
 * </p>
 */
@Service
public class WarehouseCheckServiceImpl implements IWarehouseCheckService {

    @Autowired
    private WarehouseCheckMapper warehouseCheckMapper;
    @Autowired
    private WarehouseInventoryMapper warehouseInventoryMapper;

    @Override
    public WarehouseCheck selectById(Long id) {
        WarehouseCheck entity = warehouseCheckMapper.selectWarehouseCheckById(id);
        if (entity != null) {
            entity.setGoodsList(warehouseCheckMapper.selectWarehouseCheckGoodsByCheckId(id));
        }
        return entity;
    }

    @Override
    public List<WarehouseCheck> selectList(WarehouseCheck query) {
        return warehouseCheckMapper.selectWarehouseCheckList(query);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int submitCheck(WarehouseCheck entity, String operator) {
        validateSubmit(entity);
        if (StringUtils.isEmpty(entity.getCheckUser())) {
            entity.setCheckUser(operator);
        }
        entity.setSheetNo(generateSheetNo(entity.getOrgId(), entity.getCheckDate()));
        entity.setCreateBy(operator);
        entity.setUpdateBy(operator);
        entity.setDelFlag("0");
        warehouseCheckMapper.insertWarehouseCheck(entity);

        List<InventoryLineOptionVo> lineOpts = warehouseInventoryMapper.selectInventoryLinesForStockCheck(entity.getOrgId());
        Map<Long, InventoryLineOptionVo> lineOptMap = new HashMap<>();
        for (InventoryLineOptionVo opt : lineOpts) {
            lineOptMap.put(opt.getInventoryId(), opt);
        }

        Set<Long> seenInventory = new HashSet<>();
        List<WarehouseCheckGoods> lines = entity.getGoodsList();
        for (WarehouseCheckGoods line : lines) {
            if (line.getInventoryId() == null) {
                throw new ServiceException("提交失败，存在未选择库存行的明细");
            }
            if (!seenInventory.add(line.getInventoryId())) {
                throw new ServiceException("提交失败，同一库存行不能重复盘点");
            }
            WarehouseInventory inv = warehouseInventoryMapper.selectWarehouseInventoryById(line.getInventoryId());
            if (inv == null || !entity.getOrgId().equals(inv.getOrgId()) || !"0".equals(inv.getDelFlag())) {
                throw new ServiceException("提交失败，库存行不存在或无权操作");
            }

            BigDecimal bookBase = defaultZero(inv.getStockQty());
            BigDecimal bookAssist = defaultZero(inv.getAssistStockQty());
            BigDecimal countBase = defaultZero(line.getCountBaseQty());
            BigDecimal countAssist = defaultZero(line.getCountAssistQty());

            BigDecimal diffBase = countBase.subtract(bookBase);
            BigDecimal diffAssist = countAssist.subtract(bookAssist);

            int updated = warehouseInventoryMapper.updateStockQtyById(inv.getId(), countBase, countAssist, operator);
            if (updated == 0) {
                throw new ServiceException("提交失败，更新库存失败");
            }

            line.setCheckId(entity.getId());
            line.setSheetNo(entity.getSheetNo());
            line.setOrgId(entity.getOrgId());
            line.setGoodsNum(inv.getGoodsNum());
            line.setGoodsName(inv.getGoodsName());
            line.setBatchNo(inv.getBatchNo());
            line.setWarehouseNo(inv.getWarehouseNo());
            line.setWarehouseName(inv.getWarehouseName());
            line.setBookBaseQty(bookBase);
            line.setBookAssistQty(bookAssist);
            line.setCountBaseQty(countBase);
            line.setCountAssistQty(countAssist);
            line.setDiffBaseQty(diffBase);
            line.setDiffAssistQty(diffAssist);
            line.setCreateBy(operator);
            line.setUpdateBy(operator);
            line.setDelFlag("0");
            fillUnitsFromMap(lineOptMap, line);
        }
        warehouseCheckMapper.insertWarehouseCheckGoodsBatch(lines);
        return 1;
    }

    private void fillUnitsFromMap(Map<Long, InventoryLineOptionVo> lineOptMap, WarehouseCheckGoods line) {
        InventoryLineOptionVo opt = lineOptMap.get(line.getInventoryId());
        if (opt == null) {
            return;
        }
        if (StringUtils.isEmpty(line.getBaseUnit())) {
            line.setBaseUnit(opt.getBaseUnit());
        }
        if (StringUtils.isEmpty(line.getAssistantUnit())) {
            line.setAssistantUnit(opt.getAssistantUnit());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeById(Long id, String operator) {
        warehouseCheckMapper.deleteWarehouseCheckGoodsByCheckId(id, operator);
        return warehouseCheckMapper.deleteWarehouseCheckById(id, operator);
    }

    @Override
    public List<InventoryLineOptionVo> listInventoryLineOptions(String orgId) {
        return warehouseInventoryMapper.selectInventoryLinesForStockCheck(orgId);
    }

    private void validateSubmit(WarehouseCheck entity) {
        if (entity == null) {
            throw new ServiceException("提交失败，参数不能为空");
        }
        if (entity.getCheckDate() == 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 checkDate) {
        String dateText = new SimpleDateFormat("yyyyMMdd").format(checkDate);
        Integer maxSeq = warehouseCheckMapper.selectTodayMaxSeq(orgId, dateText);
        int nextSeq = (maxSeq == null ? 0 : maxSeq) + 1;
        return dateText + String.format("%04d", nextSeq);
    }

    private static BigDecimal defaultZero(BigDecimal v) {
        return v == null ? BigDecimal.ZERO : v;
    }
}
