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.CrmOpportunity;
import org.hzhub.crm.domain.bo.CrmOpportunityBo;
import org.hzhub.crm.domain.vo.CrmOpportunityVo;
import org.hzhub.crm.mapper.CrmOpportunityMapper;
import org.hzhub.crm.service.ICrmOpportunityService;
import org.springframework.stereotype.Service;

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

/**
 * CRM商机 Service 实现
 *
 * @author hzhub
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class CrmOpportunityServiceImpl implements ICrmOpportunityService {

    private final CrmOpportunityMapper opportunityMapper;

    @Override
    public TableDataInfo<CrmOpportunityVo> selectPageOpportunityList(CrmOpportunityBo opportunity, PageQuery pageQuery) {
        LambdaQueryWrapper<CrmOpportunity> wrapper = buildQueryWrapper(opportunity);
        Page<CrmOpportunityVo> page = opportunityMapper.selectVoPage(pageQuery.build(), wrapper);
        return TableDataInfo.build(page);
    }

    /**
     * 构建查询条件
     */
    private LambdaQueryWrapper<CrmOpportunity> buildQueryWrapper(CrmOpportunityBo opportunity) {
        Map<String, Object> params = opportunity.getParams();
        LambdaQueryWrapper<CrmOpportunity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(CrmOpportunity::getDelFlag, SystemConstants.NORMAL)
            .eq(ObjectUtil.isNotNull(opportunity.getDealerId()), CrmOpportunity::getDealerId, opportunity.getDealerId())
            .like(StringUtils.isNotBlank(opportunity.getOpportunityName()), CrmOpportunity::getOpportunityName, opportunity.getOpportunityName())
            .eq(StringUtils.isNotBlank(opportunity.getStage()), CrmOpportunity::getStage, opportunity.getStage())
            .eq(ObjectUtil.isNotNull(opportunity.getOwnerUserId()), CrmOpportunity::getOwnerUserId, opportunity.getOwnerUserId())
            .eq(StringUtils.isNotBlank(opportunity.getStatus()), CrmOpportunity::getStatus, opportunity.getStatus())
            .between(params.get("beginTime") != null && params.get("endTime") != null,
                CrmOpportunity::getCreateTime, params.get("beginTime"), params.get("endTime"))
            .orderByDesc(CrmOpportunity::getCreateTime);
        return wrapper;
    }

    @Override
    public CrmOpportunityVo selectOpportunityById(Long opportunityId) {
        return opportunityMapper.selectVoById(opportunityId);
    }

    @Override
    public int insertOpportunity(CrmOpportunityBo opportunity) {
        CrmOpportunity crmOpportunity = MapstructUtils.convert(opportunity, CrmOpportunity.class);
        return opportunityMapper.insert(crmOpportunity);
    }

    @Override
    public int updateOpportunity(CrmOpportunityBo opportunity) {
        // 校验商机是否存在
        CrmOpportunity existingOpportunity = opportunityMapper.selectById(opportunity.getOpportunityId());
        if (ObjectUtil.isNull(existingOpportunity)) {
            throw new ServiceException("商机不存在");
        }

        CrmOpportunity crmOpportunity = MapstructUtils.convert(opportunity, CrmOpportunity.class);
        return opportunityMapper.updateById(crmOpportunity);
    }

    @Override
    public int deleteOpportunityByIds(Long[] opportunityIds) {
        return opportunityMapper.deleteBatchIds(List.of(opportunityIds));
    }

    @Override
    public int createInitialOpportunity(Long dealerId, Long sourceLeadId, Long ownerUserId) {
        // 创建初始商机
        CrmOpportunity opportunity = new CrmOpportunity();
        opportunity.setDealerId(dealerId);
        opportunity.setOpportunityName("初始商机");
        opportunity.setStage("lead");
        opportunity.setProbability(10); // 初始概率10%
        opportunity.setOwnerUserId(ownerUserId);
        opportunity.setSourceLeadId(sourceLeadId);
        opportunity.setStatus("active");

        int result = opportunityMapper.insert(opportunity);
        if (result > 0) {
            log.info("创建初始商机成功: dealerId={}, opportunityId={}", dealerId, opportunity.getOpportunityId());
        }
        return result;
    }
}