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.WarehouseAccountingGuide;
import com.ruoyi.web.stock.domain.WarehouseAccountingGuideGoods;
import com.ruoyi.web.stock.domain.vo.InventoryLineOptionVo;
import com.ruoyi.web.stock.mapper.WarehouseAccountingGuideMapper;
import com.ruoyi.web.stock.mapper.WarehouseInventoryMapper;
import com.ruoyi.web.stock.service.IWarehouseAccountingGuideService;
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.List;
import java.util.Map;

@Service
public class WarehouseAccountingGuideServiceImpl implements IWarehouseAccountingGuideService {
    @Autowired private WarehouseAccountingGuideMapper warehouseAccountingGuideMapper;
    @Autowired private WarehouseInventoryMapper warehouseInventoryMapper;

    @Override
    public WarehouseAccountingGuide selectById(Long id) {
        WarehouseAccountingGuide entity = warehouseAccountingGuideMapper.selectById(id);
        if (entity != null) entity.setGoodsList(warehouseAccountingGuideMapper.selectGoodsByGuideId(id));
        return entity;
    }

    @Override
    public List<WarehouseAccountingGuide> selectList(WarehouseAccountingGuide query) {
        return warehouseAccountingGuideMapper.selectList(query);
    }

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

        List<InventoryLineOptionVo> options = warehouseInventoryMapper.selectInventoryLinesForStockCheck(entity.getOrgId());
        Map<String, InventoryLineOptionVo> mapByGoods = new HashMap<>();
        for (InventoryLineOptionVo o : options) {
            if (!mapByGoods.containsKey(o.getGoodsNum())) mapByGoods.put(o.getGoodsNum(), o);
        }

        int lineNo = 1;
        for (WarehouseAccountingGuideGoods item : entity.getGoodsList()) {
            if (StringUtils.isEmpty(item.getGoodsNum())) throw new ServiceException("提交失败，存在未选择物料的明细");
            if (StringUtils.isEmpty(item.getProductionWorkshop())) throw new ServiceException("提交失败，明细生产车间不能为空");
            InventoryLineOptionVo hit = mapByGoods.get(item.getGoodsNum());
            item.setGuideId(entity.getId());
            item.setSheetNo(entity.getSheetNo());
            item.setLineNo(lineNo++);
            if (StringUtils.isEmpty(item.getGoodsName()) && hit != null) item.setGoodsName(hit.getGoodsName());
            if (StringUtils.isEmpty(item.getGoodsSpec()) && hit != null) item.setGoodsSpec(hit.getGoodsSpec());
            if (item.getGuidePrice() == null) item.setGuidePrice(BigDecimal.ZERO);
            item.setOrgId(entity.getOrgId());
            item.setCreateBy(operator);
            item.setUpdateBy(operator);
            item.setDelFlag("0");
        }
        warehouseAccountingGuideMapper.insertGoodsBatch(entity.getGoodsList());
        return 1;
    }

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

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

    private void validate(WarehouseAccountingGuide 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 = warehouseAccountingGuideMapper.selectTodayMaxSeq(orgId, dateText);
        int nextSeq = (maxSeq == null ? 0 : maxSeq) + 1;
        return dateText + String.format("%04d", nextSeq);
    }
}

