package com.ruoyi.database.service.impl;


import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.database.domain.ParkingBill;
import com.ruoyi.database.domain.ParkingBillInfo;
import com.ruoyi.database.mapper.ParkingBillInfoMapper;
import com.ruoyi.database.service.ParkingBillInfoService;
import com.ruoyi.database.util.HaiKangApiUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * (停车场账单表)ServiceImpl
 *
 * @author makejava
 * @since 2025-12-01 15:37:06
 */
@Service
@RequiredArgsConstructor
public class ParkingBillInfoServiceImpl extends ServiceImpl<ParkingBillInfoMapper, ParkingBillInfo> implements ParkingBillInfoService {


    private final HaiKangApiUtils haiKangApiUtils;
    private final ObjectMapper objectMapper = new ObjectMapper();


    @Override
    public ParkingBillInfo saveOrUpdateParkingBillInfo(String plateNo) {
        String parkingPaymentInfo = haiKangApiUtils.getParkingPaymentInfo(plateNo);
        if(parkingPaymentInfo==null){
            return null;
        }
        JSONObject jsonObject = new JSONObject(parkingPaymentInfo);
        String data = jsonObject.getJSONObject("data").toString();
        if(data==null){
            return null;
        }
        try {
            ParkingBill vehicleRecord = objectMapper.readValue(data, ParkingBill.class);
            ParkingBillInfo parkingBillInfo = new ParkingBillInfo();
            BeanUtils.copyProperties(vehicleRecord,parkingBillInfo);
            parkingBillInfo.setPayMoneyYuan(vehicleRecord.getPayMoneyYuan());
            parkingBillInfo.setDeductMoneyYuan(vehicleRecord.getDeductMoneyYuan());
            parkingBillInfo.setTotalCostYuan(vehicleRecord.getTotalCostYuan());
            LambdaUpdateWrapper<ParkingBillInfo> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(ParkingBillInfo::getInUnid,parkingBillInfo.getInUnid());
            boolean b = saveOrUpdate(parkingBillInfo, updateWrapper);
            if (b) {
                return parkingBillInfo;
            }else {
                return null;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
