package com.mortals.xhx.module.site.service.impl;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.xhx.module.area.model.AreaEntity;
import com.mortals.xhx.module.area.service.AreaService;
import com.mortals.xhx.module.site.model.SiteQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mortals.framework.service.impl.AbstractCRUDServiceImpl;
import com.mortals.xhx.module.site.dao.SiteDao;
import com.mortals.xhx.module.site.model.SiteEntity;
import com.mortals.xhx.module.site.service.SiteService;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
* SiteService
* 站点 service实现
*
* @author zxfei
* @date 2022-01-12
*/
@Service("siteService")
public class SiteServiceImpl extends AbstractCRUDServiceImpl<SiteDao, SiteEntity, Long> implements SiteService {
    @Autowired
    private AreaService areaService;

    @Override
    protected void validData(SiteEntity entity, Context context) throws AppException {
        if(ObjectUtils.isEmpty(entity.getAreaCode())){
            throw new AppException("区域编码不能为空！");
        }
        AreaEntity areaEntity = areaService.getCache(entity.getAreaCode());
        if(ObjectUtils.isEmpty(areaEntity)){
            throw new AppException(String.format("区域不存在！区域编码：%s", entity.getAreaCode()));
        }
        super.validData(entity, context);
    }

    @Override
    protected void saveBefore(SiteEntity entity, Context context) throws AppException {
        List<SiteEntity> siteEntities = this.find(new SiteQuery().areaCode(entity.getAreaCode()));
        entity.setSiteCode(entity.getAreaCode()+"#"+(siteEntities.size()+1));
        super.saveBefore(entity, context);
    }
}