/**
 * 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.OtherExpenseRecordExcel;
import org.springblade.transport.excel.OtherExpenseRecordExportExcel;
import org.springblade.transport.mapper.OtherExpenseRecordMapper;
import org.springblade.transport.pojo.entity.OtherExpenseRecord;
import org.springblade.transport.pojo.vo.OtherExpenseRecordVO;
import org.springblade.transport.service.IOtherExpenseRecordService;
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;
import java.util.Set;

/**
 * 其他费用记录 服务实现类
 *
 * @author Chill
 */
@Service
public class OtherExpenseRecordServiceImpl extends BaseServiceImpl<OtherExpenseRecordMapper, OtherExpenseRecord> implements IOtherExpenseRecordService {

	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 MONEY_SCALE = 2;
	private static final String VEHICLE = "车辆";
	private static final String SHIP = "船舶";
	private static final Set<String> EXPENSE_TYPES = Set.of("过路费", "停车费", "维修费", "保险费", "年检费", "装卸费", "其他");

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

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

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

	@Override
	public List<OtherExpenseRecordExportExcel> exportOtherExpenseRecord(Wrapper<OtherExpenseRecord> queryWrapper) {
		return list(queryWrapper).stream().map(otherExpenseRecord -> {
			OtherExpenseRecordExportExcel excel = Objects.requireNonNull(BeanUtil.copyProperties(otherExpenseRecord, OtherExpenseRecordExportExcel.class));
			excel.setAmount(nonNegative(otherExpenseRecord.getAmount()));
			excel.setUpdateUserName(UserCache.getUserRealName(otherExpenseRecord.getUpdateUser()));
			return excel;
		}).toList();
	}

	private void prepare(OtherExpenseRecord otherExpenseRecord) {
		if (Func.isEmpty(otherExpenseRecord.getExpenseDate())) {
			otherExpenseRecord.setExpenseDate(LocalDate.now());
		}
		otherExpenseRecord.setExpenseType(trimToNull(otherExpenseRecord.getExpenseType()));
		otherExpenseRecord.setVehicleType(normalizeVehicleType(otherExpenseRecord.getVehicleType()));
		otherExpenseRecord.setVehicleNo(trimToEmpty(otherExpenseRecord.getVehicleNo()));
		if (VEHICLE.equals(otherExpenseRecord.getVehicleType())) {
			otherExpenseRecord.setVehicleNo(otherExpenseRecord.getVehicleNo().toUpperCase());
		}
		otherExpenseRecord.setDataSource(defaultDataSource(otherExpenseRecord.getDataSource()));
		otherExpenseRecord.setAttachments(trimToNull(otherExpenseRecord.getAttachments()));
		otherExpenseRecord.setRemark(trimToNull(otherExpenseRecord.getRemark()));
	}

	private void validate(OtherExpenseRecord otherExpenseRecord) {
		if (Func.isEmpty(otherExpenseRecord.getExpenseDate())) {
			throw new ServiceException("费用日期不能为空");
		}
		if (Func.isEmpty(otherExpenseRecord.getExpenseType())) {
			throw new ServiceException("费用类型不能为空");
		}
		if (!EXPENSE_TYPES.contains(otherExpenseRecord.getExpenseType())) {
			throw new ServiceException("费用类型不正确");
		}
		if (Func.isEmpty(otherExpenseRecord.getVehicleType())) {
			throw new ServiceException("车船类型不能为空");
		}
		if (!VEHICLE.equals(otherExpenseRecord.getVehicleType()) && !SHIP.equals(otherExpenseRecord.getVehicleType())) {
			throw new ServiceException("车船类型不正确");
		}
		if (Func.isEmpty(otherExpenseRecord.getVehicleNo())) {
			throw new ServiceException("车牌号/船号不能为空");
		}
		if (Func.isEmpty(otherExpenseRecord.getAmount())) {
			throw new ServiceException("金额不能为空");
		}
		validateLength(otherExpenseRecord.getVehicleNo(), VEHICLE_NO_MAX_LENGTH, "车牌号/船号不能超过30字");
		validateLength(otherExpenseRecord.getRemark(), REMARK_MAX_LENGTH, "备注不能超过200字");
		validateLength(otherExpenseRecord.getAttachments(), ATTACHMENTS_MAX_LENGTH, "附件不能超过1000字");
		validateMoney(otherExpenseRecord.getAmount(), "金额");
	}

	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 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;
	}

}
