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

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DictI18nUtil;
import com.ruoyi.framework.web.domain.BaseEntity;
import com.ruoyi.project.business.domain.TcAccount;
import com.ruoyi.project.business.domain.TcLeadHistory;
import com.ruoyi.project.business.domain.TcProject;
import com.ruoyi.project.business.mapper.TcAccountMapper;
import com.ruoyi.project.business.mapper.TcLeadHistoryMapper;
import com.ruoyi.project.business.mapper.TcProjectMapper;
import com.ruoyi.project.business.service.ITcLeadHistoryService;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author ruoyi
 * @date 2024-04-22
 */
@Slf4j
@Service
public class TcLeadHistoryServiceImpl extends ServiceImpl<TcLeadHistoryMapper, TcLeadHistory> implements ITcLeadHistoryService {

    @Resource
    private TcLeadHistoryMapper tcLeadHistoryMapper;

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private TcAccountMapper tcAccountMapper;

    @Resource
    private TcProjectMapper tcProjectMapper;

    /**
     * 查询【请填写功能名称】
     *
     * @param leadId 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public TcLeadHistory selectTcLeadHistoryById(Long leadId) {
        return tcLeadHistoryMapper.selectTcLeadHistoryById(leadId);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param tcLeadHistory 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<TcLeadHistory> selectTcLeadHistoryList(TcLeadHistory tcLeadHistory) {
        return tcLeadHistoryMapper.selectTcLeadHistoryList(tcLeadHistory);
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param tcLeadHistory 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertTcLeadHistory(TcLeadHistory tcLeadHistory) {
        tcLeadHistory.setCreateTime(DateUtils.getNowDate());
        return tcLeadHistoryMapper.insertTcLeadHistory(tcLeadHistory);
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param tcLeadHistory 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateTcLeadHistory(TcLeadHistory tcLeadHistory) {
        return tcLeadHistoryMapper.updateTcLeadHistory(tcLeadHistory);
    }

    /**
     * 批量删除【请填写功能名称】
     *
     * @param leadIds 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteTcLeadHistoryByLeadIds(Long[] leadIds) {
        return tcLeadHistoryMapper.deleteTcLeadHistoryByLeadIds(leadIds);
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param leadId 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteTcLeadHistoryByLeadId(Long leadId) {
        return tcLeadHistoryMapper.deleteTcLeadHistoryByLeadId(leadId);
    }

    @Override
    public List<TcLeadHistory> getHistoryListByLeadId(Long leadId) {

        List<TcLeadHistory> historyListByLeadIdAsc = getHistoryListByLeadIdAsc(leadId);
        if (CollectionUtil.isEmpty(historyListByLeadIdAsc)) {
            return historyListByLeadIdAsc;
        }

        Map<Long, String> user2NameMap = getUserId2NameMap(historyListByLeadIdAsc);
        Map<String, String> leadHisType = DictI18nUtil.getI18nLabel("lead_his_type");

        // 设置 histories ：操作人 + 本次操作类型 + 本次操作对象
        for (TcLeadHistory history : historyListByLeadIdAsc) {
            // 操作人
            String oriUserName = history.getOriUserName();
            // 本次操作对象
            Long getUser = history.getGetUser();
            String actionType = String.valueOf(history.getActionType());
            //String action = DictI18nUtil.getI18nLabel("lead_his_type", actionType);
            String action = leadHisType.get(actionType);

            String hisContent = oriUserName + " -> " + action;
            switch (actionType) {
                case "0":
                    // 新增
                case "2":
                    // 回收
                case "10":
                    // 静默
                case "8":
                    // 无效
                    history.setHisContent(hisContent);
                    break;
                case "1":
                    // 分配
                    history.setHisContent(hisContent + " -> " + user2NameMap.get(getUser));
                    break;
                case "3":
                    // 转化客户
                    // 查询客户信息
                    TcAccount tcAccount = tcAccountMapper.selectTcAccountByAccountId(getUser);
                    history.setHisContent(hisContent + " -> " + (tcAccount == null ? "-" : tcAccount.getAccountName()));
                    break;
                case "4":
                    // 转化项目
                    // 查询项目信息
                    TcProject tcProject = tcProjectMapper.selectTcProjectByProjectId(getUser);
                    history.setHisContent(hisContent + " -> " + (tcProject == null ? "-" : tcProject.getProjectName()));
                    break;
                default:
                    log.error("线索履历中id为{}的操作类型{}错误", history.getId(), actionType);
                    history.setHisContent(hisContent);
                    break;
            }
        }

        return historyListByLeadIdAsc;
    }


    private List<TcLeadHistory> getHistoryListByLeadIdAsc(Long leadId) {
        TcLeadHistory his = new TcLeadHistory();
        his.setLeadId(leadId);
        List<TcLeadHistory> histories = tcLeadHistoryMapper.selectTcLeadHistoryList(his);
        return histories.stream().sorted(Comparator.comparing(BaseEntity::getCreateTime)).collect(Collectors.toList());
    }

    /**
     * 取出所有分配操作中 分配对象的用户id与用户名称的映射
     */
    private Map<Long, String> getUserId2NameMap(List<TcLeadHistory> historyListByLeadIdAsc) {
        List<Long> allocateUserIds = historyListByLeadIdAsc.stream()
                .filter(item -> null != item.getActionType())
                .filter(item -> 1 == item.getActionType())
                .map(TcLeadHistory::getGetUser)
                .distinct()
                .collect(Collectors.toList());
        Map<Long, String> user2NameMap = null;
        if (CollectionUtil.isNotEmpty(allocateUserIds)) {
            List<SysUser> sysUsers = sysUserMapper.selectUserByIds(allocateUserIds);
            user2NameMap = sysUsers.stream().collect(Collectors.toMap(SysUser::getUserId, SysUser::getNickName));
        }
        return user2NameMap;
    }

    @Override
    public boolean existsUser(Long userId, Long leadId) {
        Integer exist = baseMapper.existsUser(userId, leadId);
        return exist != null;
    }
}
