package com.fjs.scenic.service.ord.impl;

import com.fjs.scenic.entity.order.Orders;
import com.fjs.scenic.entity.order.Receipt;
import com.fjs.scenic.mapper.order.OrdersMapper;
import com.fjs.scenic.mapper.order.ReceiptMapper;
import com.fjs.scenic.service.ord.ReceiptService;
import com.fjs.scenic.utils.Cons;
import com.fjs.scenic.utils.ReturnResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DecimalFormat;

@Service
public class ReceiptServiceImpl implements ReceiptService {

    @Autowired
    private ReceiptMapper receiptMapper;
    @Autowired
    private OrdersMapper ordersMapper;

    @Override
    public ReturnResult add(Receipt receipt) {

        Orders o=ordersMapper.selectByPrimaryKey(receipt.getOrderId());

        if(o==null){
            return ReturnResult.build(500,"此订单不存在");
        }

        if(!o.getStatus().equals(Cons.ORDER_STATUS.DONE)){
            return ReturnResult.build(500,"此订单不能开发票");
        }

        String priceStr = receipt.getPrice().toString();
        System.out.println("priceStr--->"+priceStr);

        System.out.println("totalPrice------>"+o.getTotelPrice());

        String orderPrice = new BigDecimal(o.getTotelPrice()).divide(BigDecimal.valueOf(100))
                .setScale(2, BigDecimal.ROUND_UP).toString();

        System.out.println("orderPrice--->"+orderPrice);
        if(!priceStr.equals(orderPrice)){
            return ReturnResult.build(500,"发票金额与订单金额不符");
        }

        //添加发票
        int row = receiptMapper.insertSelective(receipt);

        if (row > 0) {
            Orders orders=new Orders();
            orders.setId(o.getId());
            orders.setStatus(Cons.ORDER_STATUS.BILL);
            ordersMapper.updateByPrimaryKeySelective(orders);
            return ReturnResult.ok();
        }
        return ReturnResult.build(500, "添加失败！");
    }
}
