/**
 * 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.transport.excel.AccidentRecordExcel;
import org.springblade.transport.excel.AccidentRecordExportExcel;
import org.springblade.system.cache.UserCache;
import org.springblade.transport.mapper.AccidentRecordMapper;
import org.springblade.transport.pojo.entity.AccidentRecord;
import org.springblade.transport.pojo.vo.AccidentRecordVO;
import org.springblade.transport.service.IAccidentRecordService;
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 AccidentRecordServiceImpl extends BaseServiceImpl<AccidentRecordMapper, AccidentRecord> implements IAccidentRecordService {

	private static final int VEHICLE_NO_MAX_LENGTH = 30;
	private static final int LOCATION_MAX_LENGTH = 100;
	private static final int REASON_DAMAGE_MAX_LENGTH = 500;
	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<AccidentRecordVO> selectAccidentRecordPage(IPage<AccidentRecordVO> page, AccidentRecordVO accidentRecord) {
		List<AccidentRecordVO> records = baseMapper.selectAccidentRecordPage(page, accidentRecord);
		records.forEach(record -> record.setUpdateUserName(UserCache.getUserRealName(record.getUpdateUser())));
		return page.setRecords(records);
	}

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

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

	@Override
	public List<AccidentRecordExportExcel> exportAccidentRecord(Wrapper<AccidentRecord> queryWrapper) {
		return list(queryWrapper).stream().map(accidentRecord -> {
			AccidentRecordExportExcel excel = Objects.requireNonNull(BeanUtil.copyProperties(accidentRecord, AccidentRecordExportExcel.class));
			excel.setDirectEconomicLoss(nonNegative(accidentRecord.getDirectEconomicLoss()));
			excel.setInsuranceClaimAmount(nonNegative(accidentRecord.getInsuranceClaimAmount()));
			excel.setUpdateUserName(UserCache.getUserRealName(accidentRecord.getUpdateUser()));
			return excel;
		}).toList();
	}

	private void prepare(AccidentRecord accidentRecord) {
		accidentRecord.setVehicleType(normalizeVehicleType(accidentRecord.getVehicleType()));
		accidentRecord.setVehicleNo(trimToEmpty(accidentRecord.getVehicleNo()).toUpperCase());
		accidentRecord.setAccidentLocation(trimToNull(accidentRecord.getAccidentLocation()));
		accidentRecord.setAccidentNature(trimToNull(accidentRecord.getAccidentNature()));
		accidentRecord.setAccidentResponsibility(trimToNull(accidentRecord.getAccidentResponsibility()));
		accidentRecord.setAccidentReasonDamage(trimToNull(accidentRecord.getAccidentReasonDamage()));
		accidentRecord.setAttachments(trimToNull(accidentRecord.getAttachments()));
		accidentRecord.setRemark(trimToNull(accidentRecord.getRemark()));
	}

	private void validate(AccidentRecord accidentRecord) {
		if (Func.isEmpty(accidentRecord.getVehicleType())) {
			throw new ServiceException("车船类型不能为空");
		}
		if (!VEHICLE.equals(accidentRecord.getVehicleType()) && !SHIP.equals(accidentRecord.getVehicleType())) {
			throw new ServiceException("车船类型不正确");
		}
		if (Func.isEmpty(accidentRecord.getVehicleNo())) {
			throw new ServiceException("车牌号/船号不能为空");
		}
		if (Func.isEmpty(accidentRecord.getAccidentDate())) {
			throw new ServiceException("事故发生日期不能为空");
		}
		if (Func.isEmpty(accidentRecord.getAccidentNature())) {
			throw new ServiceException("事故性质不能为空");
		}
		if (Func.isEmpty(accidentRecord.getAccidentResponsibility())) {
			throw new ServiceException("事故责任不能为空");
		}
		validateLength(accidentRecord.getVehicleNo(), VEHICLE_NO_MAX_LENGTH, "车牌号/船号不能超过30字");
		validateLength(accidentRecord.getAccidentLocation(), LOCATION_MAX_LENGTH, "事故发生地点不能超过100字");
		validateLength(accidentRecord.getAccidentReasonDamage(), REASON_DAMAGE_MAX_LENGTH, "事故原因及损坏情况不能超过500字");
		validateLength(accidentRecord.getRemark(), REMARK_MAX_LENGTH, "备注不能超过200字");
		validateLength(accidentRecord.getAttachments(), ATTACHMENTS_MAX_LENGTH, "附件不能超过1000字");
		validateMoney(accidentRecord.getDirectEconomicLoss(), "直接经济损失");
		validateMoney(accidentRecord.getInsuranceClaimAmount(), "保险理赔金额");
		if (Func.isNotEmpty(accidentRecord.getInsuranceClaimAmount())
			&& Func.isNotEmpty(accidentRecord.getDirectEconomicLoss())
			&& accidentRecord.getInsuranceClaimAmount().compareTo(accidentRecord.getDirectEconomicLoss()) > 0) {
			throw new ServiceException("保险理赔金额不能超过直接经济损失金额");
		}
	}

	private void validateVehicleTypeImmutable(AccidentRecord accidentRecord) {
		if (Func.isEmpty(accidentRecord.getId())) {
			return;
		}
		AccidentRecord oldRecord = getById(accidentRecord.getId());
		if (oldRecord != null && Func.isNotEmpty(oldRecord.getVehicleType()) && !oldRecord.getVehicleType().equals(accidentRecord.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;
	}

}
