package com.gxwebsoft.clinic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.clinic.mapper.ClinicListMapper;
import com.gxwebsoft.clinic.service.ClinicListService;
import com.gxwebsoft.clinic.entity.ClinicList;
import com.gxwebsoft.clinic.param.ClinicListParam;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.service.AreaService;
import org.springframework.stereotype.Service;

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

/**
 * 诊所列表Service实现
 *
 * @author LX
 * @since 2025-12-09 17:29:44
 */
@Service
public class ClinicListServiceImpl extends ServiceImpl<ClinicListMapper, ClinicList> implements ClinicListService {
    @Resource
    private AreaService areaServicel;

    @Override
    public PageResult<ClinicList> pageRel(ClinicListParam param) {
        PageParam<ClinicList, ClinicListParam> page = new PageParam<>(param);
        page.setDefaultOrder("sort_number asc, create_time desc");
        List<ClinicList> list = baseMapper.selectPageRel(page, param);
        for (ClinicList clinicList : list) {
            // 获取关联数据
            if (clinicList.getProvinceId() != null) {
                clinicList.setProvince(areaServicel.getByIdRel(clinicList.getProvinceId()));
            }
            if (clinicList.getCityId() != null) {
                clinicList.setCity(areaServicel.getByIdRel(clinicList.getCityId()));
            }
            if (clinicList.getRegionId() != null) {
                clinicList.setRegion(areaServicel.getByIdRel(clinicList.getRegionId()));
            }
        }
        return new PageResult<>(list, page.getTotal());
    }

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

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

    @Override
    public ClinicList getByUserId(Integer userId) {
        return getOne(
                new LambdaQueryWrapper<ClinicList>()
                        .eq(ClinicList::getUserId, userId)
                        .last("limit 1")
        );
    }

}
