/**
 * 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.AnnualInspectionRecordExcel;
import org.springblade.transport.excel.AnnualInspectionRecordExportExcel;
import org.springblade.transport.mapper.AnnualInspectionRecordMapper;
import org.springblade.transport.pojo.entity.AnnualInspectionRecord;
import org.springblade.transport.pojo.vo.AnnualInspectionRecordVO;
import org.springblade.transport.service.IAnnualInspectionRecordService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 年检记录 服务实现类
 *
 * @author Chill
 */
@Service
public class AnnualInspectionRecordServiceImpl extends BaseServiceImpl<AnnualInspectionRecordMapper, AnnualInspectionRecord> implements IAnnualInspectionRecordService {

	private static final int VEHICLE_NO_MAX_LENGTH = 30;
	private static final int PASSENGER_TYPE_LEVEL_MAX_LENGTH = 50;
	private static final int INSPECTION_UNIT_MAX_LENGTH = 50;
	private static final int ASSESSMENT_UNIT_MAX_LENGTH = 50;
	private static final int REMARK_MAX_LENGTH = 200;
	private static final int ATTACHMENTS_MAX_LENGTH = 1000;
	private static final int MONEY_SCALE = 2;
	private static final String VEHICLE = "车辆";
	private static final String SHIP = "船舶";

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

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

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

	@Override
	public List<AnnualInspectionRecordExportExcel> exportAnnualInspectionRecord(Wrapper<AnnualInspectionRecord> queryWrapper) {
		return list(queryWrapper).stream().map(annualInspectionRecord -> {
			AnnualInspectionRecordExportExcel excel = Objects.requireNonNull(BeanUtil.copyProperties(annualInspectionRecord, AnnualInspectionRecordExportExcel.class));
			excel.setVehicleTechnicalLevel(VEHICLE.equals(annualInspectionRecord.getVehicleType()) ? annualInspectionRecord.getVehicleTechnicalLevel() : null);
			excel.setShipInspectionType(SHIP.equals(annualInspectionRecord.getVehicleType()) ? annualInspectionRecord.getShipInspectionType() : null);
			excel.setFee(nonNegative(annualInspectionRecord.getFee()));
			excel.setUpdateUserName(UserCache.getUserRealName(annualInspectionRecord.getUpdateUser()));
			return excel;
		}).toList();
	}

	private void prepare(AnnualInspectionRecord annualInspectionRecord) {
		annualInspectionRecord.setVehicleType(normalizeVehicleType(annualInspectionRecord.getVehicleType()));
		annualInspectionRecord.setVehicleNo(trimToEmpty(annualInspectionRecord.getVehicleNo()).toUpperCase());
		annualInspectionRecord.setVehicleTechnicalLevel(trimToNull(annualInspectionRecord.getVehicleTechnicalLevel()));
		annualInspectionRecord.setShipInspectionType(trimToNull(annualInspectionRecord.getShipInspectionType()));
		annualInspectionRecord.setPassengerTypeLevel(trimToNull(annualInspectionRecord.getPassengerTypeLevel()));
		annualInspectionRecord.setInspectionUnit(trimToNull(annualInspectionRecord.getInspectionUnit()));
		annualInspectionRecord.setAssessmentUnit(trimToNull(annualInspectionRecord.getAssessmentUnit()));
		annualInspectionRecord.setAttachments(trimToNull(annualInspectionRecord.getAttachments()));
		annualInspectionRecord.setRemark(trimToNull(annualInspectionRecord.getRemark()));
		if (annualInspectionRecord.getInspectionAssessmentDate() == null) {
			annualInspectionRecord.setInspectionAssessmentDate(LocalDate.now());
		}
		if (VEHICLE.equals(annualInspectionRecord.getVehicleType())) {
			annualInspectionRecord.setShipInspectionType(null);
		} else {
			annualInspectionRecord.setVehicleTechnicalLevel(null);
			annualInspectionRecord.setPassengerTypeLevel(null);
		}
	}

	private void validate(AnnualInspectionRecord annualInspectionRecord) {
		if (Func.isEmpty(annualInspectionRecord.getVehicleType())) {
			throw new ServiceException("车船类型不能为空");
		}
		if (!VEHICLE.equals(annualInspectionRecord.getVehicleType()) && !SHIP.equals(annualInspectionRecord.getVehicleType())) {
			throw new ServiceException("车船类型不正确");
		}
		if (Func.isEmpty(annualInspectionRecord.getVehicleNo())) {
			throw new ServiceException("车牌号/船号不能为空");
		}
		if (VEHICLE.equals(annualInspectionRecord.getVehicleType()) && Func.isEmpty(annualInspectionRecord.getVehicleTechnicalLevel())) {
			throw new ServiceException("车辆技术等级不能为空");
		}
		if (SHIP.equals(annualInspectionRecord.getVehicleType()) && Func.isEmpty(annualInspectionRecord.getShipInspectionType())) {
			throw new ServiceException("船舶检验类型不能为空");
		}
		if (Func.isEmpty(annualInspectionRecord.getValidUntilDate())) {
			throw new ServiceException("有效期截止日不能为空");
		}
		if (!annualInspectionRecord.getValidUntilDate().isAfter(annualInspectionRecord.getInspectionAssessmentDate())) {
			throw new ServiceException("有效期截止日应大于检测评定日期");
		}
		if (Func.isEmpty(annualInspectionRecord.getFee())) {
			throw new ServiceException("费用不能为空");
		}
		validateLength(annualInspectionRecord.getVehicleNo(), VEHICLE_NO_MAX_LENGTH, "车牌号/船号不能超过30字");
		validateLength(annualInspectionRecord.getPassengerTypeLevel(), PASSENGER_TYPE_LEVEL_MAX_LENGTH, "客车类型及等级不能超过50字");
		validateLength(annualInspectionRecord.getInspectionUnit(), INSPECTION_UNIT_MAX_LENGTH, "检测评定单位不能超过50字");
		validateLength(annualInspectionRecord.getAssessmentUnit(), ASSESSMENT_UNIT_MAX_LENGTH, "评定(复核)单位不能超过50字");
		validateLength(annualInspectionRecord.getRemark(), REMARK_MAX_LENGTH, "备注不能超过200字");
		validateLength(annualInspectionRecord.getAttachments(), ATTACHMENTS_MAX_LENGTH, "附件不能超过1000字");
		validateMoney(annualInspectionRecord.getFee(), "费用");
	}

	private void validateVehicleTypeImmutable(AnnualInspectionRecord annualInspectionRecord) {
		if (Func.isEmpty(annualInspectionRecord.getId())) {
			return;
		}
		AnnualInspectionRecord oldRecord = getById(annualInspectionRecord.getId());
		if (oldRecord != null && Func.isNotEmpty(oldRecord.getVehicleType()) && !oldRecord.getVehicleType().equals(annualInspectionRecord.getVehicleType())) {
			throw new ServiceException("车船类型保存后不可修改");
		}
	}

	private void validateMoney(BigDecimal value, String fieldName) {
		if (Func.isEmpty(value)) {
			return;
		}
		if (value.compareTo(BigDecimal.ZERO) < 0) {
			throw new ServiceException(fieldName + "不能小于0");
		}
		if (value.stripTrailingZeros().scale() > MONEY_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 normalizeVehicleType(String vehicleType) {
		String value = trimToEmpty(vehicleType);
		return value.isEmpty() ? VEHICLE : value;
	}

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

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

}
