/**
 * 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.MaintenancePlanExcel;
import org.springblade.transport.excel.MaintenancePlanExportExcel;
import org.springblade.transport.mapper.MaintenancePlanMapper;
import org.springblade.transport.pojo.entity.MaintenancePlan;
import org.springblade.transport.pojo.vo.MaintenancePlanVO;
import org.springblade.transport.service.IMaintenancePlanService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 车辆保养计划 服务实现类
 *
 * @author Chill
 */
@Service
public class MaintenancePlanServiceImpl extends BaseServiceImpl<MaintenancePlanMapper, MaintenancePlan> implements IMaintenancePlanService {

	private static final int VEHICLE_NO_MAX_LENGTH = 30;
	private static final int MAINTAINER_MAX_LENGTH = 20;
	private static final int MAINTENANCE_ITEM_MAX_LENGTH = 100;
	private static final int ADDRESS_MAX_LENGTH = 100;
	private static final int REMARK_MAX_LENGTH = 500;

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

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

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

	@Override
	public List<MaintenancePlanExportExcel> exportMaintenancePlan(Wrapper<MaintenancePlan> queryWrapper) {
		return list(queryWrapper).stream().map(maintenancePlan -> {
			MaintenancePlanExportExcel excel = Objects.requireNonNull(BeanUtil.copyProperties(maintenancePlan, MaintenancePlanExportExcel.class));
			excel.setUpdateUserName(UserCache.getUserRealName(maintenancePlan.getUpdateUser()));
			excel.setMileage(nonNegative(maintenancePlan.getMileage()));
			excel.setNextMaintenanceMileage(nonNegative(maintenancePlan.getNextMaintenanceMileage()));
			if (Func.isEmpty(excel.getMileageUnit())) {
				excel.setMileageUnit(defaultMileageUnit(maintenancePlan.getVehicleType()));
			}
			return excel;
		}).toList();
	}

	private void prepare(MaintenancePlan maintenancePlan) {
		maintenancePlan.setVehicleType(trimToEmpty(maintenancePlan.getVehicleType()));
		maintenancePlan.setVehicleNo(trimToEmpty(maintenancePlan.getVehicleNo()));
		maintenancePlan.setMaintainer(trimToNull(maintenancePlan.getMaintainer()));
		maintenancePlan.setMaintenanceItem(trimToNull(maintenancePlan.getMaintenanceItem()));
		maintenancePlan.setStoreName(trimToNull(maintenancePlan.getStoreName()));
		maintenancePlan.setContactPhone(trimToNull(maintenancePlan.getContactPhone()));
		maintenancePlan.setAddress(trimToNull(maintenancePlan.getAddress()));
		maintenancePlan.setRemark(trimToNull(maintenancePlan.getRemark()));
		if (Func.isEmpty(maintenancePlan.getMileageUnit())) {
			maintenancePlan.setMileageUnit(defaultMileageUnit(maintenancePlan.getVehicleType()));
		}
	}

	private void validate(MaintenancePlan maintenancePlan) {
		if (Func.isEmpty(maintenancePlan.getVehicleType())) {
			throw new ServiceException("车船类型不能为空");
		}
		if (!"车辆".equals(maintenancePlan.getVehicleType()) && !"船舶".equals(maintenancePlan.getVehicleType())) {
			throw new ServiceException("车船类型不正确");
		}
		if (Func.isEmpty(maintenancePlan.getVehicleNo())) {
			throw new ServiceException("车牌号/船号不能为空");
		}
		validateLength(maintenancePlan.getVehicleNo(), VEHICLE_NO_MAX_LENGTH, "车牌号/船号不能超过30字");
		validateLength(maintenancePlan.getMaintainer(), MAINTAINER_MAX_LENGTH, "保养人不能超过20字");
		validateLength(maintenancePlan.getMaintenanceItem(), MAINTENANCE_ITEM_MAX_LENGTH, "保养项目不能超过100字");
		validateLength(maintenancePlan.getAddress(), ADDRESS_MAX_LENGTH, "地址不能超过100字");
		validateLength(maintenancePlan.getRemark(), REMARK_MAX_LENGTH, "备注不能超过500字");
		if (Func.isEmpty(maintenancePlan.getMaintenanceTime())) {
			throw new ServiceException("保养时间不能为空");
		}
		if (Func.isEmpty(maintenancePlan.getCost())) {
			throw new ServiceException("费用不能为空");
		}
		validateNonNegative(maintenancePlan.getCost(), "费用不能小于0");
		validateNonNegative(maintenancePlan.getMileage(), "里程/航程数不能小于0");
		validateNonNegative(maintenancePlan.getNextMaintenanceMileage(), "下次保养里程/航程不能小于0");
		if (Func.isNotEmpty(maintenancePlan.getNextMaintenanceTime()) && maintenancePlan.getNextMaintenanceTime().isBefore(maintenancePlan.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 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;
	}

}
