/**
 * 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.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 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;

	@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.setStatusName(ship.getStatus() != null && ship.getStatus() == 2 ? "停用" : "启用");
			excel.setNationalityCertLongTermName(yesNo(ship.getNationalityCertLongTerm()));
			excel.setSafeManningCertLongTermName(yesNo(ship.getSafeManningCertLongTerm()));
			excel.setBusinessTransportCertLongTermName(yesNo(ship.getBusinessTransportCertLongTerm()));
			excel.setLeaseLongTermName(yesNo(ship.getLeaseLongTerm()));
			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.setShipInspectionNo(trimToNull(ship.getShipInspectionNo()));
		ship.setShipType(trimToEmpty(ship.getShipType()));
		ship.setNationalityCertImage(trimToNull(ship.getNationalityCertImage()));
		ship.setSafeManningCertImage(trimToNull(ship.getSafeManningCertImage()));
		ship.setBusinessTransportCertImage(trimToNull(ship.getBusinessTransportCertImage()));
		ship.setLeaseContractImage(trimToNull(ship.getLeaseContractImage()));
		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.getShipType())) {
			throw new ServiceException("船舶类型不能为空");
		}
		if (ship.getNationalityCertLongTerm() != 1 && Func.isEmpty(ship.getNationalityCertEndDate())) {
			throw new ServiceException("国籍证有效期至不能为空");
		}
		if (ship.getSafeManningCertLongTerm() != 1 && Func.isEmpty(ship.getSafeManningCertEndDate())) {
			throw new ServiceException("最低安全配员证书有效期至不能为空");
		}
		if (ship.getBusinessTransportCertLongTerm() != 1 && Func.isEmpty(ship.getBusinessTransportCertEndDate())) {
			throw new ServiceException("营业运输证有效期至不能为空");
		}
		validateLength(ship.getShipName(), NAME_MAX_LENGTH, "船舶名不能超过50字");
		validateLength(ship.getShipIdentifierNo(), SHORT_TEXT_MAX_LENGTH, "船舶识别号不能超过50字");
		validateLength(ship.getOrganizationName(), NAME_MAX_LENGTH, "所属组织不能超过50字");
		validateLength(ship.getShipInspectionNo(), SHORT_TEXT_MAX_LENGTH, "船检登记号不能超过50字");
		validateLength(ship.getShipType(), SHORT_TEXT_MAX_LENGTH, "船舶类型不能超过50字");
		validateLength(ship.getRemark(), REMARK_MAX_LENGTH, "备注不能超过200字");
	}

	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 Long defaultZero(Long value) {
		return value == null ? 0L : value;
	}

	private String yesNo(Integer value) {
		return value != null && value == 1 ? "是" : "否";
	}

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

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

}
