package net.lab1024.sa.admin.module.business.wms.base.stock.service.impl;

import cn.idev.excel.FastExcel;
import jakarta.annotation.Resource;
import net.lab1024.sa.admin.constant.UsageStatusEnum;
import net.lab1024.sa.admin.module.business.wms.base.location.dao.LocationDao;
import net.lab1024.sa.admin.module.business.wms.base.location.domain.entity.LocationEntity;
import net.lab1024.sa.admin.module.business.wms.base.location.service.LocationService;
import net.lab1024.sa.admin.module.business.wms.base.stock.domain.entity.StockEntity;
import net.lab1024.sa.admin.module.business.wms.base.stock.domain.form.StockAddForm;
import net.lab1024.sa.admin.module.business.wms.base.stock.domain.form.StockUpdateForm;
import net.lab1024.sa.admin.module.business.wms.base.stock.domain.form.StocksImportForm;
import net.lab1024.sa.admin.module.business.wms.base.stock.manager.StockManager;
import net.lab1024.sa.admin.module.business.wms.base.stock.service.StockQueryService;
import net.lab1024.sa.admin.module.business.wms.base.stock.service.StockService;
import net.lab1024.sa.admin.util.JoinerResult;
import net.lab1024.sa.admin.util.ResponseDTOUtil;
import net.lab1024.sa.admin.util.ValidateDictKeyUtil;
import net.lab1024.sa.base.common.code.SystemErrorCode;
import net.lab1024.sa.base.common.code.UserErrorCode;
import net.lab1024.sa.base.common.domain.ResponseDTO;
import net.lab1024.sa.base.common.exception.BusinessException;
import net.lab1024.sa.base.common.util.SmartBeanUtil;
import net.lab1024.sa.base.common.util.SmartRequestUtil;
import net.lab1024.sa.base.module.support.dict.constant.DictConst;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class StockServiceImpl implements StockService {
    @Resource
    private LocationDao locationDao;

    @Resource
    private StockManager stockManager;

    @Resource
    private ValidateDictKeyUtil ValidateDictKeyUtil;

    @Resource
    private StockQueryService stockQueryService;

    @Resource
    private LocationService locationService;


    /**
     * 添加
     *
     * @param addForm 添加参数
     * @return ResponseDTO<String>
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseDTO<String> add(StockAddForm addForm) {
        StockEntity existingStock = stockQueryService.queryByStockCode(addForm.getStockCode());
        if (existingStock != null) {
            return ResponseDTO.error(UserErrorCode.ALREADY_EXIST, UserErrorCode.ALREADY_EXIST.getMsg());
        }
        StockEntity stockEntity = SmartBeanUtil.copy(addForm, StockEntity.class);
        stockManager.save(stockEntity);
        return ResponseDTO.ok();
    }

    /**
     * 更新
     *
     * @param updateForm 更新参数
     * @return ResponseDTO<String>
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseDTO<String> update(StockUpdateForm updateForm) {
        StockEntity existingStock = stockQueryService.queryByStockCode(updateForm.getStockCode());
        if (existingStock != null && !existingStock.getStockId().equals(updateForm.getStockId())) {
            return ResponseDTO.error(UserErrorCode.ALREADY_EXIST, UserErrorCode.ALREADY_EXIST.getMsg());
        }
        //当前更新的容器的库位
        if (existingStock != null && existingStock.getLocationId() != null) {
            //更新库位状态
            locationService.updateLocationStatus(existingStock.getLocationId(), UsageStatusEnum.FREE.getValue());
        }

        if (updateForm.getLocationId() != null) {
            LocationEntity location = locationDao.selectById(updateForm.getLocationId());
            StockEntity curStock = stockQueryService.queryStockByLocationId(updateForm.getLocationId());
            if (curStock != null && existingStock != null) {
                if (!curStock.getStockId().equals(existingStock.getStockId())) {
                    return ResponseDTO.error(SystemErrorCode.SYSTEM_ERROR, location.getLocationCode() + "库位绑定的当前容器为" + curStock.getStockCode());
                }
            }
            //更新库位状态
            locationService.updateLocationStatus(updateForm.getLocationId(), UsageStatusEnum.USED.getValue());
        }
        StockEntity stockEntity = SmartBeanUtil.copy(updateForm, StockEntity.class);
        //更新并更新缓存
        stockManager.update(stockEntity);
        return ResponseDTO.ok();
    }

    /**
     * 批量删除
     *
     * @param idList id集合
     * @return ResponseDTO<String>
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseDTO<String> batchDelete(List<Long> idList) {
        if (CollectionUtils.isEmpty(idList)) {
            return ResponseDTO.userErrorParam(UserErrorCode.PARAM_ERROR.getMsg());
        }

        //删除并删除缓存
        stockManager.batchDelete(idList);
        return ResponseDTO.ok();
    }

    /**
     * 单个删除
     *
     * @param stockId 容器Id
     * @return ResponseDTO<String>
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseDTO<String> delete(Long stockId) {
        if (null == stockId) {
            return ResponseDTO.userErrorParam(UserErrorCode.PARAM_ERROR.getMsg());
        }

        //删除并删除缓存
        stockManager.deleteById(stockId);
        return ResponseDTO.ok();
    }

    /**
     * 容器导入
     *
     * @param file 上传文件
     * @return ResponseDTO<String>
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseDTO<String> importStocks(MultipartFile file) {
        List<StocksImportForm> dataList;
        try {
            dataList = FastExcel.read(file.getInputStream()).head(StocksImportForm.class)
                    .sheet()
                    .doReadSync();
        } catch (IOException e) {
            throw new BusinessException("数据格式存在问题，无法读取");
        }
        if (CollectionUtils.isEmpty(dataList)) {
            return ResponseDTO.userErrorParam("数据为空");
        }

        //获取所有容器类型
        List<String> stockTypes = dataList.stream().map(StocksImportForm::getStockType).toList();

        //验证容器类型
        Map<String, String> itemTypeMap = ValidateDictKeyUtil.validateDictCodes(stockTypes, DictConst.STOCK_TYPE.getValue());

        //获取所有的容器编码
        List<String> stockCodes = dataList.stream().map(StocksImportForm::getStockCode).toList();

        //查询数据库存在的容器
        Map<String, StockEntity> exitStockMap = stockQueryService.queryByStockCodesToMap(stockCodes);

        List<StockEntity> insertToStock = new ArrayList<>();
        List<StockEntity> updateToStock = new ArrayList<>();
        for (StocksImportForm stocksImportForm : dataList) {

            //容器类型
            String stockType = itemTypeMap.get(stocksImportForm.getStockType());

            //容器
            StockEntity stock = exitStockMap.get(stocksImportForm.getStockCode());

            //容器为空新增，否则更新
            if (stock == null) {
                insertToStock.add(createStock(stocksImportForm.getStockCode(), stockType));
            } else {
                updateToStock.add(createStock(stocksImportForm.getStockCode(), stockType));
            }
        }

        JoinerResult resultMsg = JoinerResult.createJoiner();
        return ResponseDTOUtil.buildResponseDTO(insertToStock, updateToStock, stockManager::saveBatch, stockManager::batchUpdate, resultMsg);
    }

    /**
     * 创建容器
     *
     * @param stockCode 容器编码
     * @param stockType 容器类型
     * @return StockEntity
     */
    public StockEntity createStock(String stockCode, String stockType) {
        return StockEntity.builder()
                .stockCode(stockCode)
                .stockType(stockType)
                .status(UsageStatusEnum.FREE.getValue())
                .disabledFlag(true)
                .createUserId(SmartRequestUtil.getRequestUser().getUserId())
                .createUserName(SmartRequestUtil.getRequestUser().getUserName())
                .build();
    }
}
