package com.yeejoin.equipmanage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yeejoin.equipmanage.common.entity.Car;
import com.yeejoin.equipmanage.common.entity.EquipmentQrcode;
import com.yeejoin.equipmanage.common.utils.QRCodeUtil;
import com.yeejoin.equipmanage.mapper.CarMapper;
import com.yeejoin.equipmanage.mapper.EquipmentQrcodeMapper;
import com.yeejoin.equipmanage.service.ProductionQRCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * 车辆二维码生成
 * 
 **/
@Service
public class CarProductionQRCode implements ProductionQRCode {
	@Autowired
	EquipmentQrcodeMapper equipmentQrcodeMapper;
	@Autowired
	CarMapper carMapper;

	@Override
	public List<EquipmentQrcode> getProductionQRCode(Long id, Integer amount, Date productDate) {
		List<EquipmentQrcode> equipmentQRCodes = new ArrayList<>(amount);
		QueryWrapper queryWrapper = new QueryWrapper();
		queryWrapper.eq("car_id", id);
		List<EquipmentQrcode> equipmentQRCode = equipmentQrcodeMapper.selectList(queryWrapper);

		if (equipmentQRCode != null && equipmentQRCode.size() == 1) {
			for (int i = 0; i < amount; i++) {
				EquipmentQrcode code = new EquipmentQrcode();
				code.setCreateDate(equipmentQRCode.get(0).getCreateDate());
				code.setCarId(equipmentQRCode.get(0).getCarId());
				code.setIsSingleUsed(equipmentQRCode.get(0).getIsSingleUsed());
				code.setQRCode(equipmentQRCode.get(0).getQRCode());
				code.setId(equipmentQRCode.get(0).getId());
				code.setFullQRCode("03#" + code.getQRCode());
				equipmentQRCodes.add(code);
			}
		} else {
			Car car = carMapper.selectById(id);
			if (car == null) {
				throw new RuntimeException("请先录入该车辆信息！");
			}
			EquipmentQrcode equipmentQRCode1 = new EquipmentQrcode();
			equipmentQRCode1.setCarId(id);
			equipmentQRCode1.setIsSingleUsed(true);
			equipmentQRCode1.setProductDate(productDate);
			equipmentQrcodeMapper.insert(equipmentQRCode1);
			// 生成QRCode
			equipmentQRCode1.setQRCode(QRCodeUtil.generateQRCode());
			car.setQrCode(equipmentQRCode1.getQRCode());
			carMapper.updateById(car);
			equipmentQrcodeMapper.updateById(equipmentQRCode1);
			equipmentQRCode1.setFullQRCode("03#" + equipmentQRCode1.getQRCode());
			equipmentQRCodes.add(equipmentQRCode1);
		}
		return equipmentQRCodes;
	}

}
