/**
 * 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 com.baomidou.mybatisplus.core.toolkit.Wrappers;
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.transport.excel.TransportShipExcel;
import org.springblade.transport.mapper.TransportShipMapper;
import org.springblade.transport.pojo.entity.TransportShip;
import org.springblade.transport.pojo.vo.TransportShipExpiryStatVO;
import org.springblade.transport.pojo.vo.TransportShipVO;
import org.springblade.transport.service.ITransportShipService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
import java.util.Objects;

/**
 * 船舶管理 服务实现类
 *
 * @author Chill
 */
@Service
public class TransportShipServiceImpl extends BaseServiceImpl<TransportShipMapper, TransportShip> implements ITransportShipService {

	private static final int NAME_MAX_LENGTH = 50;
	private static final int SHIP_NAME_MAX_LENGTH = 20;
	private static final int SHORT_TEXT_MAX_LENGTH = 50;
	private static final int REMARK_MAX_LENGTH = 200;
	private static final int DEFAULT_ENABLED_STATUS = 1;
	private static final int DEFAULT_FALSE = 0;
	private static final BigDecimal ZERO = BigDecimal.ZERO;
	private static final List<String> SHIP_TYPES = List.of("散货船", "集装箱船", "杂货船", "油船");

	@Override
	public IPage<TransportShipVO> selectTransportShipPage(IPage<TransportShipVO> page, TransportShipVO ship) {
		prepareQuery(ship);
		return page.setRecords(baseMapper.selectTransportShipPage(page, ship));
	}

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

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean changeStatus(Long id, Integer status) {
		if (Func.isEmpty(id)) {
			throw new ServiceException("船舶主键不能为空");
		}
		if (Func.isEmpty(status) || (status != 1 && status != 2)) {
			throw new ServiceException("状态值不正确");
		}
		TransportShip ship = new TransportShip();
		ship.setId(id);
		ship.setStatus(status);
		return updateById(ship);
	}

	@Override
	public TransportShipExpiryStatVO expiryStat(TransportShipVO ship) {
		prepareQuery(ship);
		ship.setExpireStatus(null);
		TransportShipExpiryStatVO stat = baseMapper.selectExpiryStat(ship);
		if (stat == null) {
			stat = new TransportShipExpiryStatVO();
		}
		stat.setTotal(defaultZero(stat.getTotal()));
		stat.setWithin30(defaultZero(stat.getWithin30()));
		stat.setExpired(defaultZero(stat.getExpired()));
		return stat;
	}

	@Override
	public List<TransportShipExcel> exportTransportShip(Wrapper<TransportShip> queryWrapper) {
		return list(queryWrapper).stream().map(ship -> {
			TransportShipExcel excel = Objects.requireNonNull(BeanUtil.copyProperties(ship, TransportShipExcel.class));
			excel.setConstructionDateRange(formatDateRange(
				ship.getKeelLayingDate(), ship.getBuildCompletionDate()
			));
			return excel;
		}).toList();
	}

	private void prepareQuery(TransportShipVO ship) {
		if (ship.getToday() == null) {
			ship.setToday(LocalDate.now());
		}
		if (ship.getWarningDate() == null) {
			ship.setWarningDate(ship.getToday().plusDays(30));
		}
	}

