/**
 * 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.MileageRecordExcel;
import org.springblade.transport.excel.MileageRecordExportExcel;
import org.springblade.transport.mapper.MileageRecordMapper;
import org.springblade.transport.pojo.entity.MileageRecord;
import org.springblade.transport.pojo.vo.MileageRecordVO;
import org.springblade.transport.service.IMileageRecordService;
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 MileageRecordServiceImpl extends BaseServiceImpl<MileageRecordMapper, MileageRecord> implements IMileageRecordService {

	private static final int VEHICLE_NO_MAX_LENGTH = 30;
	private static final int REMARK_MAX_LENGTH = 200;
	private static final int ATTACHMENTS_MAX_LENGTH = 1000;
	private static final int MILEAGE_SCALE = 2;
	private static final String VEHICLE_TYPE_VEHICLE = "车辆";
	private static final String VEHICLE_TYPE_SHIP = "船舶";

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

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

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

	@Override
	public List<MileageRecordExportExcel> exportMileageRecord(Wrapper<MileageRecord> queryWrapper) {
		return list(queryWrapper).stream().map(mileageRecord -> {
			MileageRecordExportExcel excel = Objects.requireNonNull(
				BeanUtil.copyProperties(mileageRecord, MileageRecordExportExcel.class)
			);
			excel.setPreviousMonthMileage(nonNegative(mileageRecord.getPreviousMonthMileage()));
			excel.setCurrentMonthMileage(nonNegative(mileageRecord.getCurrentMonthMileage()));
			excel.setMonthlyMileage(nonNegative(mileageRecord.getMonthlyMileage()));
			excel.setTotalMileage(nonNegative(mileageRecord.getTotalMileage()));
			excel.setUpdateUserName(UserCache.getUserRealName(mileageRecord.getUpdateUser()));
			return excel;
		}).toList();
	}

	private void prepare(MileageRecord mileageRecord) {
		mileageRecord.setVehicleType(trimToEmpty(mileageRecord.getVehicleType()));
		if (Func.isEmpty(mileageRecord.getVehicleType())) {
			mileageRecord.setVehicleType(VEHICLE_TYPE_VEHICLE);
		}
		mileageRecord.setVehicleNo(
			normalizeVehicleNo(mileageRecord.getVehicleNo(), mileageRecord.getVehicleType())
		);
		mileageRecord.setMileageUnit(defaultMileageUnit(mileageRecord.getVehicleType()));
		mileageRecord.setRemark(trimToNull(mileageRecord.getRemark()));
		mileageRecord.setAttachments(trimToNull(mileageRecord.getAttachments()));
		if (mileageRecord.getMonthlyMileage() == null
			&& mileageRecord.getPreviousMonthMileage() != null
			&& mileageRecord.getCurrentMonthMileage() != null) {
			mileageRecord.setMonthlyMileage(mileageRecord.getCurrentMonthMileage().subtract(mileageRecord.getPreviousMonthMileage()));
		}
	}

	private void validate(MileageRecord mileageRecord) {
		boolean isShip = VEHICLE_TYPE_SHIP.equals(mileageRecord.getVehicleType());
		if (!VEHICLE_TYPE_VEHICLE.equals(mileageRecord.getVehicleType()) && !isShip) {
			throw new ServiceException("车船类型不正确");
		}
		if (Func.isEmpty(mileageRecord.getVehicleNo())) {
			throw new ServiceException(isShip ? "船号不能为空" : "车牌号不能为空");
		}
		validateLength(
			mileageRecord.getVehicleNo(),
			VEHICLE_NO_MAX_LENGTH,
			isShip ? "船号不能超过30字" : "车牌号不能超过30字"
		);
		validateLength(mileageRecord.getRemark(), REMARK_MAX_LENGTH, "备注不能超过200字");
		validateLength(mileageRecord.getAttachments(), ATTACHMENTS_MAX_LENGTH, "附件不能超过1000字");
		validateMileage(mileageRecord.getPreviousMonthMileage(), isShip ? "上月统计航程数" : "上月统计里程数");
		validateMileage(mileageRecord.getCurrentMonthMileage(), isShip ? "本月统计航程数" : "本月统计里程数");
		validateMileage(mileageRecord.getMonthlyMileage(), isShip ? "本月航行航程数" : "本月行驶里程数");
		validateMileage(mileageRecord.getTotalMileage(), isShip ? "累计航程数" : "累计行驶里程数");
		validateMonthlyMileageConsistency(mileageRecord);
		if (mileageRecord.getTotalMileage() != null
			&& mileageRecord.getCurrentMonthMileage() != null
			&& mileageRecord.getTotalMileage().compareTo(mileageRecord.getCurrentMonthMileage()) < 0) {
			throw new ServiceException(
				isShip ? "累计航程数应大于等于本月统计航程数" : "累计行驶里程数应大于等于本月统计里程数"
			);
		}
	}

	private void validateMonthlyMileageConsistency(MileageRecord mileageRecord) {
		if (mileageRecord.getPreviousMonthMileage() == null
			|| mileageRecord.getCurrentMonthMileage() == null
			|| mileageRecord.getMonthlyMileage() == null) {
			return;
		}
		BigDecimal calculated = mileageRecord.getCurrentMonthMileage().subtract(mileageRecord.getPreviousMonthMileage());
		if (calculated.compareTo(mileageRecord.getMonthlyMileage()) != 0) {
			if (VEHICLE_TYPE_SHIP.equals(mileageRecord.getVehicleType())) {
				throw new ServiceException("本月航行航程数应等于本月统计航程数减去上月统计航程数");
			}
			throw new ServiceException("本月行驶里程数应等于本月统计里程数减去上月统计里程数");
		}
	}

	private void validateVehicleNoImmutable(MileageRecord mileageRecord) {
		if (Func.isEmpty(mileageRecord.getId())) {
			return;
		}
		MileageRecord oldRecord = getById(mileageRecord.getId());
		if (oldRecord != null
			&& Func.isNotEmpty(oldRecord.getVehicleNo())
			&& !oldRecord.getVehicleNo().equals(mileageRecord.getVehicleNo())) {
			throw new ServiceException("车牌号/船号保存后不可修改");
		}
	}

	private void validateMileage(BigDecimal value, String fieldName) {
		if (Func.isEmpty(value)) {
			return;
		}
		if (value.compareTo(BigDecimal.ZERO) < 0) {
			throw new ServiceException(fieldName + "不能小于0");
		}
		if (value.stripTrailingZeros().scale() > MILEAGE_SCALE) {
			throw new ServiceException(fieldName + "最多保留2位小数");
		}
	}

	private void validateLength(String value, int maxLength, String message) {
		if (Func.isNotEmpty(value) && value.length() > maxLength) {
			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 VEHICLE_TYPE_SHIP.equals(vehicleType) ? "海里" : "公里";
	}

	private String normalizeVehicleNo(String vehicleNo, String vehicleType) {
		String trimValue = trimToEmpty(vehicleNo);
		return VEHICLE_TYPE_SHIP.equals(vehicleType) ? trimValue : trimValue.toUpperCase();
	}

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

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

}
