/**
 * BladeX Commercial License Agreement
 * Copyright (c) 2018-2099, https://bladex.cn. All rights reserved.
 * <p>
 * Use of this software is governed by the Commercial License Agreement
 * obtained after purchasing a license from BladeX.
 * <p>
 * 1. This software is for development use only under a valid license
 * from BladeX.
 * <p>
 * 2. Redistribution of this software's source code to any third party
 * without a commercial license is strictly prohibited.
 * <p>
 * 3. Licensees may copyright their own code but cannot use segments
 * from this software for such purposes. Copyright of this software
 * remains with BladeX.
 * <p>
 * Using this software signifies agreement to this License, and the software
 * must not be used for illegal purposes.
 * <p>
 * THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY. The author is
 * not liable for any claims arising from secondary or illegal development.
 * <p>
 * Author: Chill Zhuang (bladejava@qq.com)
 */
package org.springblade.transport.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.system.cache.UserCache;
import org.springblade.transport.excel.MaintenanceRecordExcel;
import org.springblade.transport.excel.MaintenanceRecordExportExcel;
import org.springblade.transport.mapper.MaintenanceRecordMapper;
import org.springblade.transport.pojo.entity.MaintenanceRecord;
import org.springblade.transport.pojo.vo.MaintenanceRecordVO;
import org.springblade.transport.service.IMaintenanceRecordService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 车辆维修记录 服务实现类
 *
 * @author Chill
 */
@Service
public class MaintenanceRecordServiceImpl extends BaseServiceImpl<MaintenanceRecordMapper, MaintenanceRecord> implements IMaintenanceRecordService {

	private static final int VEHICLE_NO_MAX_LENGTH = 30;
	private static final int MAINTAINER_MAX_LENGTH = 20;
	private static final int LOCATION_MAX_LENGTH = 100;
	private static final int REPLACED_PART_MAX_LENGTH = 200;
	private static final int ADDRESS_MAX_LENGTH = 100;
	private static final int REMARK_MAX_LENGTH = 500;

