package com.ghy.system.service.impl;

import com.ghy.common.constant.UserConstants;
import com.ghy.common.core.text.Convert;
import com.ghy.common.exception.ServiceException;
import com.ghy.common.utils.StringUtils;
import com.ghy.system.domain.SysArea;
import com.ghy.system.mapper.SysAreaMapper;
import com.ghy.system.service.ISysAreaService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author clunt
 * 区域表Impl层
 */
@Service
public class SysAreaServiceImpl implements ISysAreaService {

    @Resource
    private SysAreaMapper sysAreaMapper;

    @Override
    public List<SysArea> selectSysAreaList(SysArea sysArea) {
        return sysAreaMapper.selectSysAreaList(sysArea);
    }

    @Override
    public SysArea selectById(Long areaId) {
        return sysAreaMapper.selectById(areaId);
    }

    @Override
    public SysArea selectByAreaCode(String areaCode) {
        return sysAreaMapper.selectByAreaCode(areaCode);
    }

    @Override
    public int deleteSysAreaByIds(String ids) {
        Long[] areaIds = Convert.toLongArray(ids);
        for (Long areaId : areaIds)
        {
            SysArea sysArea = selectById(areaId);
            if (countUseSysAreaById(sysArea) > 0)
            {
                throw new ServiceException(String.format("%1$s正在使用,不能删除", sysArea.getAreaName()));
            }
        }
        return sysAreaMapper.deleteSysAreaByIds(areaIds);
    }

    @Override
    public int updateSysArea(SysArea sysArea) {
        return sysAreaMapper.updateSysArea(sysArea);
    }

    @Override
    public int insertSysArea(SysArea sysArea) {
        return sysAreaMapper.insertSysArea(sysArea);
    }

    @Override
    public String checkAreaCodeUnique(SysArea sysArea) {
        Long areaId = StringUtils.isNull(sysArea.getAreaId()) ? -1L : sysArea.getAreaId();
        SysArea info = sysAreaMapper.selectByAreaCode(sysArea.getAreaCode());
        if(StringUtils.isNotNull(info) && info.getAreaId().longValue() != areaId){
            return UserConstants.AREA_CODE_UNIQUE;
        }
        return UserConstants.AREA_CODE_NOT_UNIQUE;
    }

    @Override
    public int selectAreaCount(Long areaId) {
        SysArea sysArea = sysAreaMapper.selectById(areaId);
        SysArea info = new SysArea();
        info.setParentCode(sysArea.getAreaCode());
        return sysAreaMapper.selectSysAreaList(info).size();
    }

    @Override
    public SysArea selectByName(String name, String parentCode) {
        SysArea sysArea = new SysArea();
        sysArea.setAreaName(name);
        sysArea.setParentCode(parentCode);
        return sysAreaMapper.selectByName(sysArea);
    }

    public int countUseSysAreaById(SysArea sysArea){
        //TODO 校验区域是否使用
        return 0;
    }


}
