package com.pj.project.tb_pass_record;

import java.util.Date;
import java.util.List;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pj.utils.so.SoMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * Service: tb_pass_record -- 放行日志
 * @author lzm 
 */
@Service
@Transactional
public class TbPassRecordService extends ServiceImpl<TbPassRecordMapper, TbPassRecord> implements IService<TbPassRecord> {

	/** 底层 Mapper 对象 */
	@Autowired
	TbPassRecordMapper tbPassRecordMapper;

	/** 增 */
	int add(TbPassRecord t){
		return tbPassRecordMapper.add(t);
	}

	/** 删 */
	int delete(Long id){
		return tbPassRecordMapper.delete(id);
	}

	/** 改 */
	int update(TbPassRecord t){
		return tbPassRecordMapper.update(t);
	}

	/** 查 */
	TbPassRecord getById(Long id){
		return tbPassRecordMapper.getById(id);
	}

	/** 查集合 - 根据条件（参数为空时代表忽略指定条件） */
        public List<TbPassRecord> getList(SoMap so) {
            return tbPassRecordMapper.getList(so);
	}

    public TbPassRecord getByBusinessId(String businessId){
        return tbPassRecordMapper.getByBusinessId(businessId);
    }

    public TbPassRecord getByBusinessIdAndCountryName(String businessId, String carCountryName){
        return tbPassRecordMapper.getByBusinessIdAndCountryName(businessId, carCountryName);
    }

    /** 初始化或更新一条出入记录, 越南车和中国车分开 */
    @Async
    public void addOrUpdate(String businessId, String customerId, String customerName, String carNo, int status, Date inTime, Date outTime, String carCountryName){
        TbPassRecord record = this.getByBusinessIdAndCountryName(businessId, carCountryName);
        if(record == null)
            record = new TbPassRecord();
        record.setBusinessId(businessId)
            .setCustomerId(customerId).setCustomerName(customerName)
            .setCardNo(carNo).setStatus(status)
            .setInTime(inTime).setOutTime(outTime)
            .setCarCountryName(carCountryName)
            .setUpdateTime(new Date());
        if(record.getInTime() != null && record.getOutTime() != null){
            long minutes = DateUtil.between(record.getInTime(), record.getOutTime(), DateUnit.MINUTE);
            record.setPartTime(minutes);
        }
        saveOrUpdate(record);
    }

    public void removeByBusinessId(String businessId) {
       tbPassRecordMapper.deleteByBusinessId(businessId);
    }
}