	@Override
	public IPage<MaintenanceRecordVO> selectMaintenanceRecordPage(IPage<MaintenanceRecordVO> page, MaintenanceRecordVO maintenanceRecord) {
		List<MaintenanceRecordVO> records = baseMapper.selectMaintenanceRecordPage(page, maintenanceRecord);
		records.forEach(record -> record.setUpdateUserName(UserCache.getUserRealName(record.getUpdateUser())));
		return page.setRecords(records);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean submit(MaintenanceRecord maintenanceRecord) {
		prepare(maintenanceRecord);
		validate(maintenanceRecord);
		return saveOrUpdate(maintenanceRecord);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public List<MaintenanceRecordExcel> importMaintenanceRecord(List<MaintenanceRecordExcel> data) {
		if (Func.isEmpty(data)) {
			throw new ServiceException("导入数据不能为空");
		}
		List<MaintenanceRecordExcel> errorList = new ArrayList<>();
		for (int index = 0; index < data.size(); index++) {
			MaintenanceRecordExcel excel = data.get(index);
			try {
				MaintenanceRecord maintenanceRecord = Objects.requireNonNull(BeanUtil.copyProperties(excel, MaintenanceRecord.class));
				maintenanceRecord.setCreateTime(null);
				maintenanceRecord.setUpdateTime(null);
				submit(maintenanceRecord);
			} catch (Exception exception) {
				excel.setErrorMessage("第" + (index + 2) + "行：" + exception.getMessage());
				errorList.add(excel);
			}
		}
		return errorList;
	}

	@Override
	public List<MaintenanceRecordExportExcel> exportMaintenanceRecord(Wrapper<MaintenanceRecord> queryWrapper) {
		return list(queryWrapper).stream().map(maintenanceRecord -> {
			MaintenanceRecordExportExcel excel = Objects.requireNonNull(BeanUtil.copyProperties(maintenanceRecord, MaintenanceRecordExportExcel.class));
			excel.setCost(scaleAmount(maintenanceRecord.getCost()));
			excel.setMileage(scaleAmount(nonNegative(maintenanceRecord.getMileage())));
			excel.setUpdateUserName(UserCache.getUserRealName(maintenanceRecord.getUpdateUser()));
			if (Func.isEmpty(excel.getMileageUnit())) {
				excel.setMileageUnit(defaultMileageUnit(maintenanceRecord.getVehicleType()));
			}
			return excel;
		}).toList();
	}

	private void prepare(MaintenanceRecord maintenanceRecord) {
		maintenanceRecord.setVehicleType(trimToEmpty(maintenanceRecord.getVehicleType()));
		maintenanceRecord.setVehicleNo(trimToEmpty(maintenanceRecord.getVehicleNo()));
		maintenanceRecord.setMaintainer(trimToNull(maintenanceRecord.getMaintainer()));
		maintenanceRecord.setLocation(trimToNull(maintenanceRecord.getLocation()));
		maintenanceRecord.setReplacedPart(trimToNull(maintenanceRecord.getReplacedPart()));
		maintenanceRecord.setCompany(trimToNull(maintenanceRecord.getCompany()));
		maintenanceRecord.setContact(trimToNull(maintenanceRecord.getContact()));
		maintenanceRecord.setAddress(trimToNull(maintenanceRecord.getAddress()));
		maintenanceRecord.setRemark(trimToNull(maintenanceRecord.getRemark()));
		if (Func.isEmpty(maintenanceRecord.getMileageUnit())) {
			maintenanceRecord.setMileageUnit(defaultMileageUnit(maintenanceRecord.getVehicleType()));
		}
	}

	private void validate(MaintenanceRecord maintenanceRecord) {
		if (Func.isEmpty(maintenanceRecord.getVehicleType())) {
			throw new ServiceException("车船类型不能为空");
		}
		if (!"车辆".equals(maintenanceRecord.getVehicleType()) && !"船舶".equals(maintenanceRecord.getVehicleType())) {
			throw new ServiceException("车船类型不正确");
		}
		if (Func.isEmpty(maintenanceRecord.getVehicleNo())) {
			throw new ServiceException("车牌号/船号不能为空");
		}
		validateLength(maintenanceRecord.getVehicleNo(), VEHICLE_NO_MAX_LENGTH, "车牌号/船号不能超过30字");
		validateLength(maintenanceRecord.getMaintainer(), MAINTAINER_MAX_LENGTH, "维修人不能超过20字");
		validateLength(maintenanceRecord.getLocation(), LOCATION_MAX_LENGTH, "维修位置不能超过100字");
		validateLength(maintenanceRecord.getReplacedPart(), REPLACED_PART_MAX_LENGTH, "更换零件不能超过200字");
		validateLength(maintenanceRecord.getAddress(), ADDRESS_MAX_LENGTH, "地址不能超过100字");
		validateLength(maintenanceRecord.getRemark(), REMARK_MAX_LENGTH, "备注不能超过500字");
		if (Func.isEmpty(maintenanceRecord.getMaintenanceTime())) {
			throw new ServiceException("维修时间不能为空");
		}
		if (Func.isEmpty(maintenanceRecord.getCost())) {
			throw new ServiceException("费用不能为空");
		}
		validateNonNegative(maintenanceRecord.getCost(), "费用不能小于0");
		validateNonNegative(maintenanceRecord.getMileage(), "里程/航程数不能小于0");
		if (Func.isNotEmpty(maintenanceRecord.getFactoryTime()) && maintenanceRecord.getFactoryTime().isBefore(maintenanceRecord.getMaintenanceTime())) {
			throw new ServiceException("出厂时间不能早于维修时间");
		}
	}

	private void validateLength(String value, int maxLength, String message) {
		if (Func.isNotEmpty(value) && value.length() > maxLength) {
			throw new ServiceException(message);
		}
	}

	private void validateNonNegative(BigDecimal value, String message) {
		if (Func.isNotEmpty(value) && value.compareTo(BigDecimal.ZERO) < 0) {
			throw new ServiceException(message);
		}
	}

	private BigDecimal nonNegative(BigDecimal value) {
		if (Func.isEmpty(value) || value.compareTo(BigDecimal.ZERO) >= 0) {
			return value;
		}
		return BigDecimal.ZERO;
	}

	private BigDecimal scaleAmount(BigDecimal value) {
		return Func.isEmpty(value) ? null : value.setScale(2, RoundingMode.HALF_UP);
	}

	private String defaultMileageUnit(String vehicleType) {
		return "船舶".equals(vehicleType) ? "海里" : "公里";
	}

	private String trimToEmpty(String value) {
		return value == null ? "" : value.trim();
	}

	private String trimToNull(String value) {
		String trimValue = trimToEmpty(value);
		return trimValue.isEmpty() ? null : trimValue;
	}

}
