package org.hzhub.crm.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.hzhub.common.core.constant.SystemConstants;
import org.hzhub.common.core.exception.ServiceException;
import org.hzhub.common.core.utils.MapstructUtils;
import org.hzhub.common.core.utils.StringUtils;
import org.hzhub.common.mybatis.core.page.PageQuery;
import org.hzhub.common.mybatis.core.page.TableDataInfo;
import org.hzhub.crm.domain.CrmDealer;
import org.hzhub.crm.domain.bo.CrmDealerBo;
import org.hzhub.crm.domain.vo.CrmDealerVo;
import org.hzhub.crm.mapper.CrmDealerMapper;
import org.hzhub.crm.service.ICrmDealerService;
import org.springframework.stereotype.Service;

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

/**
 * CRM经销商 Service 实现
 *
 * @author hzhub
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class CrmDealerServiceImpl implements ICrmDealerService {

    private final CrmDealerMapper dealerMapper;

    @Override
    public TableDataInfo<CrmDealerVo> selectPageDealerList(CrmDealerBo dealer, PageQuery pageQuery) {
        LambdaQueryWrapper<CrmDealer> wrapper = buildQueryWrapper(dealer);
        Page<CrmDealerVo> page = dealerMapper.selectVoPage(pageQuery.build(), wrapper);
        return TableDataInfo.build(page);
    }

    /**
     * 构建查询条件
     */
    private LambdaQueryWrapper<CrmDealer> buildQueryWrapper(CrmDealerBo dealer) {
        Map<String, Object> params = dealer.getParams();
        LambdaQueryWrapper<CrmDealer> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(CrmDealer::getDelFlag, SystemConstants.NORMAL)
            .like(StringUtils.isNotBlank(dealer.getDealerName()), CrmDealer::getDealerName, dealer.getDealerName())
            .eq(StringUtils.isNotBlank(dealer.getDealerCode()), CrmDealer::getDealerCode, dealer.getDealerCode())
            .eq(StringUtils.isNotBlank(dealer.getMobile()), CrmDealer::getMobile, dealer.getMobile())
            .eq(StringUtils.isNotBlank(dealer.getLevel()), CrmDealer::getLevel, dealer.getLevel())
            .eq(StringUtils.isNotBlank(dealer.getLifecycle()), CrmDealer::getLifecycle, dealer.getLifecycle())
            .eq(ObjectUtil.isNotNull(dealer.getOwnerUserId()), CrmDealer::getOwnerUserId, dealer.getOwnerUserId())
            .eq(StringUtils.isNotBlank(dealer.getCustomerCode()), CrmDealer::getCustomerCode, dealer.getCustomerCode())
            .between(params.get("beginTime") != null && params.get("endTime") != null,
                CrmDealer::getCreateTime, params.get("beginTime"), params.get("endTime"))
            .orderByDesc(CrmDealer::getCreateTime);
        return wrapper;
    }

    @Override
    public CrmDealerVo selectDealerById(Long dealerId) {
        return dealerMapper.selectVoById(dealerId);
    }

    @Override
    public int insertDealer(CrmDealerBo dealer) {
        // 校验经销商编码唯一性
        if (!checkDealerCodeUnique(dealer)) {
            throw new ServiceException("经销商编码已存在");
        }

        CrmDealer crmDealer = MapstructUtils.convert(dealer, CrmDealer.class);
        return dealerMapper.insert(crmDealer);
    }

    @Override
    public int updateDealer(CrmDealerBo dealer) {
        // 校验经销商是否存在
        CrmDealer existingDealer = dealerMapper.selectById(dealer.getDealerId());
        if (ObjectUtil.isNull(existingDealer)) {
            throw new ServiceException("经销商不存在");
        }

        // 校验经销商编码唯一性
        if (!checkDealerCodeUnique(dealer)) {
            throw new ServiceException("经销商编码已存在");
        }

        CrmDealer crmDealer = MapstructUtils.convert(dealer, CrmDealer.class);
        return dealerMapper.updateById(crmDealer);
    }

    @Override
    public int deleteDealerByIds(Long[] dealerIds) {
        return dealerMapper.deleteBatchIds(List.of(dealerIds));
    }

    @Override
    public boolean checkDealerCodeUnique(CrmDealerBo dealer) {
        boolean exist = dealerMapper.exists(new LambdaQueryWrapper<CrmDealer>()
            .eq(CrmDealer::getDealerCode, dealer.getDealerCode())
            .ne(ObjectUtil.isNotNull(dealer.getDealerId()), CrmDealer::getDealerId, dealer.getDealerId()));
        return !exist;
    }
}