package com.patzn.lims.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.patzn.lims.core.api.PtAssert;
import com.patzn.lims.core.web.BaseServiceImpl;
import com.patzn.lims.sys.entity.SysCountry;
import com.patzn.lims.sys.mapper.SysCountryMapper;
import com.patzn.lims.sys.service.ISysCountryService;
import com.patzn.lims.sys.service.ISysProvinceService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;

/**
 * <p>
 * 国家表 服务实现类
 * </p>
 *
 * @author patzn
 * @since 2017-07-10
 */
@Service
public class SysCountryServiceImpl extends BaseServiceImpl<SysCountryMapper, SysCountry> implements ISysCountryService {
  @Autowired
  private ISysProvinceService provinceService;

  @Override
  public Page<SysCountry> page(Page<SysCountry> page, SysCountry sysCountry) {
    QueryWrapper<SysCountry> wrapper = Wrappers.<SysCountry>query(sysCountry);
    if (StringUtils.isNotEmpty(sysCountry.getCn())) {
      wrapper.like("cn", sysCountry.getCn());
      sysCountry.setCn(null);
    }
    if (StringUtils.isNotEmpty(sysCountry.getCode2())) {
      wrapper.like("code2", sysCountry.getCode2());
      sysCountry.setCode2(null);
    }
    if (StringUtils.isNotEmpty(sysCountry.getCode3())) {
      wrapper.like("code3", sysCountry.getCode3());
      sysCountry.setCode2(null);
    }
    wrapper.orderBy(true, false, "id");
    return page(page, wrapper);
  }

  @Override
  public boolean save(SysCountry sysCountry) {
    verifyNameCode(sysCountry);
    return super.save(sysCountry);
  }

  @Override
  public boolean updateById(SysCountry sysCountry) {
    verifyNameCode(sysCountry);
    return super.updateById(sysCountry);
  }

  /**
   * 校验名称编号
   */
  private void verifyNameCode(SysCountry sysCountry) {
    if (baseMapper.selectCountOrNameCode(sysCountry) > 0) {
      PtAssert.fail("抱歉!国家名称或编号已存在，请重新输入。");
    }
  }

  @Override
  public boolean removeById(Serializable id) {
    SysCountry sysCountry = getById(id);
    PtAssert.fail(null == sysCountry, "该国家信息不存在");
    PtAssert.fail(provinceService.existByCountryCode2(sysCountry.getCode2())
      , "该国家存在下级省份信息，必须先删除省份信息");
    return super.removeById(id);
  }
}
