package com.pj.project.tb_car;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.validation.ValidationUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.pj.constants.UserTypeEnum;
import com.pj.project.tb_costomer.TbCostomer;
import com.pj.project.tb_costomer.TbCostomerService;
import com.pj.project4sp.global.BusinessException;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Component
public class ImportCarListener extends AnalysisEventListener<ImportCarBO> {
    @Resource
    @Lazy
    private TbCarService tbCarService;

    @Resource
    private TbCostomerService tbCostomerService;


    public List<ImportCarBO> list = new ArrayList<>();

    @Override
    public void invoke(ImportCarBO importCarBO, AnalysisContext analysisContext) {
        if (StrUtil.isNotEmpty(importCarBO.getCustomerName())) {
            list.add(importCarBO);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        List<TbCar> cars = new ArrayList<>();
        list.forEach(importCarBO -> {
            String customerName = importCarBO.getCustomerName();
            String customerId = UserTypeEnum.PLATFORM_ADMIN.getCustomerId();
            if (!StrUtil.equals(customerName, UserTypeEnum.PLATFORM_ADMIN.getDesc())) {
                TbCostomer tbCostomer = tbCostomerService.findByName(customerName);
                if (tbCostomer == null) {
                    throw new BusinessException("系统找不到：" + customerName + "企业");
                }
                customerId = tbCostomer.getId();
            }
            String carNo = importCarBO.getCardNo();
            if (StrUtil.isEmpty(carNo)) {
                throw new BusinessException(customerName + "的车牌号不能为空");
            }
            carNo = carNo.toUpperCase().trim();
            TbCar db = tbCarService.findByCardNo(carNo);
            if (db == null) {
                db = new TbCar();
            }
            String carType = importCarBO.getCarType();
            Integer type = TbCar.CarTypeEnum.getType(carType);
            BeanUtil.copyProperties(importCarBO, db, "carType");
            db.setCardNo(carNo).setCarType(type).setCustomerId(customerId);
            cars.add(db);
        });
        tbCarService.saveOrUpdateBatch(cars);
    }
}
