/**
 * 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.DriverExcel;
import org.springblade.transport.mapper.DriverMapper;
import org.springblade.transport.pojo.entity.Driver;
import org.springblade.transport.pojo.vo.DriverExpiryStatVO;
import org.springblade.transport.pojo.vo.DriverVO;
import org.springblade.transport.service.IDriverService;
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 DriverServiceImpl extends BaseServiceImpl<DriverMapper, Driver> implements IDriverService {

	private static final int NAME_MAX_LENGTH = 10;
	private static final int ID_CARD_MAX_LENGTH = 18;
	private static final int MOBILE_MAX_LENGTH = 20;
	private static final int SHORT_TEXT_MAX_LENGTH = 50;
	private static final int ADDRESS_MAX_LENGTH = 200;
	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<DriverVO> selectDriverPage(IPage<DriverVO> page, DriverVO driver) {
		prepareQuery(driver);
		return page.setRecords(baseMapper.selectDriverPage(page, driver));
	}

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

	@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("状态值不正确");
		}
		Driver driver = new Driver();
		driver.setId(id);
		driver.setStatus(status);
		return updateById(driver);
	}

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

	@Override
	public List<DriverExcel> exportDriver(Wrapper<Driver> queryWrapper) {
		return list(queryWrapper).stream().map(driver -> {
			DriverExcel excel = Objects.requireNonNull(BeanUtil.copyProperties(driver, DriverExcel.class));
			excel.setAddress((driver.getAddressRegion() == null ? "" : driver.getAddressRegion())
				+ (driver.getAddress() == null ? "" : driver.getAddress()));
			return excel;
		}).toList();
	}

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

	private void prepare(Driver driver) {
		driver.setDriverName(trimToEmpty(driver.getDriverName()));
		driver.setIdCardNo(trimToEmpty(driver.getIdCardNo()).toUpperCase());
		driver.setGender(trimToNull(driver.getGender()));
		driver.setNation(trimToNull(driver.getNation()));
		driver.setEducation(trimToNull(driver.getEducation()));
		driver.setAddressRegion(trimToNull(driver.getAddressRegion()));
		driver.setAddress(trimToNull(driver.getAddress()));
		driver.setPosts(trimToNull(driver.getPosts()));
		driver.setDrivingType(trimToEmpty(driver.getDrivingType()).toUpperCase());
		driver.setDrivingLicenseNo(trimToNull(driver.getDrivingLicenseNo()));
		driver.setQualificationType(trimToNull(driver.getQualificationType()));
		driver.setQualificationNo(trimToNull(driver.getQualificationNo()));
		driver.setDriverType(trimToEmpty(driver.getDriverType()));
		driver.setMobile(trimToEmpty(driver.getMobile()));
		driver.setContactRelation(trimToNull(driver.getContactRelation()));
		driver.setOrganizationName(trimToEmpty(driver.getOrganizationName()));
		driver.setEmergencyContactName(trimToEmpty(driver.getEmergencyContactName()));
		driver.setEmergencyContactMobile(trimToEmpty(driver.getEmergencyContactMobile()));
		driver.setRemark(trimToNull(driver.getRemark()));
		driver.setIdCardFront(trimToNull(driver.getIdCardFront()));
		driver.setIdCardBack(trimToNull(driver.getIdCardBack()));
		driver.setHeadPhoto(trimToNull(driver.getHeadPhoto()));
		driver.setDrivingLicenseFront(trimToNull(driver.getDrivingLicenseFront()));
		driver.setDrivingLicenseBack(trimToNull(driver.getDrivingLicenseBack()));
		driver.setQualificationFront(trimToNull(driver.getQualificationFront()));
		driver.setQualificationBack(trimToNull(driver.getQualificationBack()));
		if (driver.getDrivingLicenseLongTerm() == null) {
			driver.setDrivingLicenseLongTerm(DEFAULT_FALSE);
		}
		if (driver.getQualificationLongTerm() == null) {
			driver.setQualificationLongTerm(DEFAULT_FALSE);
		}
		if (driver.getStatus() == null) {
			driver.setStatus(DEFAULT_ENABLED_STATUS);
		}
	}

	private void validate(Driver driver) {
		if (Func.isEmpty(driver.getDriverName())) {
			throw new ServiceException("司机姓名不能为空");
		}
		if (Func.isEmpty(driver.getIdCardNo())) {
			throw new ServiceException("身份证号不能为空");
		}
		if (Func.isEmpty(driver.getGender())) {
			throw new ServiceException("性别不能为空");
		}
		if (Func.isEmpty(driver.getPosts())) {
			throw new ServiceException("岗位不能为空");
		}
		if (Func.isEmpty(driver.getDrivingType())) {
			throw new ServiceException("准驾车型不能为空");
		}
		if (Func.isEmpty(driver.getDrivingLicenseNo())) {
			throw new ServiceException("驾驶证档案编号不能为空");
		}
		if (Func.isEmpty(driver.getDrivingLicenseStartDate())) {
			throw new ServiceException("驾驶证有效期起不能为空");
		}
		if (driver.getDrivingLicenseLongTerm() != 1 && Func.isEmpty(driver.getDrivingLicenseEndDate())) {
			throw new ServiceException("驾驶证有效期止不能为空");
		}
		if (Func.isEmpty(driver.getQualificationType())) {
			throw new ServiceException("从业资格认证类型不能为空");
		}
		if (Func.isEmpty(driver.getQualificationNo())) {
			throw new ServiceException("资格证号不能为空");
		}
		if (driver.getQualificationLongTerm() != 1 && Func.isEmpty(driver.getQualificationEndDate())) {
			throw new ServiceException("从业资格证有效期不能为空");
		}
		if (Func.isEmpty(driver.getDriverType())) {
			throw new ServiceException("司机类型不能为空");
		}
		if (Func.isEmpty(driver.getMobile())) {
			throw new ServiceException("手机号不能为空");
		}
		if (Func.isEmpty(driver.getOrganizationName())) {
			throw new ServiceException("所属组织不能为空");
		}
		if (Func.isEmpty(driver.getEmergencyContactName())) {
			throw new ServiceException("紧急联系人姓名不能为空");
		}
		if (driver.getEmergencyContactName().matches(".*\\d.*")) {
			throw new ServiceException("紧急联系人姓名不能包含数字");
		}
		if (Func.isEmpty(driver.getEmergencyContactMobile())) {
			throw new ServiceException("紧急联系人手机号不能为空");
		}
		if (Func.isEmpty(driver.getIdCardFront()) || Func.isEmpty(driver.getIdCardBack())) {
			throw new ServiceException("身份证正反面照片不能为空");
		}
		if (Func.isEmpty(driver.getDrivingLicenseFront()) || Func.isEmpty(driver.getDrivingLicenseBack())) {
			throw new ServiceException("驾驶证主页和副页不能为空");
		}
		validateLength(driver.getDriverName(), NAME_MAX_LENGTH, "司机姓名不能超过10字");
		validateLength(driver.getIdCardNo(), ID_CARD_MAX_LENGTH, "身份证号不能超过18字");
		validateLength(driver.getMobile(), MOBILE_MAX_LENGTH, "手机号不能超过20字");
		validateLength(driver.getEmergencyContactMobile(), MOBILE_MAX_LENGTH, "紧急联系人手机号不能超过20字");
		validateLength(driver.getDrivingLicenseNo(), SHORT_TEXT_MAX_LENGTH, "驾驶证档案编号不能超过50字");
		validateLength(driver.getQualificationNo(), SHORT_TEXT_MAX_LENGTH, "资格证号不能超过50字");
		validateLength(driver.getOrganizationName(), SHORT_TEXT_MAX_LENGTH, "所属组织不能超过50字");
		validateLength(driver.getAddress(), ADDRESS_MAX_LENGTH, "详细地址不能超过200字");
		validateLength(driver.getRemark(), REMARK_MAX_LENGTH, "备注不能超过200字");
		if (Func.isNotEmpty(driver.getDrivingLicenseStartDate()) && Func.isNotEmpty(driver.getDrivingLicenseEndDate()) && driver.getDrivingLicenseEndDate().isBefore(driver.getDrivingLicenseStartDate())) {
			throw new ServiceException("驾驶证有效期止不能早于有效期起");
		}
	}

	private void checkUniqueIdCard(Driver driver) {
		Long count = count(Wrappers.<Driver>lambdaQuery()
			.eq(Driver::getIsDeleted, 0)
			.eq(Driver::getIdCardNo, driver.getIdCardNo())
			.ne(Func.isNotEmpty(driver.getId()), Driver::getId, driver.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 trimToEmpty(String value) {
		return value == null ? "" : value.trim();
	}

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

}
