package com.fs.qw.service.impl;

import java.util.Collections;
import java.util.Date;
import java.util.List;

import com.fs.common.core.domain.R;
import com.fs.common.utils.DateUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fs.common.utils.StringUtils;
import com.fs.his.domain.FsSopDoctorTask;
import com.fs.his.dto.SopDoctorTaskDto;
import com.fs.his.mapper.FsSopDoctorTaskMapper;
import com.fs.his.param.DoctorTaskStatsParam;
import com.fs.his.service.IFsSopDoctorTaskService;
import com.fs.his.utils.PhoneUtil;
import com.fs.his.vo.SopDoctorTaskVo;
import com.fs.hisStore.service.IFsUserInformationCollectionService;
import com.fs.qw.domain.QwExternalContact;
import com.fs.qw.mapper.QwExternalContactMapper;
import com.fs.qw.param.FsDoctorMemberSalesQueryParam;
import com.fs.qw.param.MemberSalesParam;
import com.fs.qw.vo.DoctorTaskStatsVO;
import com.fs.qw.vo.FsDoctorMemberSalesVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fs.qw.mapper.FsDoctorMemberSalesMapper;
import com.fs.qw.domain.FsDoctorMemberSales;
import com.fs.qw.service.IFsDoctorMemberSalesService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * 医生会员搭销Service业务层处理
 * 
 * @author fs
 * @date 2026-01-13
 */
@Service
public class FsDoctorMemberSalesServiceImpl extends ServiceImpl<FsDoctorMemberSalesMapper, FsDoctorMemberSales> implements IFsDoctorMemberSalesService {

    @Autowired
    private FsDoctorMemberSalesMapper memberSalesMapper;

    @Autowired
    private FsSopDoctorTaskMapper sopDoctorTaskMapper;

    @Autowired
    private QwExternalContactMapper externalContactMapper;

    @Autowired
    private IFsUserInformationCollectionService userInformationCollectionService;

    @Autowired
    private FsSopDoctorTaskMapper fsSopDoctorTaskMapper;

    @Autowired
    private IFsSopDoctorTaskService fsSopDoctorTaskService;

    @Transactional
    @Override
    public R push(MemberSalesParam param) {

        QwExternalContact qwExternalContact = externalContactMapper.selectQwExternalContactById(param.getExId());
        if (qwExternalContact == null) {
            return R.error("没有外部联系信息");
        }
        if (qwExternalContact.getIsPush() == 1) {
            return R.error("会员已推送，推送失败");
        }

        FsDoctorMemberSales memberSales = new FsDoctorMemberSales();
        BeanUtils.copyProperties(param, memberSales);
        memberSales.setCreateTime(DateUtils.getNowDate());

        if(memberSalesMapper.insertFsDoctorMemberSales(memberSales) > 0){
            //插入第一次推送时随访待处理
            Date nowDate = DateUtils.getNowDate();
            // 为医生创建初始任务
            FsSopDoctorTask doctorTask = new FsSopDoctorTask();
            doctorTask.setDoctorId(memberSales.getDoctorId());
            doctorTask.setStatus(0);//0:待处理
            doctorTask.setCreateTime(nowDate);
            doctorTask.setQwExternalContactId(memberSales.getExId());
            doctorTask.setCompanyUserId(memberSales.getCompanyUserId());
            doctorTask.setRemark("新推送会员");
            doctorTask.setUserId(memberSales.getFsUserId());
            doctorTask.setDoctorMemberSalesId(memberSales.getId());
            doctorTask.setTaskType(1); // 初始任务
            doctorTask.setHandlePersonType(1); // 1:医生
            sopDoctorTaskMapper.insertFsSopDoctorTask(doctorTask);

            // 为销售创建初始任务
            FsSopDoctorTask salesTask = new FsSopDoctorTask();
            salesTask.setDoctorId(memberSales.getDoctorId());
            salesTask.setStatus(0);//0:待处理
            salesTask.setCreateTime(nowDate);
            salesTask.setQwExternalContactId(memberSales.getExId());
            salesTask.setCompanyUserId(memberSales.getCompanyUserId());
            salesTask.setRemark("新推送会员");
            salesTask.setUserId(memberSales.getFsUserId());
            salesTask.setDoctorMemberSalesId(memberSales.getId());
            salesTask.setTaskType(1); // 初始任务
            salesTask.setHandlePersonType(2); // 2:销售
            sopDoctorTaskMapper.insertFsSopDoctorTask(salesTask);
            //更新企业外部联系人推送状态
            QwExternalContact map = new QwExternalContact();
            map.setId(param.getExId());
            map.setIsPush(1);
            externalContactMapper.updateQwExternalContact(map);
            return R.ok("推送成功");
        }

        return R.error("推送失败");
    }

