package cn.iocoder.yudao.module.custom.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.mybatis.core.dataobject.BaseDO;
import cn.iocoder.yudao.module.custom.entity.CustomerCar;
import cn.iocoder.yudao.module.custom.mapper.CustomerCarMapper;
import cn.iocoder.yudao.module.custom.service.CustomerCarService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.List;

import static cn.iocoder.yudao.common.BaseConstants.CUS_SIGN_CAR;
import static cn.iocoder.yudao.common.BaseConstants.CUS_SIGN_CUSTOMER;

/**
 * 客户车辆管理关联
 *
 * @author pqz
 */
@Service
@Validated
public class CustomerCarServiceImpl extends ServiceImpl<CustomerCarMapper, CustomerCar> implements CustomerCarService {


    /**
     * 保存客户与车辆的关联关系
     *
     * @param mainId       主表id
     * @param mainTable    主表标识（cust：客户，car：车辆）
     * @param customerCars List<CustomerCar>
     * @return void
     * @author PQZ
     * @date 18:45 2024/8/3
     **/
    @Override
    public void bindCustomerCar(String mainId, String mainTable, List<CustomerCar> customerCars) {
        /*1、删除已有关联关系*/
        LambdaQueryWrapper<CustomerCar> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(BaseDO::getDeleted, 0);
        if (CUS_SIGN_CUSTOMER.equals(mainTable)) {
            //如果主表是客户表
            lambdaQueryWrapper.eq(CustomerCar::getCusId, mainId);
            this.remove(lambdaQueryWrapper);
        } else if(CUS_SIGN_CAR.equals(mainTable)){
            //如果主表是车辆表
            lambdaQueryWrapper.eq(CustomerCar::getCarId, mainId);
            this.remove(lambdaQueryWrapper);
        }

        /*2、保存新关联关系*/
        if (ObjectUtil.isNotEmpty(customerCars) && !customerCars.isEmpty()) {
            customerCars.forEach(item -> {
                //防止主键重复
                item.setId(null);
            });
            this.saveBatch(customerCars);
        }

    }
}