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.StockChangeVo;
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, "调仓明细不能为空");

        Date date = new Date();
        Long userId = AuthUtil.getUserId();
        List<StockTransfer> stockTransferList = changeProductList.stream()
                // 排除调仓数量为0
                .filter(item -> item.getQuantity().compareTo(BigDecimal.ZERO) > 0)
                .map(item -> {
                    long id = IdWorker.getId();
                    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());
                    stockTransfer.setCreateTime(date);
                    stockTransfer.setCreateUser(userId);

                    item.setBusinessId(id);

                    return stockTransfer;
                }).collect(Collectors.toList());
        saveBatch(stockTransferList);

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

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

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

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

        byId.setInUser(AuthUtil.getUserId());
        byId.setInQuantity(inQuantity);
        byId.setInTime(new Date());
        byId.setInStatus(StatusConstant.YES);
        updateById(byId);

        ChangeProduct changeProduct = new ChangeProduct();
        changeProduct.setProductId(byId.getProductId());
        changeProduct.setQuantity(inQuantity);

        StockChangeVo stockChangeVo = new StockChangeVo();
        stockChangeVo.setDefaultBusinessId(byId.getId());
        stockChangeVo.setDefaultWarehouseId(byId.getInWarehouseId());
        stockChangeVo.setDefaultRemarks(byId.getRemark());
        stockChangeVo.setTypeEnum(InTypeEnum.TRANSFER);
        stockChangeVo.setChangeDetailsList(Collections.singletonList(changeProduct));
        stockService.changeQuantity(stockChangeVo);
    }

}