    @Override
    public List<FsDoctorMemberSalesVO> selectFsDoctorMemberSalesVOList(FsDoctorMemberSalesQueryParam param,Integer handelPersonType) {
        //1.跟进会员信息
        List<FsDoctorMemberSalesVO> voList = memberSalesMapper.selectFsDoctorMemberSalesVOList(param);
        if (!CollectionUtils.isEmpty(voList)) {
            for (FsDoctorMemberSalesVO vo : voList) {
                if (!StringUtils.isEmpty(vo.getPhone())) {
                    //
                    boolean likelyEncryptedByEntropy = PhoneUtil.isLikelyEncryptedByEntropy(vo.getPhone());
                    if (likelyEncryptedByEntropy) {
                        String decryptPhone = PhoneUtil.decryptPhone(vo.getPhone());
                        vo.setPhone(decryptPhone);
                    }
                }
                //2.获取跟进会员待处理的总数
                FsSopDoctorTask doctorTask = new FsSopDoctorTask();
                doctorTask.setDoctorMemberSalesId(vo.getId());
                if (handelPersonType==1){
                    doctorTask.setDoctorId(vo.getDoctorId());
                    Long unprocessedDoctorTaskCount = (long) fsSopDoctorTaskService.selectFsSopDoctorTaskList(doctorTask).size();
                    vo.setUnprocessed(unprocessedDoctorTaskCount);
                } else if (handelPersonType==2) {
                    doctorTask.setCompanyUserId(vo.getCompanyUserId());
                    Long unprocessedDoctorTaskCount = (long) fsSopDoctorTaskService.getSalesTaskList(doctorTask).size();
                    vo.setUnprocessed(unprocessedDoctorTaskCount);
                }

            }
        }
        return voList;
    }

    /**
     * 查询医生会员搭销
     * 
     * @param id 医生会员搭销主键
     * @return 医生会员搭销
     */
    @Override
    public FsDoctorMemberSales selectFsDoctorMemberSalesById(Long id)
    {
        return baseMapper.selectFsDoctorMemberSalesById(id);
    }

    /**
     * 查询医生会员搭销列表
     * 
     * @param fsDoctorMemberSales 医生会员搭销
     * @return 医生会员搭销
     */
    @Override
    public List<FsDoctorMemberSales> selectFsDoctorMemberSalesList(FsDoctorMemberSales fsDoctorMemberSales)
    {
        return baseMapper.selectFsDoctorMemberSalesList(fsDoctorMemberSales);
    }

    /**
     * 新增医生会员搭销
     * 
     * @param fsDoctorMemberSales 医生会员搭销
     * @return 结果
     */
    @Override
    public int insertFsDoctorMemberSales(FsDoctorMemberSales fsDoctorMemberSales)
    {
        fsDoctorMemberSales.setCreateTime(DateUtils.getNowDate());
        return baseMapper.insertFsDoctorMemberSales(fsDoctorMemberSales);
    }

    /**
     * 修改医生会员搭销
     * 
     * @param fsDoctorMemberSales 医生会员搭销
     * @return 结果
     */
    @Override
    public int updateFsDoctorMemberSales(FsDoctorMemberSales fsDoctorMemberSales)
    {
        fsDoctorMemberSales.setUpdateTime(DateUtils.getNowDate());
        return baseMapper.updateFsDoctorMemberSales(fsDoctorMemberSales);
    }

    /**
     * 批量删除医生会员搭销
     * 
     * @param ids 需要删除的医生会员搭销主键
     * @return 结果
     */
    @Override
    public int deleteFsDoctorMemberSalesByIds(Long[] ids)
    {
        return baseMapper.deleteFsDoctorMemberSalesByIds(ids);
    }

    /**
     * 删除医生会员搭销信息
     * 
     * @param id 医生会员搭销主键
     * @return 结果
     */
    @Override
    public int deleteFsDoctorMemberSalesById(Long id)
    {
        return baseMapper.deleteFsDoctorMemberSalesById(id);
    }

    @Override
    public List<DoctorTaskStatsVO> selectDoctorTaskStats(DoctorTaskStatsParam param) {
        List<DoctorTaskStatsVO> doctorTaskStatsVOS = memberSalesMapper.selectDoctorTaskStats(param);
        if (CollectionUtils.isEmpty(doctorTaskStatsVOS)){
            return Collections.emptyList();
        }
        return doctorTaskStatsVOS;
    }

    @Override
    public List<SopDoctorTaskVo> selectCompletedTasksList(SopDoctorTaskDto queryDto) {
        queryDto.setStatus(1);//1:已处理
        List<SopDoctorTaskVo> sopDoctorTaskVos = fsSopDoctorTaskMapper.selectFsSopDoctorTaskVoList(queryDto);
        if (!CollectionUtils.isEmpty(sopDoctorTaskVos)){
            return sopDoctorTaskVos;
        }
        return sopDoctorTaskVos;
    }
}
