/**
 * 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.TransportChangeRecordExcel;
import org.springblade.transport.excel.TransportChangeRecordExportExcel;
import org.springblade.transport.mapper.TransportChangeRecordMapper;
import org.springblade.transport.pojo.entity.TransportChangeRecord;
import org.springblade.transport.pojo.vo.TransportChangeRecordVO;
import org.springblade.transport.service.ITransportChangeRecordService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * 变更记录 服务实现类
 *
 * @author Chill
 */
@Service
public class TransportChangeRecordServiceImpl extends BaseServiceImpl<TransportChangeRecordMapper, TransportChangeRecord> implements ITransportChangeRecordService {

	private static final int VEHICLE_NO_MAX_LENGTH = 30;
	private static final int CHANGE_CONTENT_MAX_LENGTH = 200;
	private static final int REMARK_MAX_LENGTH = 200;
	private static final int ATTACHMENTS_MAX_LENGTH = 1000;
	private static final String VEHICLE = "车辆";
	private static final String SHIP = "船舶";
	private static final Set<String> CHANGE_ITEMS = Set.of("所有人变更", "挂靠变更", "经营范围变更", "车牌号变更", "其他");

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

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

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

	@Override
	public List<TransportChangeRecordExportExcel> exportTransportChangeRecord(Wrapper<TransportChangeRecord> queryWrapper) {
		return list(queryWrapper).stream()
			.map(transportChangeRecord -> {
				TransportChangeRecordExportExcel excel = Objects.requireNonNull(BeanUtil.copyProperties(transportChangeRecord, TransportChangeRecordExportExcel.class));
				excel.setUpdateUserName(UserCache.getUserRealName(transportChangeRecord.getUpdateUser()));
				return excel;
			})
			.toList();
	}

	private void prepare(TransportChangeRecord transportChangeRecord) {
		transportChangeRecord.setVehicleType(normalizeVehicleType(transportChangeRecord.getVehicleType()));
		transportChangeRecord.setVehicleNo(trimToNull(transportChangeRecord.getVehicleNo()));
		if (Func.isNotEmpty(transportChangeRecord.getVehicleNo()) && VEHICLE.equals(transportChangeRecord.getVehicleType())) {
			transportChangeRecord.setVehicleNo(transportChangeRecord.getVehicleNo().toUpperCase());
		}
		transportChangeRecord.setChangeItem(trimToNull(transportChangeRecord.getChangeItem()));
		transportChangeRecord.setChangeContent(trimToNull(transportChangeRecord.getChangeContent()));
		transportChangeRecord.setAttachments(trimToNull(transportChangeRecord.getAttachments()));
		transportChangeRecord.setRemark(trimToNull(transportChangeRecord.getRemark()));
	}

	private void validate(TransportChangeRecord transportChangeRecord) {
		if (Func.isEmpty(transportChangeRecord.getVehicleType())) {
			throw new ServiceException("车船类型不能为空");
		}
		if (!VEHICLE.equals(transportChangeRecord.getVehicleType()) && !SHIP.equals(transportChangeRecord.getVehicleType())) {
			throw new ServiceException("车船类型不正确");
		}
		if (Func.isEmpty(transportChangeRecord.getChangeItem())) {
			throw new ServiceException("变更事项不能为空");
		}
		if (!CHANGE_ITEMS.contains(transportChangeRecord.getChangeItem())) {
			throw new ServiceException("变更事项不正确");
		}
		if (Func.isEmpty(transportChangeRecord.getChangeContent())) {
			throw new ServiceException("变更内容不能为空");
		}
		validateLength(transportChangeRecord.getVehicleNo(), VEHICLE_NO_MAX_LENGTH, "车牌号/船号不能超过30字");
		validateLength(transportChangeRecord.getChangeContent(), CHANGE_CONTENT_MAX_LENGTH, "变更内容不能超过200字");
		validateLength(transportChangeRecord.getRemark(), REMARK_MAX_LENGTH, "备注不能超过200字");
		validateLength(transportChangeRecord.getAttachments(), ATTACHMENTS_MAX_LENGTH, "附件不能超过1000字");
	}

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

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

}
