package com.gxwebsoft.common.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.Area;
import com.gxwebsoft.common.system.mapper.AreaMapper;
import com.gxwebsoft.common.system.param.AreaParam;
import com.gxwebsoft.common.system.service.AreaService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Service实现
 *
 * @author 科技小王子
 * @since 2023-07-06 15:08:15
 */
@Service
public class AreaServiceImpl extends ServiceImpl<AreaMapper, Area> implements AreaService {

    @Override
    public PageResult<Area> pageRel(AreaParam param) {
        PageParam<Area, AreaParam> page = new PageParam<>(param);
        //page.setDefaultOrder("create_time desc");
        List<Area> list = baseMapper.selectPageRel(page, param);
        return new PageResult<>(list, page.getTotal());
    }

    @Override
    public List<Area> listRel(AreaParam param) {
        List<Area> list = baseMapper.selectListRel(param);
        // 排序
        PageParam<Area, AreaParam> page = new PageParam<>();
        //page.setDefaultOrder("create_time desc");
        return page.sortRecords(list);
    }

    @Override
    public Area getByIdRel(Integer id) {
        AreaParam param = new AreaParam();
        param.setId(id);
        return param.getOne(baseMapper.selectListRel(param));
    }

    @Override
    public Area areaInfoByName(String name, Integer level) {
        LambdaQueryWrapper<Area> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Area::getName, name);
        if (level != null) wrapper.eq(Area::getLevelId, level);
        return getOne(wrapper);
    }

    @Override
    public Area areaInfoByName(String name, Integer level, Integer parentId) {
        LambdaQueryWrapper<Area> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Area::getName, name);
        if (parentId != null) wrapper.eq(Area::getFid, parentId);
        if (level != null) wrapper.eq(Area::getLevelId, level);
        return getOne(wrapper);
    }

    @Override
    public Area regionInfoWithProvince(String provinceName, String cityName, String regionName) {
        Area province = areaInfoByName(provinceName, 1);
        if (province == null) return null;
        Area city = getOne(
                new LambdaQueryWrapper<Area>()
                        .eq(Area::getName, cityName)
                        .eq(Area::getFid, province.getId())
                        .last("limit 1")
        );
        if (city == null) return null;
        return getOne(
                new LambdaQueryWrapper<Area>()
                        .eq(Area::getName, regionName)
                        .eq(Area::getFid, city.getId())
        );

    }

}
