package org.dromara.zhishu.service.strategy;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.exception.base.BaseException;
import org.dromara.zhishu.domain.ShopGoodsPublishedLog;
import org.dromara.zhishu.domain.ZhishuShopGoods;
import org.dromara.zhishu.domain.dto.request.SoldOutRequest;
import org.dromara.zhishu.domain.vo.ShopGoodsPublishedVo;
import org.dromara.zhishu.domain.vo.ShopVo;
import org.dromara.zhishu.mapper.ShopGoodsPublishedLogMapper;
import org.dromara.zhishu.mapper.ZhishuShopGoodsMapper;
import org.dromara.zhishu.service.IKongFzService;
import org.dromara.zhishu.service.client.KfzClient;
import org.dromara.zhishu.util.UrlUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class InventorySynchronizedKWStrategy implements InventorySynchronizedStrategy {

    @Autowired
    private IKongFzService kongFzService;

    @Autowired
    private KfzClient kfzClient;

    @Autowired
    private ZhishuShopGoodsMapper zhishuShopGoodsMapper;

    @Autowired
    private ShopGoodsPublishedLogMapper shopGoodsPublishedLogMapper;

    @Override
    public void inventorySynchronized(ShopVo shop, ShopGoodsPublishedVo goodsPublishedVo, Integer type) {
        String shopGoodsId = goodsPublishedVo.getShopGoodsId();
        ZhishuShopGoods zhishuShopGoods = new LambdaQueryChainWrapper<>(zhishuShopGoodsMapper)
                .eq(ZhishuShopGoods::getId, shopGoodsId)
                .oneOpt().orElseThrow(() -> new BaseException("数据异常"));
        kongFzService.goodUpdateStock(shop.getToken(), goodsPublishedVo.getPlatformId(), zhishuShopGoods.getInventory().toString());
    }

    @Override
    public void operatingGoodsSoldOut(ShopVo shop, ShopGoodsPublishedVo goodsPublishedVo, Integer platformType, Integer logType, Integer operationType, String orderSn) {
        SoldOutRequest soldOutRequest = new SoldOutRequest(shop.getToken(), goodsPublishedVo.getPlatformId());
        R<Boolean> booleanR = kfzClient.soldOut(UrlUtil.getKfzServiceUrl(), soldOutRequest);
        ShopGoodsPublishedLog shopGoodsPublishedLog = new ShopGoodsPublishedLog();
        shopGoodsPublishedLog.setShopGoodsId(Long.valueOf(goodsPublishedVo.getShopGoodsId()));
        shopGoodsPublishedLog.setShopGoodsPublishedId(goodsPublishedVo.getId());
        shopGoodsPublishedLog.setPlatformId(goodsPublishedVo.getPlatformId());
        shopGoodsPublishedLog.setAboutId(orderSn);
        shopGoodsPublishedLog.setLogType(logType);
        shopGoodsPublishedLog.setOperationType(operationType);
        shopGoodsPublishedLog.setPlatformType(platformType);
        shopGoodsPublishedLog.setStatus(R.isSuccess(booleanR) ? 0 : 1);
        shopGoodsPublishedLogMapper.insert(shopGoodsPublishedLog);
    }
}