/**
 * 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.OilElectricRecordExcel;
import org.springblade.transport.excel.OilElectricRecordExportExcel;
import org.springblade.transport.mapper.OilElectricRecordMapper;
import org.springblade.transport.pojo.entity.OilElectricRecord;
import org.springblade.transport.pojo.vo.OilElectricRecordVO;
import org.springblade.transport.service.IOilElectricRecordService;
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;
import java.util.Set;

/**
 * 油电记录 服务实现类
 *
 * @author Chill
 */
@Service
public class OilElectricRecordServiceImpl extends BaseServiceImpl<OilElectricRecordMapper, OilElectricRecord> implements IOilElectricRecordService {

	private static final int VEHICLE_NO_MAX_LENGTH = 30;
	private static final int CARD_NO_MAX_LENGTH = 30;
	private static final int CARD_HOLDER_MAX_LENGTH = 20;
	private static final int OIL_PRODUCT_MAX_LENGTH = 50;
	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;
	private static final int QUANTITY_SCALE = 2;
	private static final String VEHICLE = "车辆";
	private static final String SHIP = "船舶";
	private static final String FUEL = "加油";
	private static final String ELECTRIC = "充电";
	private static final Set<String> FEE_TYPES = Set.of(FUEL, ELECTRIC);

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

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

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

	@Override
	public List<OilElectricRecordExportExcel> exportOilElectricRecord(Wrapper<OilElectricRecord> queryWrapper) {
		return list(queryWrapper).stream().map(oilElectricRecord -> {
			OilElectricRecordExportExcel excel = Objects.requireNonNull(BeanUtil.copyProperties(oilElectricRecord, OilElectricRecordExportExcel.class));
			excel.setQuantity(nonNegative(oilElectricRecord.getQuantity()));
			excel.setUnitPrice(nonNegative(oilElectricRecord.getUnitPrice()));
			excel.setTransactionAmount(nonNegative(oilElectricRecord.getTransactionAmount()));
			excel.setBalance(nonNegative(oilElectricRecord.getBalance()));
			excel.setUpdateUserName(UserCache.getUserRealName(oilElectricRecord.getUpdateUser()));
			return excel;
		}).toList();
	}

	private void prepare(OilElectricRecord oilElectricRecord) {
		oilElectricRecord.setVehicleType(normalizeVehicleType(oilElectricRecord.getVehicleType()));
		oilElectricRecord.setVehicleNo(trimToEmpty(oilElectricRecord.getVehicleNo()));
		if (VEHICLE.equals(oilElectricRecord.getVehicleType())) {
			oilElectricRecord.setVehicleNo(oilElectricRecord.getVehicleNo().toUpperCase());
		}
		oilElectricRecord.setFeeType(trimToNull(oilElectricRecord.getFeeType()));
		oilElectricRecord.setOilProduct(trimToNull(oilElectricRecord.getOilProduct()));
		oilElectricRecord.setCardNo(trimToNull(oilElectricRecord.getCardNo()));
		oilElectricRecord.setCardHolder(trimToNull(oilElectricRecord.getCardHolder()));
		oilElectricRecord.setStation(trimToNull(oilElectricRecord.getStation()));
		oilElectricRecord.setDataSource(defaultDataSource(oilElectricRecord.getDataSource()));
		oilElectricRecord.setAttachments(trimToNull(oilElectricRecord.getAttachments()));
		oilElectricRecord.setRemark(trimToNull(oilElectricRecord.getRemark()));
		if (ELECTRIC.equals(oilElectricRecord.getFeeType())) {
			oilElectricRecord.setOilProduct(null);
		}
	}

	private void validate(OilElectricRecord oilElectricRecord) {
		if (Func.isEmpty(oilElectricRecord.getVehicleType())) {
			throw new ServiceException("车船类型不能为空");
		}
		if (!VEHICLE.equals(oilElectricRecord.getVehicleType()) && !SHIP.equals(oilElectricRecord.getVehicleType())) {
			throw new ServiceException("车船类型不正确");
		}
		if (Func.isEmpty(oilElectricRecord.getVehicleNo())) {
			throw new ServiceException("车牌号/船号不能为空");
		}
		if (Func.isEmpty(oilElectricRecord.getTransactionTime())) {
			throw new ServiceException("交易时间不能为空");
		}
		if (Func.isEmpty(oilElectricRecord.getFeeType())) {
			throw new ServiceException("费用类型不能为空");
		}
		if (!FEE_TYPES.contains(oilElectricRecord.getFeeType())) {
			throw new ServiceException("费用类型不正确");
		}
		if (Func.isEmpty(oilElectricRecord.getTransactionAmount())) {
			throw new ServiceException("交易金额不能为空");
		}
		validateLength(oilElectricRecord.getVehicleNo(), VEHICLE_NO_MAX_LENGTH, "车牌号/船号不能超过30字");
		validateLength(oilElectricRecord.getCardNo(), CARD_NO_MAX_LENGTH, "卡号不能超过30字");
		validateLength(oilElectricRecord.getCardHolder(), CARD_HOLDER_MAX_LENGTH, "持卡人不能超过20字");
		validateLength(oilElectricRecord.getOilProduct(), OIL_PRODUCT_MAX_LENGTH, "油品不能超过50字");
		validateLength(oilElectricRecord.getStation(), STATION_MAX_LENGTH, "站点不能超过50字");
		validateLength(oilElectricRecord.getRemark(), REMARK_MAX_LENGTH, "备注不能超过200字");
		validateLength(oilElectricRecord.getAttachments(), ATTACHMENTS_MAX_LENGTH, "附件不能超过1000字");
		validateMoney(oilElectricRecord.getTransactionAmount(), "交易金额");
		validateMoney(oilElectricRecord.getUnitPrice(), "单价");
		validateMoney(oilElectricRecord.getBalance(), "余额");
		validateNumber(oilElectricRecord.getQuantity(), "数量", QUANTITY_SCALE);
	}

	private void validateMoney(BigDecimal value, String fieldName) {
		validateNumber(value, fieldName, MONEY_SCALE);
	}

	private void validateNumber(BigDecimal value, String fieldName, int scale) {
		if (Func.isEmpty(value)) {
			return;
		}
		if (value.compareTo(BigDecimal.ZERO) < 0) {
			throw new ServiceException(fieldName + "不能小于0");
		}
		if (value.stripTrailingZeros().scale() > scale) {
			throw new ServiceException(fieldName + "最多保留" + 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 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;
	}

}
