package com.cool.store.dao.fees;

import cn.hutool.core.collection.CollStreamUtil;
import com.cool.store.entity.fees.FeeStandardConfigDO;
import com.cool.store.mapper.fees.FeeStandardConfigMapper;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 加盟费用标准收费额配置DAO
 */
@Repository
@RequiredArgsConstructor
public class FeeStandardConfigDAO {

    private final FeeStandardConfigMapper feeStandardConfigMapper;

    public FeeStandardConfigDO selectByPrimaryKey(Long id) {
        return feeStandardConfigMapper.selectByPrimaryKey(id);
    }

    public void insertSelective(FeeStandardConfigDO config) {
        feeStandardConfigMapper.insertSelective(config);
    }

    public void updateByPrimaryKeySelective(FeeStandardConfigDO config) {
        feeStandardConfigMapper.updateByPrimaryKeySelective(config);
    }

    public boolean existJoinBrandAndExpenseType(Integer joinBrand, String expenseType, Long excludeId) {
        Example example = new Example(FeeStandardConfigDO.class);
        Example.Criteria criteria = example.createCriteria()
                .andEqualTo("joinBrand", joinBrand)
                .andEqualTo("expenseType", expenseType);
        if (Objects.nonNull(excludeId)) {
            criteria.andNotEqualTo("id", excludeId);
        }
        return feeStandardConfigMapper.selectCountByExample(example) > 0;
    }

    public List<FeeStandardConfigDO> selectByCondition(Integer joinBrand, String expenseType) {
        Example example = new Example(FeeStandardConfigDO.class);
        Example.Criteria criteria = example.createCriteria();
        if (joinBrand != null) {
            criteria.andEqualTo("joinBrand", joinBrand);
        }
        if (StringUtils.isNotBlank(expenseType)) {
            criteria.andEqualTo("expenseType", expenseType.trim());
        }
        example.setOrderByClause("create_time DESC");
        return feeStandardConfigMapper.selectByExample(example);
    }

    /**
     * 根据品牌查询费用标准收费额配置映射
     * @param joinBrand 品牌
     * @return 费用类型 -> 收费额配置
     */
    public Map<String, FeeStandardConfigDO> getStandardConfigMap(Integer joinBrand) {
        FeeStandardConfigDO configDO = new FeeStandardConfigDO();
        configDO.setJoinBrand(joinBrand);
        List<FeeStandardConfigDO> list = feeStandardConfigMapper.select(configDO);
        return CollStreamUtil.toMap(list, FeeStandardConfigDO::getExpenseType, v -> v);
    }
}


