package com.gxwebsoft.shop.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.shop.mapper.ShopDealerSettingMapper;
import com.gxwebsoft.shop.service.ShopDealerSettingService;
import com.gxwebsoft.shop.entity.ShopDealerSetting;
import com.gxwebsoft.shop.param.ShopDealerSettingParam;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;

/**
 * 分销商设置表Service实现
 *
 * @author 科技小王子
 * @since 2025-08-11 23:51:41
 */
@Service
public class ShopDealerSettingServiceImpl extends ServiceImpl<ShopDealerSettingMapper, ShopDealerSetting> implements ShopDealerSettingService {

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

    @Override
    public List<ShopDealerSetting> listRel(ShopDealerSettingParam param) {
        List<ShopDealerSetting> list = baseMapper.selectListRel(param);
        if (list == null || list.size() < 2) {
            return list;
        }
        list.sort(Comparator.comparing(
            ShopDealerSetting::getUpdateTime,
            Comparator.nullsLast(Integer::compareTo)
        ).reversed());
        return list;
    }

    @Override
    public ShopDealerSetting getByIdRel(String key) {
        ShopDealerSettingParam param = new ShopDealerSettingParam();
        param.setKey(key);
        return param.getOne(baseMapper.selectListRel(param));
    }

    @Override
    public boolean saveOrUpdateByKey(ShopDealerSetting setting) {
        if (setting == null || setting.getKey() == null) {
            return false;
        }
        LambdaQueryWrapper<ShopDealerSetting> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShopDealerSetting::getKey, setting.getKey());
        if (setting.getTenantId() != null) {
            wrapper.eq(ShopDealerSetting::getTenantId, setting.getTenantId());
        }
        return this.saveOrUpdate(setting, wrapper);
    }

}
