package com.yh.saas.plugin.configuration.vessel.service.imp;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alipay.sofa.runtime.api.annotation.SofaReference;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.winsea.svc.base.base.entity.CommonVessel;
import com.winsea.svc.base.base.entity.VesselDetail;
import com.winsea.svc.base.base.service.ICommonVesselService;
import com.winsea.svc.base.base.service.IVesselDetailService;
import com.yh.saas.common.support.util.IdGenerator;
import com.yh.saas.plugin.configuration.vessel.service.ISystemVesselService;

/**
 * <p>
 * 记录船舶信息 服务类
 * </p>
 *
 * @author SunTianjun
 * @since 2019-04-11
 */
@Service
public class SystemVesselServiceImpl implements ISystemVesselService {

	@SofaReference
	private IVesselDetailService vesselDetailService;

	@SofaReference
	private ICommonVesselService commonVesselService;

	@Transactional
	@Override
	public void changeInfo(CommonVessel vessel) {
		this.commonVesselService.updateById(vessel);
		VesselDetail vesselDetail = vessel.getVesselDetail();
		if (StringUtils.isBlank(vesselDetail.getId())) {
			vesselDetail.setId(IdGenerator.generateUUID());
			vesselDetail.setVesselId(vessel.getVesselId());
			this.vesselDetailService.insert(vesselDetail);
		} else {
			this.vesselDetailService.updateAllColumnById(vesselDetail);
		}
	}

	@Override
	public Page<CommonVessel> getVesselPage(CommonVessel example) {
		Wrapper<CommonVessel> wrapper = new EntityWrapper<>();
		wrapper.eq(CommonVessel.QueryFields.COMP_ID, example.getCompId());
		if (StringUtils.isNotBlank(example.getVesselId())) {
			wrapper.eq(CommonVessel.QueryFields.VESSEL_ID, example.getVesselId());
		}
		if (StringUtils.isNotBlank(example.getSearchKeyword())) {
			wrapper.andNew("(" + CommonVessel.QueryFields.COMP_NAME + " like {0} or "
					+ CommonVessel.QueryFields.VESSEL_NAME + " like {0} )",
					"%" + example.getSearchKeyword().trim() + "%");
		}
		return this.commonVesselService.selectPage(example.getQueryPage(), wrapper);
	}

	@Override
	public CommonVessel getVesselOne(String vesselId) {
		CommonVessel vessel = this.commonVesselService.selectById(vesselId);
		VesselDetail vesselDetail = this.vesselDetailService
				.selectOne((new EntityWrapper<VesselDetail>()).eq(VesselDetail.QueryFields.VESSEL_ID, vesselId));
		if (vesselDetail == null) {
			vesselDetail = new VesselDetail();
		}
		vessel.setVesselDetail(vesselDetail);
		return vessel;

	}

}
