package com.ruoyi.oa.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.oa.domain.OaBusinessProduct;
import com.ruoyi.oa.domain.vo.OaProductVo;
import com.ruoyi.oa.mapper.OaBusinessProductMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.oa.domain.bo.OaBusinessBo;
import com.ruoyi.oa.domain.vo.OaBusinessVo;
import com.ruoyi.oa.domain.OaBusiness;
import com.ruoyi.oa.mapper.OaBusinessMapper;
import com.ruoyi.oa.service.IOaBusinessService;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * CRM 商机Service业务层处理
 *
 * @author ruoyi
 * @date 2025-03-12
 */
@RequiredArgsConstructor
@Service
public class OaBusinessServiceImpl implements IOaBusinessService {

    private final OaBusinessMapper baseMapper;

    private final OaBusinessProductMapper oaBusinessProductMapper;

    /**
     * 查询CRM 商机
     */
    @Override
    public OaBusinessVo queryById(Long businessId){
        return baseMapper.selectVoById(businessId);
    }

    /**
     * 查询CRM 商机列表
     */
    @Override
    public TableDataInfo<OaBusinessVo> queryPageList(OaBusinessBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<OaBusiness> lqw = buildQueryWrapper(bo);
        List<OaBusinessVo> oaBusiness= queryList(bo);
       // Page<OaBusinessVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(oaBusiness);
    }

    /**
     * 查询CRM 商机列表
     */
    @Override
    public List<OaBusinessVo> queryList(OaBusinessBo bo) {
        LambdaQueryWrapper<OaBusiness> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<OaBusiness> buildQueryWrapper(OaBusinessBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<OaBusiness> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getName()), OaBusiness::getName, bo.getName());
        lqw.eq(bo.getCustomerId() != null, OaBusiness::getCustomerId, bo.getCustomerId());
        lqw.eq(bo.getFollowUpStatus() != null, OaBusiness::getFollowUpStatus, bo.getFollowUpStatus());
        lqw.eq(bo.getContactLastTime() != null, OaBusiness::getContactLastTime, bo.getContactLastTime());
        lqw.eq(bo.getContactNextTime() != null, OaBusiness::getContactNextTime, bo.getContactNextTime());
        lqw.eq(bo.getOwnerUserId() != null, OaBusiness::getOwnerUserId, bo.getOwnerUserId());
        lqw.eq(bo.getStatusTypeId() != null, OaBusiness::getStatusTypeId, bo.getStatusTypeId());
        lqw.eq(bo.getStatusId() != null, OaBusiness::getStatusId, bo.getStatusId());
        lqw.eq(bo.getEndStatus() != null, OaBusiness::getEndStatus, bo.getEndStatus());
        lqw.eq(bo.getDealTime() != null, OaBusiness::getDealTime, bo.getDealTime());
        lqw.eq(bo.getTotalProductPrice() != null, OaBusiness::getTotalProductPrice, bo.getTotalProductPrice());
        lqw.eq(bo.getDiscountPercent() != null, OaBusiness::getDiscountPercent, bo.getDiscountPercent());
        lqw.eq(bo.getTotalPrice() != null, OaBusiness::getTotalPrice, bo.getTotalPrice());
        lqw.eq(StringUtils.isNotBlank(bo.getEndRemark()), OaBusiness::getEndRemark, bo.getEndRemark());
        return lqw;
    }

    /**
     * 新增CRM 商机
     */
    @Override
    public Boolean insertByBo(OaBusinessBo bo) {
        OaBusiness add = BeanUtil.toBean(bo, OaBusiness.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setBusinessId(add.getBusinessId());
        }
        return flag;
    }

    /**
     * 修改CRM 商机
     */
    @Override
    public Boolean updateByBo(OaBusinessBo bo) {
        OaBusiness update = BeanUtil.toBean(bo, OaBusiness.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(OaBusiness entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除CRM 商机
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 联查商机与产品以及其关联表
     */
    @Override
    public TableDataInfo<OaProductVo> getBusinessProducts(OaBusinessBo bo) {
        QueryWrapper<OaBusiness> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(bo.getBusinessId() != null,"ob.business_id", bo.getBusinessId());
        return TableDataInfo.build(baseMapper.getBusinessProducts(bo,queryWrapper));
    }

    @Override
    public  TableDataInfo<OaBusiness> getBusinessByCustomerId(Long customerId,PageQuery pageQuery) {
        List<OaBusiness> list = buildQueryByCustomerId(customerId);
        return TableDataInfo.build(list);
    }
    private List<OaBusiness> buildQueryByCustomerId(Long id) {
        LambdaQueryWrapper<OaBusiness> lqw = new LambdaQueryWrapper<>();
        lqw.eq( OaBusiness::getCustomerId,id);
        return baseMapper.selectList(lqw);
    }

    @Override
    public void deleteBusiness(Long businessId) {
        baseMapper.deleteBusinessById(businessId);

        List<OaBusinessProduct> oaBusinessProducts = oaBusinessProductMapper.selectByBusinessId(businessId);
        if(!oaBusinessProducts.isEmpty()){
            oaBusinessProductMapper.deleteByBusinessId(businessId);
        }
    }

    @Override
    public void setFollow(Long businessId) {
        baseMapper.setFollow(businessId);
    }

    /**
     * 查询CRM 批量商机
     */
    @Override
    public List<OaBusinessVo> queryByIds(Collection<Long> list) {
        if (list == null || list.isEmpty()) {
            return Collections.emptyList();
        }
        return baseMapper.selectVoList(new LambdaQueryWrapper<OaBusiness>().in(OaBusiness::getBusinessId, list));
    }
}
