package com.pj.project.tb_car;

import java.io.InputStream;
import java.util.List;

import cn.hutool.core.util.StrUtil;
import cn.hutool.log.StaticLog;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.metadata.ReadSheet;
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.project4sp.global.BusinessException;
import com.pj.utils.so.SoMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * Service: tb_car --
 *
 * @author qzy
 */
@Service
@Transactional
public class TbCarService extends ServiceImpl<TbCarMapper, TbCar> implements IService<TbCar> {

    /**
     * 底层 Mapper 对象
     */
    @Autowired
    TbCarMapper tbCarMapper;
    @Resource
    private ImportCarListener importCarListener;

    /**
     * 增
     */
    void add(TbCar t) {
        String cardNo=t.getCardNo().trim();
        TbCar db = this.findByCardNo(cardNo);
        if (db!=null){
            throw new BusinessException("车辆已存在");
        }
        if (StrUtil.isEmpty(t.getCustomerId())) {
            throw new BusinessException("请选择车辆所属");
        }
        t.setCardNo(cardNo);
        super.save(t);
    }


    /**
     * 删
     */
    void delete(Long id) {
        tbCarMapper.deleteById(id);
    }

    /**
     * 改
     */
    void update(TbCar t) {
        String cardNo=t.getCardNo().trim();
        TbCar db = this.findByCardNo(cardNo);
        if (db!=null&&!StrUtil.equals(t.getId(),db.getId())) {
            throw new BusinessException("车辆已存在");
        }
        t.setCardNo(cardNo);
        super.updateById(t);
    }

    /**
     * 查
     */
    TbCar getById(Long id) {
        return super.getById(id);
    }

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


    public TbCar findByCardNo(String cardNo) {
        QueryWrapper<TbCar> ew = new QueryWrapper<>();
        ew.eq("card_no", cardNo);
        return getOne(ew);
    }

    public void importExcel(MultipartFile file) throws Exception {
        StaticLog.info("file size:{}", file.getSize());
        InputStream is = file.getInputStream();
        importCarListener.list.clear();
        ExcelReader reader = EasyExcel.read(is, ImportCarBO.class, importCarListener).build();
        ReadSheet readSheet = EasyExcel.readSheet(0).build();
        reader.read(readSheet);
        reader.finish();
        is.close();
    }
}
