package com.yuchen.saas.park.service.service.property;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuchen.saas.park.api.entity.property.PropertyFeeMode;
import com.yuchen.saas.park.api.enums.property.AdminFeeModeEnum;
import com.yuchen.saas.park.api.enums.property.ClientFeeModeEnum;
import com.yuchen.saas.park.service.mapper.property.PropertyFeeModeMapper;
import org.nest.springwrap.core.log.exception.ServiceException;
import org.nest.springwrap.core.tool.utils.Func;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class PropertyFeeModeService extends ServiceImpl<PropertyFeeModeMapper, PropertyFeeMode> {


    public void saveFeeMode(PropertyFeeMode propertyFeeMode) {
        this.verifySaveFeeMode(propertyFeeMode);
        this.assembleSaveDto(propertyFeeMode);
        this.saveOrUpdate(propertyFeeMode);
    }

    private void verifySaveFeeMode(PropertyFeeMode propertyFeeMode) {
        if (Func.isEmpty(propertyFeeMode.getId())) {
            LambdaQueryWrapper<PropertyFeeMode> qw = new LambdaQueryWrapper<>();
            qw.eq(PropertyFeeMode::getParkId,propertyFeeMode.getParkId());
            if (this.count(qw) > 0) {
                throw new ServiceException("该园区已设置缴费参数");
            }
        }
    }

    private void assembleSaveDto(PropertyFeeMode propertyFeeMode) {
        if (Func.isEmpty(propertyFeeMode.getId())) {
            propertyFeeMode.setCreateTime(new Date());
        }
    }

    public PropertyFeeMode getFeeMode(Long parkId) {
        if (Func.isEmpty(parkId)) {
            throw new ServiceException("获取收费模式查询parkId参数不能为空");
        }
        LambdaQueryWrapper<PropertyFeeMode> qw = new LambdaQueryWrapper<>();
        qw.eq(PropertyFeeMode::getParkId,parkId);
        PropertyFeeMode feeMode = this.getOne(qw);
        if (feeMode == null) {
            feeMode = new PropertyFeeMode();
            feeMode.setParkId(parkId);
            feeMode.setAdminFeeMode(AdminFeeModeEnum.ALL.getValue());
            feeMode.setClientFeeMode(ClientFeeModeEnum.ALL.getValue());
        }
        return feeMode;
    }

}