	private void prepare(TransportShip ship) {
		ship.setShipName(trimToEmpty(ship.getShipName()));
		ship.setShipIdentifierNo(trimToEmpty(ship.getShipIdentifierNo()).toUpperCase());
		ship.setOrganizationName(trimToEmpty(ship.getOrganizationName()));
		ship.setNavigationArea(trimToEmpty(ship.getNavigationArea()));
		ship.setOwnershipRegistrationNo(trimToEmpty(ship.getOwnershipRegistrationNo()));
		ship.setInitialRegistrationNo(trimToEmpty(ship.getInitialRegistrationNo()));
		ship.setShipOwner(trimToNull(ship.getShipOwner()));
		ship.setShipInspectionNo(trimToNull(ship.getShipInspectionNo()));
		ship.setShipType(trimToEmpty(ship.getShipType()));
		ship.setOwnershipCertImage(trimToNull(ship.getOwnershipCertImage()));
		ship.setSafetyCertImage(trimToNull(ship.getSafetyCertImage()));
		ship.setNationalityCertImage(trimToNull(ship.getNationalityCertImage()));
		ship.setSafeManningCertImage(trimToNull(ship.getSafeManningCertImage()));
		ship.setBusinessTransportCertNo(trimToEmpty(ship.getBusinessTransportCertNo()));
		ship.setBusinessTransportCertImage(trimToNull(ship.getBusinessTransportCertImage()));
		ship.setLeaseContractImage(trimToNull(ship.getLeaseContractImage()));
		ship.setShipLessee(trimToNull(ship.getShipLessee()));
		ship.setShipOperator(trimToNull(ship.getShipOperator()));
		ship.setRemark(trimToNull(ship.getRemark()));
		if (ship.getNationalityCertLongTerm() == null) {
			ship.setNationalityCertLongTerm(DEFAULT_FALSE);
		}
		if (ship.getSafeManningCertLongTerm() == null) {
			ship.setSafeManningCertLongTerm(DEFAULT_FALSE);
		}
		if (ship.getBusinessTransportCertLongTerm() == null) {
			ship.setBusinessTransportCertLongTerm(DEFAULT_FALSE);
		}
		if (ship.getLeaseLongTerm() == null) {
			ship.setLeaseLongTerm(DEFAULT_FALSE);
		}
		if (ship.getStatus() == null) {
			ship.setStatus(DEFAULT_ENABLED_STATUS);
		}
	}

