package com.ruoyi.oa.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.exception.ServiceException;
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.OaBusiness;
import com.ruoyi.oa.domain.bo.OaFollowUpRecordAddBo;
import com.ruoyi.oa.domain.vo.OaBusinessVo;
import com.ruoyi.oa.domain.vo.OaFollowUpRecordQueryVo;
import com.ruoyi.oa.service.IOaBusinessService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.oa.domain.bo.OaFollowUpRecordBo;
import com.ruoyi.oa.domain.vo.OaFollowUpRecordVo;
import com.ruoyi.oa.domain.OaFollowUpRecord;
import com.ruoyi.oa.mapper.OaFollowUpRecordMapper;
import com.ruoyi.oa.service.IOaFollowUpRecordService;

import java.util.*;
import java.util.stream.Collectors;

/**
 * CRM 跟进记录Service业务层处理
 *
 * @author ruoyi
 * @date 2025-03-12
 */
@RequiredArgsConstructor
@Service
public class OaFollowUpRecordServiceImpl implements IOaFollowUpRecordService {

    private final OaFollowUpRecordMapper baseMapper;

    @Autowired
    private IOaBusinessService oaBusinessService;

    /**
     * 查询CRM 跟进记录
     */
    @Override
    public OaFollowUpRecordVo queryById(Long followId){
        return baseMapper.selectVoById(followId);
    }

    /**
     * 查询CRM 跟进记录列表
     */
    @Override
    public TableDataInfo<OaFollowUpRecordVo> queryPageList(OaFollowUpRecordBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<OaFollowUpRecord> lqw = buildQueryWrapper(bo);
        Page<OaFollowUpRecordVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询CRM 跟进记录列表
     */
    @Override
    public List<OaFollowUpRecordVo> queryList(OaFollowUpRecordBo bo) {
        LambdaQueryWrapper<OaFollowUpRecord> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<OaFollowUpRecord> buildQueryWrapper(OaFollowUpRecordBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<OaFollowUpRecord> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getType() != null, OaFollowUpRecord::getType, bo.getType());
        lqw.like(StringUtils.isNotBlank(bo.getContent()), OaFollowUpRecord::getContent, bo.getContent());
        lqw.eq(bo.getNextTime() != null, OaFollowUpRecord::getNextTime, bo.getNextTime());
        lqw.eq(StringUtils.isNotBlank(bo.getPicUrls()), OaFollowUpRecord::getPicUrls, bo.getPicUrls());
        lqw.eq(StringUtils.isNotBlank(bo.getFileUrls()), OaFollowUpRecord::getFileUrls, bo.getFileUrls());
        lqw.eq(StringUtils.isNotBlank(bo.getBusinessIds()), OaFollowUpRecord::getBusinessIds, bo.getBusinessIds());
        lqw.eq(bo.getBusinessId() != null, OaFollowUpRecord::getBusinessId, bo.getBusinessId());
        lqw.eq(StringUtils.isNotBlank(bo.getContactIds()), OaFollowUpRecord::getContactIds, bo.getContactIds());
        return lqw;
    }

    /**
     * 新增CRM 跟进记录
     */
    @Override
    public Boolean insertByBo(OaFollowUpRecordBo bo) {
        OaFollowUpRecord add = BeanUtil.toBean(bo, OaFollowUpRecord.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setFollowId(add.getFollowId());
        }
        return flag;
    }

    /**
     * 修改CRM 跟进记录
     */
    @Override
    public Boolean updateByBo(OaFollowUpRecordBo bo) {
        OaFollowUpRecord update = BeanUtil.toBean(bo, OaFollowUpRecord.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(OaFollowUpRecord entity){
        //TODO 做一些数据校验,如唯一约束--(仅仅验证了顾客id唯一，如有不对可删去)
        if(!checkCustomerId(entity)){
            throw new ServiceException("操作跟进记录失败, 跟进记录客服ID已存在!");
        }

    }

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

    @Override
    public List<OaFollowUpRecordVo> selectByBusinessIds(Collection<Long> businessIds) {

        LambdaQueryWrapper<OaFollowUpRecord> queryWrapper = new LambdaQueryWrapper<>();

        // 将多个业务id用 or 拼接
        for (Long id : businessIds) {
            queryWrapper.or().apply("FIND_IN_SET({0}, business_ids)", id);
        }

        return baseMapper.selectVoList(queryWrapper);
    }

    /**
     * 验证customerid是否可以操作
     */
    public Boolean checkCustomerId(OaFollowUpRecord entity) {
        if(entity.getCustomerId() != null){
            OaFollowUpRecord followUpRecord=baseMapper.selectOne(new LambdaQueryWrapper<OaFollowUpRecord>().eq(OaFollowUpRecord::getCustomerId,entity.getCustomerId()));
            if(followUpRecord!=null&&!entity.getFollowId().equals(followUpRecord.getFollowId()))return false;
        }
        return true;
    }

    /**
     * 添加跟进记录
     */
    @Override
    public Boolean insertByAddBo(OaFollowUpRecordAddBo bo) {
        OaFollowUpRecord add = BeanUtil.toBean(bo, OaFollowUpRecord.class);
        add.setContent(bo.getContactLastContent());
        validEntityBeforeSave(add);
        return baseMapper.insert(add) > 0;
    }

    /**
     * 通过顾客id获取跟进记录
     */
    @Override
    public OaFollowUpRecordQueryVo selectByCustomerId(Long customerId) {
        //通过customerId查询出跟进记录
        OaFollowUpRecord followUpRecord=baseMapper.selectOne(new LambdaQueryWrapper<OaFollowUpRecord>().eq(OaFollowUpRecord::getCustomerId,customerId));

        OaFollowUpRecordQueryVo queryVo=BeanUtil.toBean(followUpRecord,OaFollowUpRecordQueryVo.class);
        //通过businessIds查询出业务
        if (StringUtils.isNotBlank(followUpRecord.getBusinessIds())){
            //分割businessIds
            List<Long> businessIds = Arrays.stream(followUpRecord.getBusinessIds().split(","))
                    .map(String::trim)
                    .map(Long::parseLong)
                    .collect(Collectors.toList());
            //批量查询出业务
            List<OaBusinessVo> businessVos = oaBusinessService.queryByIds(businessIds);
            queryVo.setBusinessVoList(businessVos);
        }
        return queryVo;
    }
}
