package org.jeecg.modules.productOrder.service.impl;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.log4j.Log4j2;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.product.entity.TbProduct;
import org.jeecg.modules.product.service.ITbProductService;
import org.jeecg.modules.productOrder.entity.TbProductOrder;
import org.jeecg.modules.productOrder.mapper.TbProductOrderMapper;
import org.jeecg.modules.productOrder.service.ITbProductOrderService;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * @Description: 订单表
 * @Author: jeecg-boot
 * @Date: 2024-10-20
 * @Version: V1.0
 */
@Log4j2
@Service
public class TbProductOrderServiceImpl extends ServiceImpl<TbProductOrderMapper, TbProductOrder> implements ITbProductOrderService {

    @Resource
    private ITbProductService tbProductService;

    @Transactional
    @Override
    public Result updateOrder(TbProductOrder tbProductOrder) {
        TbProductOrder byId = this.getById(tbProductOrder.getId());

        if (byId.getAuditStatus() != tbProductOrder.getAuditStatus()) {
            if (byId.getAuditStatus() == 1) {
                return Result.error("已审核通过的订单不能重复审核");
            }
            log.info("修改审核状态{}", JSONObject.toJSONString(tbProductOrder));
            //修改库存
            if (byId.getAuditStatus() == 0 && tbProductOrder.getAuditStatus() == 1) {
                //审核状态 0审核中 1 审核通过 2审核未通过
                TbProduct product = tbProductService.getById(byId.getProductId());
                BigDecimal subtract = new BigDecimal(product.getNum()).subtract(new BigDecimal(byId.getNum()));
                if (subtract.intValue()<0){
                    return Result.error("该报价库存剩余"+product.getNum()+"，库存不足");
                }
                log.info("修改库存状态,原库存{}，减少库存{}，剩余库存{}", product.getNum(), byId.getNum(), subtract);
                product.setNum(subtract.intValue());
                tbProductService.updateById(product);
            }

        }
        this.updateById(tbProductOrder);
        return Result.OK("编辑成功!");
    }
}