	private void validate(TransportShip ship) {
		if (Func.isEmpty(ship.getShipName())) {
			throw new ServiceException("船舶名不能为空");
		}
		if (Func.isEmpty(ship.getShipIdentifierNo())) {
			throw new ServiceException("船舶识别号不能为空");
		}
		if (Func.isEmpty(ship.getOrganizationName())) {
			throw new ServiceException("所属组织不能为空");
		}
		if (Func.isEmpty(ship.getNavigationArea())) {
			throw new ServiceException("航区不能为空");
		}
		if (!"A级".equals(ship.getNavigationArea()) && !"B级".equals(ship.getNavigationArea())) {
			throw new ServiceException("航区只能选择A级或B级");
		}
		if (Func.isEmpty(ship.getOwnershipRegistrationNo())) {
			throw new ServiceException("登记号码不能为空");
		}
		if (Func.isEmpty(ship.getInitialRegistrationNo())) {
			throw new ServiceException("初次登记号码不能为空");
		}
		if (Func.isEmpty(ship.getGrossTonnage())) {
			throw new ServiceException("总吨不能为空");
		}
		if (Func.isEmpty(ship.getNetTonnage())) {
			throw new ServiceException("净吨不能为空");
		}
		if (Func.isEmpty(ship.getShipInspectionNo())) {
			throw new ServiceException("船检登记号不能为空");
		}
		if (Func.isEmpty(ship.getShipType())) {
			throw new ServiceException("船舶类型不能为空");
		}
		if (!SHIP_TYPES.contains(ship.getShipType())) {
			throw new ServiceException("船舶类型只能选择散货船、集装箱船、杂货船或油船");
		}
		if (ship.getNationalityCertLongTerm() != 1
			&& (Func.isEmpty(ship.getNationalityCertStartDate()) || Func.isEmpty(ship.getNationalityCertEndDate()))) {
			throw new ServiceException("船舶国籍证书有效期不能为空");
		}
		if (ship.getSafeManningCertLongTerm() != 1
			&& (Func.isEmpty(ship.getSafeManningCertStartDate()) || Func.isEmpty(ship.getSafeManningCertEndDate()))) {
			throw new ServiceException("最低安全配员证书有效期不能为空");
		}
		if (Func.isEmpty(ship.getBusinessTransportCertNo())) {
			throw new ServiceException("营业运输证证书编号不能为空");
		}
		if (Func.isEmpty(ship.getBusinessTransportCertIssueDate())) {
			throw new ServiceException("营业运输证发证日期不能为空");
		}
		if (ship.getBusinessTransportCertLongTerm() != 1 && Func.isEmpty(ship.getBusinessTransportCertEndDate())) {
			throw new ServiceException("营业运输证有效期至不能为空");
		}
		validateLength(ship.getShipName(), SHIP_NAME_MAX_LENGTH, "船名不能超过20个字符");
		validateLength(ship.getShipIdentifierNo(), SHORT_TEXT_MAX_LENGTH, "船舶识别号不能超过50字");
		validateLength(ship.getOrganizationName(), NAME_MAX_LENGTH, "所属组织不能超过50字");
		validateLength(ship.getNavigationArea(), SHORT_TEXT_MAX_LENGTH, "航区不能超过50字");
		validateLength(ship.getOwnershipRegistrationNo(), SHORT_TEXT_MAX_LENGTH, "登记号码不能超过50字");
		validateLength(ship.getInitialRegistrationNo(), SHORT_TEXT_MAX_LENGTH, "初次登记号码不能超过50字");
		validateLength(ship.getShipOwner(), NAME_MAX_LENGTH, "船舶所有人不能超过50字");
		validateLength(ship.getShipInspectionNo(), SHORT_TEXT_MAX_LENGTH, "船检登记号不能超过50字");
		validateLength(ship.getShipType(), SHORT_TEXT_MAX_LENGTH, "船舶类型不能超过50字");
		validateLength(ship.getBusinessTransportCertNo(), SHORT_TEXT_MAX_LENGTH, "营业运输证证书编号不能超过50字");
		validateLength(ship.getShipLessee(), NAME_MAX_LENGTH, "船舶承租人不能超过50字");
		validateLength(ship.getShipOperator(), NAME_MAX_LENGTH, "船舶经营人不能超过50字");
		validateLength(ship.getRemark(), REMARK_MAX_LENGTH, "备注不能超过200字");
		validateNonNegative(ship.getTotalLength(), "总长不能小于0");
		validateNonNegative(ship.getShipWidth(), "船宽不能小于0");
		validateNonNegative(ship.getMoldedDepth(), "型深不能小于0");
		validateNonNegative(ship.getMaxShipHeight(), "最大船高不能小于0");
		validateNonNegative(ship.getLightDraft(), "空载吃水不能小于0");
		validateNonNegative(ship.getFullLoadDraft(), "满载吃水不能小于0");
		validateNonNegative(ship.getGrossTonnage(), "总吨不能小于0");
		validateNonNegative(ship.getNetTonnage(), "净吨不能小于0");
		validateDateRange(ship.getKeelLayingDate(), ship.getBuildCompletionDate(), "建造完工日期不能早于安放龙骨日期");
		validateDateRange(ship.getNationalityCertStartDate(), ship.getNationalityCertEndDate(), "国籍证结束日期不能早于开始日期");
		validateDateRange(ship.getSafeManningCertStartDate(), ship.getSafeManningCertEndDate(), "最低安全配员证书结束日期不能早于开始日期");
		validateDateRange(ship.getLeaseStartDate(), ship.getLeaseEndDate(), "终止日期不能早于起租日期");
		validateDateRange(ship.getBusinessTransportCertIssueDate(), ship.getBusinessTransportCertEndDate(), "营业运输证有效期至不能早于发证日期");
	}

	private void checkUniqueIdentifier(TransportShip ship) {
		Long count = count(Wrappers.<TransportShip>lambdaQuery()
			.eq(TransportShip::getIsDeleted, 0)
			.eq(TransportShip::getShipIdentifierNo, ship.getShipIdentifierNo())
			.ne(Func.isNotEmpty(ship.getId()), TransportShip::getId, ship.getId()));
		if (count > 0) {
			throw new ServiceException("船舶识别号已存在");
		}
	}

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

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

	private void validateDateRange(LocalDate startDate, LocalDate endDate, String message) {
		if (startDate != null && endDate != null && endDate.isBefore(startDate)) {
			throw new ServiceException(message);
		}
	}

	private Long defaultZero(Long value) {
		return value == null ? 0L : value;
	}

	private String formatDateRange(LocalDate startDate, LocalDate endDate) {
		return String.format("%s / %s", startDate == null ? "" : startDate, endDate == null ? "" : endDate);
	}

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

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

}
