package com.ruoyi.project.business.service.impl;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.URLUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.enums.FileBuzType;
import com.ruoyi.common.enums.SerialNumberPrefix;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.LocalUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.SpecialCharacterEscaper;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.project.business.domain.TbFile;
import com.ruoyi.project.business.domain.TcLead;
import com.ruoyi.project.business.mapper.TcLeadMapper;
import com.ruoyi.project.business.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.util.Pair;
import org.springframework.stereotype.Service;
import com.ruoyi.project.business.mapper.TcFollowMapper;
import com.ruoyi.project.business.domain.TcFollow;
import com.ruoyi.project.business.domain.TcFollowForList;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Optional;
import java.util.stream.Collectors;

import static com.ruoyi.project.business.enums.lead.LeadStatusEnum.*;

/**
 * 【跟进管理】Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-04-07
 */
@Service
public class TcFollowServiceImpl implements ITcFollowService 
{
    // 可以跟进的线索状态集合
    // 待分配// 已分配// 已回收// 跟进中// 静默
    private static final List<String> FOLLOWABLE_LEAD_STATUS = Arrays.asList(TO_BE_ALLOCATED.getCode(), ALLOCATED.getCode(), RECYCLED.getCode(), FOLLOWING.getCode(), ON_HOLD.getCode());
    
    @Resource
    private TcFollowMapper tcFollowMapper;

    @Resource
    private ITcLeadService tcLeadService;

    @Resource
    private ITcAccountService tcAccountService;

    @Resource
    private ITcProjectService tcProjectService;

    @Resource
    private RedisCache redisCache;

    @Resource
    private ITbFileService tbFileService;

    @Resource
    private TcLeadMapper tcLeadMapper;

    /**
     * 查询【跟进管理】
     * 
     * @param followId 【跟进管理】主键
     * @return 【跟进管理】
     */
    @Override
    public TcFollow selectTcFollowByFollowId(Long followId)
    {
        TcFollow tcFollow = tcFollowMapper.selectTcFollowByFollowId(followId);
        // 查询附件
//        String serUrl = serverConfig.getUrl();
        List<TbFile> tbFiles = tbFileService.selectTbFileListByBuzIdAndBuzType(followId, FileBuzType.Follow.getType());
        List<String> collect = tbFiles.stream().map(item -> item.getFilePath()).collect(Collectors.toList());
        tcFollow.setAnnexList(collect);
        tcFollow.setTbFiles(tbFiles);
        String urls = String.join(",", collect);
        tcFollow.setAnnex(urls);

        return tcFollow;
    }

    /**
     * 查询【跟进管理】列表
     * 
     * @param tcFollow 【跟进管理】
     * @return 【跟进管理】
     */
    @Override
    public List<TcFollowForList> selectTcFollowList(TcFollow tcFollow)
    {
        // 暂时删除时区转换
//        if (com.ruoyi.common.utils.StringUtils.isNotEmpty(tcFollow.getBeginTime())) {
//            tcFollow.setBeginTime(DateUtils.CNTimeStr(tcFollow.getBeginTime(),SecurityUtils.getTimeZone()));
//        }
//        if (com.ruoyi.common.utils.StringUtils.isNotEmpty(tcFollow.getEndTime())) {
//            tcFollow.setEndTime(DateUtils.CNTimeStr(tcFollow.getEndTime(),SecurityUtils.getTimeZone()));
//        }

        SpecialCharacterEscaper.escapeSpecialCharacters(tcFollow, TcFollow::getFollowNo, TcFollow::getBusinessNo, TcFollow::getFollowPerson, TcFollow::getContactPerson, TcFollow::getFollowDesc, TcFollow::getFollower);

        tcFollow.setPermissionChar(SecurityUtils.getPermissionCharIns());
        Long loginUserId = SecurityUtils.getUserId();
        // 代理商销售经理的场合
        if(SecurityUtils.hasRoleAgentSales()){
            tcFollow.setLoginUserId(loginUserId);
        }
        // SQL 中的 case when 可以使用 mybatis if 标签代替
        List<TcFollowForList> follows = tcFollowMapper.selectTcFollowList(tcFollow);
        LocalUtils.setLocalAreaAndCountryNameBatch(follows, TcFollowForList::getAreaId, TcFollowForList::getCountryId, TcFollowForList::setAreaName, TcFollowForList::setCountryName);
        return follows;
    }

