package com.fjhx.service.stock.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjhx.base.Condition;
import com.fjhx.constants.StatusConstant;
import com.fjhx.entity.product.ProductInfo;
import com.fjhx.entity.stock.StockTransfer;
import com.fjhx.enums.stock.InTypeEnum;
import com.fjhx.enums.stock.OutTypeEnum;
import com.fjhx.mapper.stock.StockTransferMapper;
import com.fjhx.params.stock.ChangeProduct;
import com.fjhx.params.stock.StockChangeDto;
import com.fjhx.params.stock.StockTransferAddVo;
import com.fjhx.service.stock.StockService;
import com.fjhx.service.stock.StockTransferService;
import com.fjhx.utils.Assert;
import com.fjhx.utils.UserClientUtil;
import com.fjhx.utils.wrapperUtil.IWrapper;
import com.fjhx.utils.wrapperUtil.KeywordData;
import org.springblade.core.secure.utils.AuthUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 调仓 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2022-12-14
 */
@Service
public class StockTransferServiceImpl extends ServiceImpl<StockTransferMapper, StockTransfer> implements StockTransferService {

    @Autowired
    private StockService stockService;


    @Override
    public Page<Map<String, Object>> getPage(Condition condition) {

        IWrapper<Object> wrapper = IWrapper.getWrapper(condition);
        wrapper.eq("st", StockTransfer::getInWarehouseId);
        wrapper.eq("st", StockTransfer::getOutWarehouseId);
        wrapper.eq("st", StockTransfer::getInStatus);
        wrapper.keyword(new KeywordData("pi", ProductInfo::getName), new KeywordData("pi", ProductInfo::getCode));
        wrapper.orderByDesc("st", StockTransfer::getId);

        Page<Map<String, Object>> page = baseMapper.getPage(condition.getPage(), wrapper);
        List<Map<String, Object>> records = page.getRecords();
        if (records.size() == 0) {
            return page;
        }

        List<Long> userIdList = new ArrayList<>();
        records.forEach(item -> {
            userIdList.add(Convert.toLong(item.get("inUser")));
            userIdList.add(Convert.toLong(item.get("createUser")));
        });

        Map<Long, String> userNameMap = UserClientUtil.getUserNameMap(userIdList);

        for (Map<String, Object> item : records) {
            item.put("inUserName", userNameMap.get(Convert.toLong(item.get("inUser"))));
            item.put("outUserName", userNameMap.get(Convert.toLong(item.get("createUser"))));
        }

        return page;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(StockTransferAddVo stockTransferAddVo) {
        // 调仓明细
        List<ChangeProduct> changeProductList = stockTransferAddVo.getChangeProductList();
        Assert.notEmpty(changeProductList, "调仓明细不能为空");
        List<StockTransfer> stockTransferList = changeProductList.stream()
                .filter(item -> item.getQuantity().compareTo(BigDecimal.ZERO) > 0)
                .map(item -> {
                    long id = IdWorker.getId();
                    item.setBusinessId(id);

                    StockTransfer stockTransfer = new StockTransfer();
                    stockTransfer.setId(id);
                    stockTransfer.setInWarehouseId(stockTransferAddVo.getInWarehouseId());
                    stockTransfer.setOutWarehouseId(stockTransferAddVo.getOutWarehouseId());
                    stockTransfer.setRemark(stockTransferAddVo.getRemark());
                    stockTransfer.setInStatus(StatusConstant.NO);
                    stockTransfer.setOutQuantity(item.getQuantity());
                    stockTransfer.setProductId(item.getProductId());
                    return stockTransfer;
                }).collect(Collectors.toList());

        if (stockTransferList.size() == 0) {
            return;
        }

        saveBatch(stockTransferList);

        StockChangeDto stockChangeDto = new StockChangeDto();
        stockChangeDto.setDefaultWarehouseId(stockTransferAddVo.getOutWarehouseId());
        stockChangeDto.setDefaultRemarks(stockTransferAddVo.getRemark());
        stockChangeDto.setTypeEnum(OutTypeEnum.TRANSFER);
        stockChangeDto.setChangeDetailsList(changeProductList);
        stockService.changeQuantity(stockChangeDto);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void receive(StockTransfer dto) {

        StockTransfer stockTransfer = getById(dto);
        Assert.eqTrue(StatusConstant.NO.equals(stockTransfer.getInStatus()), "物品已接收");

        stockTransfer.setInUser(AuthUtil.getUserId());
        stockTransfer.setInQuantity(dto.getInQuantity());
        stockTransfer.setInTime(new Date());
        stockTransfer.setInStatus(StatusConstant.YES);
        updateById(stockTransfer);

        ChangeProduct changeProduct = new ChangeProduct();
        changeProduct.setBusinessId(stockTransfer.getId());
        changeProduct.setProductId(stockTransfer.getProductId());
        changeProduct.setQuantity(stockTransfer.getInQuantity());

        StockChangeDto stockChangeDto = new StockChangeDto();
        stockChangeDto.setDefaultWarehouseId(stockTransfer.getInWarehouseId());
        stockChangeDto.setDefaultRemarks(stockTransfer.getRemark());
        stockChangeDto.setTypeEnum(InTypeEnum.TRANSFER);
        stockChangeDto.setChangeDetailsList(Collections.singletonList(changeProduct));
        stockService.changeQuantity(stockChangeDto);
    }

}
