/**
 * BladeX Commercial License Agreement
 * Copyright (c) 2018-2099, https://bladex.cn. All rights reserved.
 * <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.EtcRecordExcel;
import org.springblade.transport.excel.EtcRecordExportExcel;
import org.springblade.transport.mapper.EtcRecordMapper;
import org.springblade.transport.pojo.entity.EtcRecord;
import org.springblade.transport.pojo.vo.EtcRecordVO;
import org.springblade.transport.service.IEtcRecordService;
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;

/**
 * ETC记录 服务实现类
 *
 * @author Chill
 */
@Service
public class EtcRecordServiceImpl extends BaseServiceImpl<EtcRecordMapper, EtcRecord> implements IEtcRecordService {

	private static final int VEHICLE_NO_MAX_LENGTH = 30;
	private static final int ETC_CARD_NO_MAX_LENGTH = 30;
	private static final int STATION_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;

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

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

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

	@Override
	public List<EtcRecordExportExcel> exportEtcRecord(Wrapper<EtcRecord> queryWrapper) {
		return list(queryWrapper).stream().map(etcRecord -> {
			EtcRecordExportExcel excel = Objects.requireNonNull(BeanUtil.copyProperties(etcRecord, EtcRecordExportExcel.class));
			excel.setTransactionAmount(nonNegative(etcRecord.getTransactionAmount()));
			excel.setUpdateUserName(UserCache.getUserRealName(etcRecord.getUpdateUser()));
			return excel;
		}).toList();
	}

	private void prepare(EtcRecord etcRecord) {
		etcRecord.setVehicleNo(trimToEmpty(etcRecord.getVehicleNo()).toUpperCase());
		etcRecord.setEtcCardNo(trimToNull(etcRecord.getEtcCardNo()));
		etcRecord.setEntryStation(trimToNull(etcRecord.getEntryStation()));
		etcRecord.setExitStation(trimToNull(etcRecord.getExitStation()));
		etcRecord.setDataSource(defaultDataSource(etcRecord.getDataSource()));
		etcRecord.setAttachments(trimToNull(etcRecord.getAttachments()));
		etcRecord.setRemark(trimToNull(etcRecord.getRemark()));
	}

	private void validate(EtcRecord etcRecord) {
		if (Func.isEmpty(etcRecord.getVehicleNo())) {
			throw new ServiceException("车牌号不能为空");
		}
		if (Func.isEmpty(etcRecord.getEtcCardNo())) {
			throw new ServiceException("ETC卡号不能为空");
		}
		if (Func.isEmpty(etcRecord.getExitTime())) {
			throw new ServiceException("出口时间不能为空");
		}
		if (Func.isEmpty(etcRecord.getTransactionAmount())) {
			throw new ServiceException("交易金额不能为空");
		}
		if (Func.isNotEmpty(etcRecord.getEntryTime()) && !etcRecord.getExitTime().isAfter(etcRecord.getEntryTime())) {
			throw new ServiceException("出口时间应大于入口时间");
		}
		validateLength(etcRecord.getVehicleNo(), VEHICLE_NO_MAX_LENGTH, "车牌号不能超过30字");
		validateLength(etcRecord.getEtcCardNo(), ETC_CARD_NO_MAX_LENGTH, "ETC卡号不能超过30字");
		validateLength(etcRecord.getEntryStation(), STATION_MAX_LENGTH, "入口站不能超过50字");
		validateLength(etcRecord.getExitStation(), STATION_MAX_LENGTH, "出口站不能超过50字");
		validateLength(etcRecord.getRemark(), REMARK_MAX_LENGTH, "备注不能超过200字");
		validateLength(etcRecord.getAttachments(), ATTACHMENTS_MAX_LENGTH, "附件不能超过1000字");
		validateMoney(etcRecord.getTransactionAmount(), "交易金额");
	}

	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 + "最多保留" + MONEY_SCALE + "位小数");
		}
	}

	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 defaultDataSource(String dataSource) {
		String value = trimToEmpty(dataSource);
		return value.isEmpty() ? "手工录入" : 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;
	}

}