    /**
     * 新增【跟进管理】
     * 
     * @param tcFollow 【跟进管理】
     * @return 结果
     */
    @Override
    public int insertTcFollow(TcFollow tcFollow)
    {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String followPerson;
        String permissionChar = SecurityUtils.getPermissionCharIns();

        Date nowDate = DateUtils.getNowDate();
        followPerson = "";
        if("0".equals(tcFollow.getFollowType())){
            followPerson = tcLeadService.selectTcLeadByLeadId(tcFollow.getBusinessId()).getCompany();
        }
        if("1".equals(tcFollow.getFollowType())){
            followPerson = tcAccountService.selectTcAccountByAccountId(tcFollow.getBusinessId()).getAccountName();
        }
        if("2".equals(tcFollow.getFollowType())){
            followPerson = tcProjectService.selectTcProjectByProjectId(tcFollow.getBusinessId()).getProjectName();
        }
        tcFollow.setFollowTime(tcFollow.getFollowTime() == null ? nowDate : tcFollow.getFollowTime());
        tcFollow.setFollowPerson(followPerson);
        String followNo = redisCache.generateSerialNumber(SerialNumberPrefix.FL.getPrefix());
        tcFollow.setFollowNo(followNo);
        tcFollow.setPermissionChar(permissionChar);

        tcFollow.setCreateBy(SecurityUtils.getUserId().toString());
        tcFollow.setCreateTime(nowDate);
        tcFollow.setUpdateBy(SecurityUtils.getUserId().toString());
        tcFollow.setUpdateTime(nowDate);

        int rows =  tcFollowMapper.insertTcFollow(tcFollow);
        // 保存附件
        saveFollowFile(tcFollow);
        // 更新线索的状态
        if("0".equals(tcFollow.getFollowType())){
            // tcLeadMapper.updateFollowStatusByLeadId(tcFollow.getBusinessId());
            tcLeadService.update(Wrappers.lambdaUpdate(TcLead.class)
                    .set(TcLead::getStatus, FOLLOWING.getCode())
                    .eq(TcLead::getLeadId, tcFollow.getBusinessId())
                    .in(TcLead::getStatus, FOLLOWABLE_LEAD_STATUS)
            );
        }
        return rows;
    }

    private void saveFollowFile(TcFollow tcFollow) {
        // 保存附件
        String annex = tcFollow.getAnnex();
        if (StringUtils.isNotBlank(annex)) {
            for (String fileUrl : annex.split(",")) {
                // 获取文件名：
                fileUrl = fileUrl.replaceAll(" ", "%20");
                // 解析URL
                String path = URLUtil.getPath(fileUrl);
                // 从路径中获取文件名
                String fileName = FileUtil.getName(path);
                TbFile tbFile = new TbFile(tcFollow.getFollowId(), FileBuzType.Follow.getType(), fileName, fileName, fileUrl);
                tbFile.setCreateBy(SecurityUtils.getUserId().toString());
                tbFile.setCreateTime(new Date());
                tbFileService.insertTbFile(tbFile);
            }
        }
    }

    /**
     * 修改【跟进管理】
     * 
     * @param tcFollow 【跟进管理】
     * @return 结果
     */
    @Override
    public int updateTcFollow(TcFollow tcFollow)
    {
//        Date nowDate = DateUtils.UTCTimeDate()
        Date nowDate = DateUtils.getNowDate();

        // 删除附件 url
        if(tcFollow.getTbFiles() != null && tcFollow.getTbFiles().size() > 0){
            Optional.ofNullable(tcFollow.getTbFiles()).ifPresent(tbFiles -> {
                tbFileService.deleteTbFileByIds(tbFiles.stream().map(TbFile::getId).toArray(Long[]::new));
            });
        }
        //保存附件
        saveFollowFile(tcFollow);

        tcFollow.setUpdateBy(SecurityUtils.getUserId().toString());
        tcFollow.setUpdateTime(nowDate);
        return tcFollowMapper.updateTcFollow(tcFollow);
    }

    /**
     * 批量删除跟进记录
     * 
     * @param followIds 需要删除的跟进记录主键
     * @return 结果
     */
    @Override
    public int deleteTcFollowByFollowIds(Long[] followIds)
    {
        return tcFollowMapper.deleteTcFollowByFollowIds(followIds);
    }

    /**
     * 删除【跟进管理】信息
     * 
     * @param followId 【跟进管理】主键
     * @return 结果
     */
    @Override
    public int deleteTcFollowByFollowId(Long followId)
    {
        return tcFollowMapper.deleteTcFollowByFollowId(followId);
    }

    /**
     * 获取新的跟进编号
     *
     * @return 结果
     */
    public String getNewFollowNo()    {
        return tcFollowMapper.getNewFollowNo();
    }

    /**
     * 查询客户相关跟进管理列表
     *
     * @param tcFollow 跟进管理
     * @return 结果
     */
    @Override
    public List<TcFollowForList> selectTcFollowListByAccount(TcFollow tcFollow) {
        return tcFollowMapper.selectTcFollowListByAccount(tcFollow);
    }

    @Override
    public List<TcFollow> selectTcFollowListByTypeAndBusinessId(TcFollow tcFollow) {
        return tcFollowMapper.selectTcFollowListByTypeAndBusinessId(tcFollow);
    }

    @Override
    public List<Pair<Long, String>> selectCountriesByCurUser() {
        List<Long> countryIds = tcFollowMapper.selectCountryIdsByCurUser(SecurityUtils.getPermissionCharIns());
        return LocalUtils.selectCountriesByCurUser(countryIds);
    }
}
