
package com.tmerclub.cloud.search.manager;

import cn.hutool.core.collection.CollUtil;
import com.tmerclub.cloud.common.product.vo.SpuVO;
import com.tmerclub.cloud.search.constant.EsIndexEnum;
import com.tmerclub.cloud.search.util.EsSearchUtil;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author YXF
 * @date 2023/08/07
 */
@Component
public class ProductOperateManager {

    private static final Logger log = LoggerFactory.getLogger(ProductOperateManager.class);

    public void batchUpdateSpuStockAndSale(List<SpuVO> spuList) {
        if (CollUtil.isEmpty(spuList)) {
            return;
        }

        Map<Long, Script> map = new HashMap<>(spuList.size());
        for (SpuVO spuVO : spuList) {
            String code = "= ";
            // 组装商品的更新数据
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("ctx._source.stock " + code + spuVO.getTotalStock() + ";");
            stringBuilder.append("ctx._source.actualSoldNum " + code + spuVO.getSaleNum() + ";");
            stringBuilder.append("ctx._source.saleNum = " + "ctx._source.waterSoldNum" + "+" + spuVO.getSaleNum() + ";");
            boolean hasStock = spuVO.getTotalStock() > 0;
            stringBuilder.append("ctx._source.hasStock " + code + hasStock + ";");
            stringBuilder.append("ctx._source.stockWarning " + code + spuVO.getStockWarning() + ";");

            Script script = new Script(ScriptType.INLINE,
                    "painless",
                    stringBuilder.toString(),
                    Collections.emptyMap());
            map.put(spuVO.getSpuId(), script);
        }
        // 批量更新
        EsSearchUtil.updateByPainless(map, EsIndexEnum.PRODUCT.value());
    }
}
