/**
 * 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.TireReplacementRecordExcel;
import org.springblade.transport.excel.TireReplacementRecordExportExcel;
import org.springblade.transport.mapper.TireReplacementRecordMapper;
import org.springblade.transport.pojo.entity.TireReplacementRecord;
import org.springblade.transport.pojo.vo.TireReplacementRecordVO;
import org.springblade.transport.service.ITireReplacementRecordService;
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 TireReplacementRecordServiceImpl extends BaseServiceImpl<TireReplacementRecordMapper, TireReplacementRecord> implements ITireReplacementRecordService {

	private static final int VEHICLE_NO_MAX_LENGTH = 30;
	private static final int HANDLER_MAX_LENGTH = 20;
	private static final int TIRE_BRAND_MAX_LENGTH = 50;
	private static final int DESCRIPTION_MAX_LENGTH = 200;
	private static final int REMARK_MAX_LENGTH = 500;
	private static final int ATTACHMENTS_MAX_LENGTH = 1000;
	private static final int MONEY_SCALE = 2;

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

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

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

	@Override
	public List<TireReplacementRecordExportExcel> exportTireReplacementRecord(Wrapper<TireReplacementRecord> queryWrapper) {
		return list(queryWrapper).stream().map(tireReplacementRecord -> {
			TireReplacementRecordExportExcel excel = Objects.requireNonNull(BeanUtil.copyProperties(tireReplacementRecord, TireReplacementRecordExportExcel.class));
			excel.setTireQuantity(validQuantity(tireReplacementRecord.getTireQuantity()));
			excel.setReplacementCost(nonNegative(tireReplacementRecord.getReplacementCost()));
			excel.setUpdateUserName(UserCache.getUserRealName(tireReplacementRecord.getUpdateUser()));
			return excel;
		}).toList();
	}

	private void prepare(TireReplacementRecord tireReplacementRecord) {
		tireReplacementRecord.setVehicleNo(trimToEmpty(tireReplacementRecord.getVehicleNo()).toUpperCase());
		tireReplacementRecord.setHandler(trimToNull(tireReplacementRecord.getHandler()));
		tireReplacementRecord.setTireBrand(trimToNull(tireReplacementRecord.getTireBrand()));
		tireReplacementRecord.setReplacementDescription(trimToNull(tireReplacementRecord.getReplacementDescription()));
		tireReplacementRecord.setAttachments(trimToNull(tireReplacementRecord.getAttachments()));
		tireReplacementRecord.setRemark(trimToNull(tireReplacementRecord.getRemark()));
	}

	private void validate(TireReplacementRecord tireReplacementRecord) {
		if (Func.isEmpty(tireReplacementRecord.getVehicleNo())) {
			throw new ServiceException("车牌号不能为空");
		}
		if (Func.isEmpty(tireReplacementRecord.getReplacementTime())) {
			throw new ServiceException("换胎时间不能为空");
		}
		if (Func.isEmpty(tireReplacementRecord.getReplacementCost())) {
			throw new ServiceException("换胎费用不能为空");
		}
		validateLength(tireReplacementRecord.getVehicleNo(), VEHICLE_NO_MAX_LENGTH, "车牌号不能超过30字");
		validateLength(tireReplacementRecord.getHandler(), HANDLER_MAX_LENGTH, "处理人不能超过20字");
		validateLength(tireReplacementRecord.getTireBrand(), TIRE_BRAND_MAX_LENGTH, "轮胎品牌不能超过50字");
		validateLength(tireReplacementRecord.getReplacementDescription(), DESCRIPTION_MAX_LENGTH, "换胎说明不能超过200字");
		validateLength(tireReplacementRecord.getRemark(), REMARK_MAX_LENGTH, "备注不能超过500字");
		validateLength(tireReplacementRecord.getAttachments(), ATTACHMENTS_MAX_LENGTH, "附件不能超过1000字");
		validatePositiveInteger(tireReplacementRecord.getTireQuantity());
		validateNonNegative(tireReplacementRecord.getReplacementCost(), "换胎费用不能小于0");
		validateScale(tireReplacementRecord.getReplacementCost(), "换胎费用最多保留2位小数");
	}

	private void validateLength(String value, int maxLength, String message) {
		if (Func.isNotEmpty(value) && value.length() > maxLength) {
			throw new ServiceException(message);
		}
	}

	private void validatePositiveInteger(Integer value) {
		if (Func.isNotEmpty(value) && value <= 0) {
			throw new ServiceException("换胎数量必须为正整数");
		}
	}

	private void validateNonNegative(BigDecimal value, String message) {
		if (Func.isNotEmpty(value) && value.compareTo(BigDecimal.ZERO) < 0) {
			throw new ServiceException(message);
		}
	}

	private void validateScale(BigDecimal value, String message) {
		if (Func.isNotEmpty(value) && value.stripTrailingZeros().scale() > MONEY_SCALE) {
			throw new ServiceException(message);
		}
	}

	private BigDecimal nonNegative(BigDecimal value) {
		if (Func.isEmpty(value) || value.compareTo(BigDecimal.ZERO) >= 0) {
			return value;
		}
		return BigDecimal.ZERO;
	}

	private Integer validQuantity(Integer value) {
		if (Func.isEmpty(value) || value > 0) {
			return value;
		}
		return null;
	}

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

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

}
