package com.fs.task.service.impl;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.fs.audit.chain.AuditResult;
import com.fs.audit.domain.AuditFlow;
import com.fs.audit.dto.AuditRequestDTO;
import com.fs.audit.dto.CreateAuditRequestDTO;
import com.fs.audit.enums.AuditStatus;
import com.fs.audit.enums.AuditTypeEnum;
import com.fs.audit.enums.AuditUserType;
import com.fs.audit.enums.CreditStatus;
import com.fs.audit.exception.BusinessException;
import com.fs.audit.service.AuditService;
import com.fs.audit.utils.AuditFlowUtils;
import com.fs.common.BeanCopyUtils;
import com.fs.common.config.LoginContextManager;
import com.fs.common.core.domain.entity.SysDictData;
import com.fs.common.core.domain.entity.SysUser;
import com.fs.common.enums.PlatEnum;
import com.fs.common.enums.TaskLabelEnum;
import com.fs.common.enums.UserTypeEnum;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.DictUtils;
import com.fs.common.utils.StringUtils;
import com.fs.company.cache.CompanyUserCacheService;
import com.fs.company.domain.Company;
import com.fs.company.domain.CompanyDept;
import com.fs.company.domain.CompanyUser;
import com.fs.company.service.ICompanyDeptService;
import com.fs.company.service.ICompanyService;
import com.fs.company.service.ICompanyUserService;
import com.fs.delivery.domain.CtArticle;
import com.fs.delivery.domain.CtLongVideo;
import com.fs.delivery.domain.CtShortVideo;
import com.fs.delivery.service.ICtArticleService;
import com.fs.delivery.service.ICtLongVideoService;
import com.fs.delivery.service.ICtShortVideoService;
import com.fs.doctor.domain.Doctor;
import com.fs.doctor.mapper.DoctorMapper;
import com.fs.doctor.service.IDoctorService;
import com.fs.doctor.vo.DoctorVO;
import com.fs.project.domain.Project;
import com.fs.project.service.IProjectService;
import com.fs.system.service.ISysDictTypeService;
import com.fs.system.service.ISysUserService;
import com.fs.task.domain.TaskDeliveryInfo;
import com.fs.task.domain.TaskInfo;
import com.fs.task.domain.TaskMaterialInfo;
import com.fs.task.dto.TaskDeliveryDto;
import com.fs.task.dto.TaskStatsDTO;
import com.fs.task.enums.*;
import com.fs.task.mapper.TaskInfoMapper;
import com.fs.task.service.ITaskDeliveryInfoService;
import com.fs.task.service.ITaskInfoService;
import com.fs.task.service.ITaskMaterialInfoService;
import com.fs.task.vo.*;
import com.fs.task.vo.audit_Info.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 任务信息Service业务层处理
 *
 * @author fs
 * @date 2026-01-04
 */
@Service
public class TaskInfoServiceImpl implements ITaskInfoService {
    @Autowired
    private TaskInfoMapper taskInfoMapper;
    @Autowired
    private AuditService auditService;
    @Autowired
    private ISysDictTypeService sysDictTypeService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ICompanyUserService companyUserService;
    @Autowired
    private IDoctorService doctorService;
    @Autowired
    private IProjectService projectService;
    @Autowired
    private ICompanyService companyService;
    @Autowired
    private ITaskMaterialInfoService taskMaterialInfoService;
    @Autowired
    private ITaskDeliveryInfoService taskDeliveryInfoService;
    @Autowired
    private ICtLongVideoService ctLongVideoService;
    @Autowired
    private ICtShortVideoService ctShortVideoService;
    @Autowired
    private ICtArticleService ctArticleService;


    /**
     * 查询任务信息
     *
     * @param id 任务信息键
     * @return 任务信息
     */
    @Override
    public TaskInfo selectTaskInfoById(Long id) {
        TaskInfo taskInfo = taskInfoMapper.selectTaskInfoById(id);

        if (taskInfo == null) {
            return null;
        }
        // 查询医生信息
        Long doctorId = taskInfo.getDoctorId();
        if (doctorId != null) {
            Doctor doctor = doctorService.selectDoctorById(doctorId);
            DoctorVO doctorVO = BeanCopyUtils.copy(doctor, DoctorVO.class);
            taskInfo.setDoctorVO(doctorVO);
        }

        // 查询任务材料信息
        TaskMaterialInfo queryParam = new TaskMaterialInfo();
        queryParam.setTaskId(id);
        List<TaskMaterialInfo> materialInfoList = taskMaterialInfoService.selectTaskMaterialInfoList(queryParam);
        taskInfo.setMaterialInfoList(materialInfoList);

        return taskInfo;
    }

    /**
     * 查询任务信息列表
     *
     * @param taskInfo 任务信息
     * @return 任务信息
     */
    @Override
    public List<TaskInfo> selectTaskInfoList(TaskInfo taskInfo) {
        List<TaskInfo> taskInfos = taskInfoMapper.selectTaskInfoList(taskInfo);
        if (taskInfos == null || taskInfos.isEmpty()) {
            return taskInfos;
        }


        for (TaskInfo info : taskInfos) {

            Long createAuditUserId = info.getCreateAuditUserId();
            Long finishAuditUserId = info.getFinishAuditUserId();
            AuditUserType userType = AuditUserType.fromCode(info.getCaUserType());


            if (userType.isSysUser()) {

                // 创建审核人（系统用户）
                if (createAuditUserId != null) {
                    SysUser createUser = sysUserService.selectUserById(createAuditUserId);
                    if (createUser != null) {
                        info.setCreateAuditUserName(createUser.getNickName());
                    }
                }

                // 完成审核人（系统用户）
                if (finishAuditUserId != null) {
                    SysUser finishUser = sysUserService.selectUserById(finishAuditUserId);
                    if (finishUser != null) {
                        info.setFinishAuditUserName(finishUser.getNickName());
                    }
                }

            } else {

                // 创建审核人（企业用户）
                if (createAuditUserId != null) {
                    CompanyUser createUser = companyUserService.selectCompanyUserById(createAuditUserId);
                    if (createUser != null) {
                        info.setCreateAuditUserName(createUser.getNickName());
                    }
                }

                // 完成审核人（企业用户）
                if (finishAuditUserId != null) {
                    CompanyUser finishUser = companyUserService.selectCompanyUserById(finishAuditUserId);
                    if (finishUser != null) {
                        info.setFinishAuditUserName(finishUser.getNickName());
                    }
                }
            }
        }

        handleDictData(taskInfos);
        return taskInfos;
    }

    @Autowired
    private DoctorMapper doctorMapper;

    /**
     * 新增任务信息
     *
     * @return 结果
     */
    @Transactional
    @Override
    public int insertTaskInfo(TaskInfoCreateVO vo) {
        //申请时间
        vo.setApplyTime(new Date());

        // ===== ✅ 关键：统一判定操作者是谁（总后台/业务后台） =====
        PlatEnum platEnum = LoginContextManager.getNowPlatEnum();
        Long operatorUserId;
        Integer caUserType; // 0-总后台，1-业务后台（沿用你的字段语义）

        if (PlatEnum.ADMIN.equals(platEnum)) {
            operatorUserId = LoginContextManager.getCurrentUserId();
            caUserType = CreateAuditUserTypeEnum.SYSTEM_USER.getCode();
        } else if (PlatEnum.COMPANY.equals(platEnum)) {
            operatorUserId = LoginContextManager.getCurrentCompanyUserId();
            caUserType = CreateAuditUserTypeEnum.COMPANY_USER.getCode();
        } else if (PlatEnum.COMPANY_APP.equals(platEnum)) {
            operatorUserId = LoginContextManager.getCurrentCompanyUserId();
            caUserType = CreateAuditUserTypeEnum.COMPANY_USER.getCode();
        } else {
            throw new RuntimeException("当前平台不支持创建任务：" + (platEnum == null ? "null" : platEnum.name()));
        }

        if (operatorUserId == null) {
            throw new RuntimeException("无法获取当前操作者ID，plat=" + (platEnum == null ? "null" : platEnum.name()));
        }
        // =======================================================

        for (DoctorTaskVO doctor : vo.getDoctorTaskList()) {

            TaskInfo entity = new TaskInfo();
            BeanUtils.copyProperties(vo, entity);

            // 一个医生一条任务
            entity.setDoctorId(doctor.getDoctorId());

            // ⭐ 每个讲者自己的积分（有就用，没有兜底）
            BigDecimal integral = doctor.getTaskIntegral();
            entity.setTaskIntegral(integral != null ? integral : vo.getTaskIntegral());
            entity.setFinishStatus(Long.parseLong(TaskFinishStatusEnum.UNFINISHED.getCode().toString()));

            // 初始化状态
            entity.setTaskStatus(TaskStatusEnum.UN_FINISHED.getCode());
            entity.setCreateAuditStatus(0);
            entity.setFinishAuditStatus(0);
            entity.setServiceConfirmStatus(ServiceConfirmStatusEnum.PENDING.getCode());
            entity.setCreateTime(DateUtils.getNowDate());

            // ✅ 记录创建人类型  0客服(默认) 1系统用户
            entity.setCaUserType(caUserType);

            // 临时编号
            entity.setTaskNo("TMP_" + UUID.randomUUID().toString().replace("-", ""));
            String doctorName = doctorMapper.selectDoctorNameById(doctor.getDoctorId());
            Long taskType = vo.getTaskType();

            String taskTypeStr = DictUtils.getDictLabel("task_type", String.valueOf(taskType));

            entity.setTaskName(String.format("%s医生的%s", doctorName, taskTypeStr));
            entity.setFinishAuditStatus(TaskFinishAuditStatus.NOCREATE.getCode());

            taskInfoMapper.insertTaskInfo(entity);

            // 正式编号
            String taskNo = "CRW" + String.format("%014d", entity.getId());
            entity.setTaskNo(taskNo);

            // 初始化审核流程（✅ 用 operatorUserId，别再用 userId / SecurityUtils）
            handleCreatAuditInit(entity, operatorUserId);

            taskInfoMapper.updateTaskInfo(entity);
        }

        return 1;
    }


    /**
     * 修改任务信息
     *
     * @param taskInfo 任务信息
     * @return 结果
     */
    @Override
    public int updateTaskInfo(TaskInfo taskInfo) {
        taskInfo.setUpdateTime(DateUtils.getNowDate());
        return taskInfoMapper.updateTaskInfo(taskInfo);
    }

    /**
     * 批量删除任务信息
     *
     * @param ids 需要删除的任务信息键
     * @return 结果
     */
    @Override
    public int deleteTaskInfoByIds(Long[] ids) {
        return taskInfoMapper.deleteTaskInfoByIds(ids);
    }

    /**
     * 删除任务信息信息
     *
     * @param id 任务信息键
     * @return 结果
     */
    @Override
    public int deleteTaskInfoById(Long id) {
        return taskInfoMapper.deleteTaskInfoById(id);
    }

    /**
     * 创建审核
     *
     * @param taskCreateAuditReqVO
     */
    @Transactional
    @Override
    public void doCreateAudit(TaskCreateAuditReqVO taskCreateAuditReqVO) {
        // 从安全上下文拿当前登录人
        Long userId = LoginContextManager.getCurrentCompanyUserId();
        if (Objects.isNull(userId)) {
            throw new BusinessException("当前用户不存在");
        }
        Long taskId = taskCreateAuditReqVO.getTaskId();
        if (Objects.isNull(taskId)) {
            throw new BusinessException("任务id不能为空");
        }

        TaskInfo taskInfo = this.selectTaskInfoById(taskId);
        if (Objects.isNull(taskInfo)) {
            throw new BusinessException("审核的任务不存在");
        }

        Long createAuditInstanceId = taskInfo.getCreateAuditInstanceId();

        //调用审核执行
        AuditRequestDTO auditRequestDTO = new AuditRequestDTO();
        auditRequestDTO.setAuditId(createAuditInstanceId);
        auditRequestDTO.setUserId(userId);
        auditRequestDTO.setUserType(UserTypeEnum.SALES.getCode());
        auditRequestDTO.setComment(taskCreateAuditReqVO.getCreateAuditOpinion());
        auditRequestDTO.setCompanyId(taskCreateAuditReqVO.getCompanyId());
        auditRequestDTO.setAction(taskCreateAuditReqVO.getCreateAuditStatus());
        AuditResult auditResult = auditService.doAudit(auditRequestDTO);
        boolean success = auditResult.isSuccess();
        if (!success) {
            throw new BusinessException(auditResult.getMessage());
        }

        //回填taskInfo
        taskInfo.setCreateAuditTime(new Date());
        taskInfo.setCreateAuditUserId(userId);
        taskInfo.setCreateAuditStatus(taskCreateAuditReqVO.getCreateAuditStatus());
        taskInfo.setCreateAuditRemark(taskCreateAuditReqVO.getCreateAuditOpinion());
        this.updateTaskInfo(taskInfo);
        //完成审核初始化
//        if (taskCreateAuditReqVO.getCreateAuditStatus().equals(CreditStatus.APPROVED.getCode())) {
//            handleFinishAuditInit(taskInfo, userId);
//
//        }


    }

    @Override
    public void appDoCreateAudit(TaskCreateAuditReqVO taskCreateAuditReqVO) {
        // 从安全上下文拿当前登录人
        Long userId = taskCreateAuditReqVO.getCreateAuditUserId();
        if (Objects.isNull(userId)) {
            throw new BusinessException("当前用户不存在");
        }
        Long taskId = taskCreateAuditReqVO.getTaskId();
        if (Objects.isNull(taskId)) {
            throw new BusinessException("任务id不能为空");
        }

        TaskInfo taskInfo = this.selectTaskInfoById(taskId);
        if (Objects.isNull(taskInfo)) {
            throw new BusinessException("审核的任务不存在");
        }

        Long createAuditInstanceId = taskInfo.getCreateAuditInstanceId();

        //调用审核执行
        AuditRequestDTO auditRequestDTO = new AuditRequestDTO();
        auditRequestDTO.setAuditId(createAuditInstanceId);
        auditRequestDTO.setUserId(userId);
        auditRequestDTO.setUserType(UserTypeEnum.SALES.getCode());
        auditRequestDTO.setComment(taskCreateAuditReqVO.getCreateAuditOpinion());
        auditRequestDTO.setCompanyId(taskCreateAuditReqVO.getCompanyId());
        auditRequestDTO.setAction(taskCreateAuditReqVO.getCreateAuditStatus());
        AuditResult auditResult = auditService.doAudit(auditRequestDTO); //todo
        if (!auditResult.isSuccess()) {
            throw new BusinessException(auditResult.getMessage());
        }
        //回填taskInfo
        taskInfo.setCreateAuditTime(new Date());
        taskInfo.setCreateAuditUserId(userId);
        taskInfo.setCreateAuditStatus(taskCreateAuditReqVO.getCreateAuditStatus());
        taskInfo.setCreateAuditRemark(taskCreateAuditReqVO.getCreateAuditOpinion());
        this.updateTaskInfo(taskInfo);
    }


    @Override
    public void dofinishAudit(TaskFinishAuditReqVO taskFinishAuditReqVO) {
        // 从安全上下文拿当前登录人
        Long userId = LoginContextManager.getCurrentCompanyUserId();
        if (Objects.isNull(userId)) {
            throw new BusinessException("当前用户不存在");
        }
        Long taskId = taskFinishAuditReqVO.getTaskId();
        if (Objects.isNull(taskId)) {
            throw new BusinessException("任务id不能为空");
        }

        TaskInfo taskInfo = this.selectTaskInfoById(taskId);
        if (Objects.isNull(taskInfo)) {
            throw new BusinessException("审核的任务不存在");
        }

        Long finishAuditInstanceId = taskInfo.getFinishAuditInstanceId();

        //调用审核执行
        AuditRequestDTO auditRequestDTO = new AuditRequestDTO();
        auditRequestDTO.setAuditId(finishAuditInstanceId);
        auditRequestDTO.setUserId(userId);
        auditRequestDTO.setUserType(UserTypeEnum.SALES.getCode());
        auditRequestDTO.setComment(taskFinishAuditReqVO.getFinishAuditOpinion());
        auditRequestDTO.setCompanyId(taskFinishAuditReqVO.getCompanyId());
        auditRequestDTO.setAction(taskFinishAuditReqVO.getFinishAuditStatus());
        auditService.doAudit(auditRequestDTO);

        //回填taskInfo
        taskInfo.setFinishAuditTime(new Date());
        taskInfo.setFinishAuditUserId(userId);
        taskInfo.setFinishAuditStatus(taskFinishAuditReqVO.getFinishAuditStatus());
        taskInfo.setFinishAuditRemark(taskFinishAuditReqVO.getFinishAuditOpinion());
        if (Objects.equals(taskFinishAuditReqVO.getFinishAuditStatus(), TaskFinishAuditStatus.APPROVED.getCode())) {
            taskInfo.setTaskStatus(TaskFinishAuditStatus.APPROVED.getCode());
        }
        this.updateTaskInfo(taskInfo);

    }

    @Override
    public void appDofinishAudit(TaskFinishAuditReqVO taskFinishAuditReqVO) {
        // 从安全上下文拿当前登录人
        Long userId = taskFinishAuditReqVO.getFinishAuditUserId();
        if (Objects.isNull(userId)) {
            throw new BusinessException("当前用户不存在");
        }
        Long taskId = taskFinishAuditReqVO.getTaskId();
        if (Objects.isNull(taskId)) {
            throw new BusinessException("任务id不能为空");
        }

        TaskInfo taskInfo = this.selectTaskInfoById(taskId);
        if (Objects.isNull(taskInfo)) {
            throw new BusinessException("审核的任务不存在");
        }
        if (taskInfo.getCreateAuditStatus() != null && taskInfo.getCreateAuditStatus() == 0) {
            throw new BusinessException("未审核创建任务，不能审核完成任务");
        }
        Long finishAuditInstanceId = taskInfo.getFinishAuditInstanceId();

        //调用审核执行
        AuditRequestDTO auditRequestDTO = new AuditRequestDTO();
        auditRequestDTO.setAuditId(finishAuditInstanceId);
        auditRequestDTO.setUserId(userId);
        auditRequestDTO.setUserType(UserTypeEnum.SALES.getCode());
        auditRequestDTO.setComment(taskFinishAuditReqVO.getFinishAuditOpinion());
        auditRequestDTO.setCompanyId(taskFinishAuditReqVO.getCompanyId());
        auditRequestDTO.setAction(taskFinishAuditReqVO.getFinishAuditStatus());
        AuditResult auditResult = auditService.doAudit(auditRequestDTO);
        if (!auditResult.isSuccess()) {
            throw new BusinessException(auditResult.getMessage());
        }

        //回填taskInfo
        taskInfo.setFinishAuditTime(new Date());
        taskInfo.setFinishAuditUserId(userId);
        taskInfo.setFinishAuditStatus(taskFinishAuditReqVO.getFinishAuditStatus());
        taskInfo.setFinishAuditRemark(taskFinishAuditReqVO.getFinishAuditOpinion());
        if (Objects.equals(taskFinishAuditReqVO.getFinishAuditStatus(), TaskFinishAuditStatus.APPROVED.getCode())) {
            taskInfo.setTaskStatus(TaskFinishAuditStatus.APPROVED.getCode());
        }
        this.updateTaskInfo(taskInfo);
    }

    /**
     * 任务的创建审核初始化处理器
     *
     * @param taskInfo
     * @param userId
     */
    private void handleCreatAuditInit(TaskInfo taskInfo, Long userId) {
        CreateAuditRequestDTO createAuditRequestDTO = new CreateAuditRequestDTO();
        createAuditRequestDTO.setBusinessId(taskInfo.getId());
        createAuditRequestDTO.setBusinessType(AuditTypeEnum.TASK_CREATE_AUDIT.getCode());
        createAuditRequestDTO.setTempCode(AuditTypeEnum.TASK_CREATE_AUDIT.getCode());
        createAuditRequestDTO.setInitiatorId(userId);
        createAuditRequestDTO.setCompanyId(taskInfo.getCompanyId());
        Long createAuditInstanceId = auditService.createAudit(createAuditRequestDTO);
        taskInfo.setCreateAuditInstanceId(createAuditInstanceId);
    }

    /**
     * 任务的创建审核初始化处理器
     *
     * @param taskInfo
     * @param userId
     */
    private void handleFinishAuditInit(TaskInfo taskInfo, Long userId) {
        CreateAuditRequestDTO createAuditRequestDTO = new CreateAuditRequestDTO();
        createAuditRequestDTO.setBusinessId(taskInfo.getId());
        createAuditRequestDTO.setBusinessType(AuditTypeEnum.TASK_COMPLETE_AUDIT.getCode());
        createAuditRequestDTO.setTempCode(AuditTypeEnum.TASK_COMPLETE_AUDIT.getCode());
        createAuditRequestDTO.setInitiatorId(userId);
        createAuditRequestDTO.setCompanyId(1L);
        createAuditRequestDTO.setCompanyId(taskInfo.getCompanyId());
        Long finishAuditInstanceId = auditService.createAudit(createAuditRequestDTO);
        taskInfo.setFinishAuditInstanceId(finishAuditInstanceId);
    }

    /**
     * 获取字典值，让导出的字典值显示中文名称。
     *
     * @param taskInfos
     */
    private void handleDictData(List<TaskInfo> taskInfos) {

        for (TaskInfo item : taskInfos) {
            item.setBelongTypeName(DictUtils.getDictLabel("task_belong_type", String.valueOf(item.getBelongType())));
            item.setTaskTypeName(DictUtils.getDictLabel("task_type", String.valueOf(item.getTaskType())));
            item.setTaskUnitName(DictUtils.getDictLabel("task_unit", String.valueOf(item.getBelongType())));
            item.setTaskStatusName(DictUtils.getDictLabel("task_status", String.valueOf(item.getTaskStatus())));
            item.setServiceConfirmStatusName(DictUtils.getDictLabel("task_service_confirm_status", item.getBelongType() + ""));
            item.setFinishStatusName(DictUtils.getDictLabel("task_finish_status", item.getBelongType() + ""));
        }
    }


    @Override
    public TaskAuditInfoVO getTaskCreateAuditInfo(Long taskId) {
        TaskAuditInfoVO vo = new TaskAuditInfoVO();

        // 1) 审核任务信息
        AuditTaskInfoVO audit = taskInfoMapper.selectAuditTaskInfoVO(taskId);
        if (audit == null) {
            // 你也可以选择 throw 自定义异常
            return vo;
        }
        handleDictBytTaskCreateAuditInfo(audit);
        vo.setAuditTaskInfoVO(audit);

        // 2) 医生信息（注意：doctorId 字段类型要与你表一致）
        // 如果 audit.getDoctorId() 其实是 String，就改成 String doctorId
        Long doctorId = audit.getDoctorId();
        if (doctorId != null) {
            Doctor doctor = doctorService.selectDoctorById(doctorId);
            if (doctor != null) {
                DocterVO docterVO = BeanCopyUtils.copy(doctor, DocterVO.class);
                vo.setDocterVO(docterVO);
            }
        }

        // 3) 项目信息
        Long projectId = audit.getProjectId();
        if (projectId != null) {
            Project project = projectService.selectProjectById(projectId);
            if (project != null) {
                ProjectVO projectVO = BeanCopyUtils.copy(project, ProjectVO.class);
                vo.setProjectVO(projectVO);
            }
        }

        // 4) 业务员信息（你原来缺了 set 回 vo）
        Long companyUserId = audit.getCompanyUserId();
        if (companyUserId != null) {
            CompanyUser companyUser = companyUserService.selectCompanyUserById(companyUserId);
            if (companyUser != null) {
                CompanyUserVO companyUserVO = BeanCopyUtils.copy(companyUser, CompanyUserVO.class);

                Long companyId = companyUserVO.getCompanyId();
                if (companyId != null) {
                    Company company = companyService.selectCompanyById(companyId);
                    if (company != null) {
                        companyUserVO.setCompanyName(company.getCompanyName());
                    }
                }

                vo.setCompanyUserVO(companyUserVO);
            }
        }

        // 获取审核流程
        Long createAuditInstanceId = audit.getCreateAuditInstanceId();
        List<AuditFlow> auditFlows = auditService.getAuditFlows(createAuditInstanceId);
        List<AuditFlowVO> auditFlowVOS = BeanCopyUtils.copyList(auditFlows, AuditFlowVO.class);
        for (AuditFlowVO auditFlowVO : auditFlowVOS) {

            // 1) 审核状态中文
            auditFlowVO.setStatusName(AuditStatus.fromCode(auditFlowVO.getStatus()).getDesc());

            // 2) 统一算出“要展示的审核人ID”
            //    优先 auditUserId，其次从 auditUserIds 取第一个
            Long displayUserId = auditFlowVO.getAuditUserId();
            if (displayUserId == null) {
                displayUserId = AuditFlowUtils.parseFirstIdFromAuditUserIds(auditFlowVO.getAuditUserIds());
            }

            if (displayUserId == null) {
                auditFlowVO.setAuditUserName("-");
                continue;
            }

            // 3) 统一算出“审核人类型”
            //    VO 约定：0 销售(company_user) / 1 系统用户(sys_user)
            Integer typeCode = auditFlowVO.getAuditUserType();

            // ✅ 如果类型为空：给一个策略
            // - step=0 申请人：你们大概率是系统用户发起 => 默认 1
            // - 其他节点：类型为空就走“先查 sys_user 再查 company_user”兜底
            boolean isStep0 = auditFlowVO.getStepNumber() != null && auditFlowVO.getStepNumber() == 0;

            if (typeCode == null) {
                if (isStep0) {
                    typeCode = 1; // ✅ 申请人默认系统用户（按你们约定）
                } else {
                    // 非 step=0：类型缺失，走兜底双查（下面会处理）
                    typeCode = -1;
                }
            }

            // 4) 根据类型查用户名
            String name = "-";

            if (typeCode == 1) {
                // 系统用户
                SysUser sysUser = sysUserService.selectUserById(displayUserId);
                if (sysUser != null) name = sysUser.getUserName();

            } else if (typeCode == 0) {
                // 销售/公司用户
                CompanyUser cu = companyUserService.selectCompanyUserById(displayUserId);
                if (cu != null) name = cu.getUserName();

            } else {
                // typeCode == -1：兜底双查（先 sys_user 后 company_user）
                SysUser sysUser = sysUserService.selectUserById(displayUserId);
                if (sysUser != null) {
                    name = sysUser.getUserName();
                    // 顺便把类型补回去（可选）
                    auditFlowVO.setAuditUserType(1);
                } else {
                    CompanyUser cu = companyUserService.selectCompanyUserById(displayUserId);
                    if (cu != null) {
                        name = cu.getUserName();
                        auditFlowVO.setAuditUserType(0);
                    }
                }
            }

            auditFlowVO.setAuditUserName(name);
        }


        vo.setAuditFlowVO(auditFlowVOS);
        return vo;
    }


    @Override
    public TaskAuditInfoVO getTaskFinishAuditInfo(Long taskId) {
        TaskAuditInfoVO vo = new TaskAuditInfoVO();

        // 1) 审核任务信息
        AuditTaskInfoVO audit = taskInfoMapper.selectAuditTaskInfoVO(taskId);
        if (audit == null) {
            // 你也可以选择 throw 自定义异常
            return vo;
        }


        //交付物
        TaskDeliveryInfo taskDeliveryInfo = new TaskDeliveryInfo();
        taskDeliveryInfo.setTaskId(taskId);
        List<TaskDeliveryInfo> taskDeliveryInfos = taskDeliveryInfoService.selectTaskDeliveryInfoList(taskDeliveryInfo);
        if (Objects.nonNull(taskDeliveryInfos) && !taskDeliveryInfos.isEmpty()) {
            TaskDeliveryInfo taskDeliveryInfo1 = taskDeliveryInfos.get(0);
            String projectLink = taskDeliveryInfo1.getProjectLink();
            Integer taskType = audit.getTaskType();
            if (taskType.equals(TaskTypeEnum.ARTICLE.getCode())) {
                CtArticle ctArticle = ctArticleService.selectCtArticleById(Long.valueOf(projectLink));
                vo.setCtArticle(ctArticle);
            }
            if (taskType.equals(TaskTypeEnum.SHORT_VIDEO.getCode())) {
                CtShortVideo ctShortVideo = ctShortVideoService.selectCtShortVideoById(Long.valueOf(projectLink));
                vo.setCtShortVideo(ctShortVideo);
            }
            if (taskType.equals(TaskTypeEnum.LONG_VIDEO.getCode())) {
                CtLongVideo ctLongVideo = ctLongVideoService.selectCtLongVideoById(Long.valueOf(projectLink));
                vo.setCtLongVideo(ctLongVideo);

            }

        }
        handleDictBytTaskCreateAuditInfo(audit);
        vo.setAuditTaskInfoVO(audit);

        // 2) 医生信息（注意：doctorId 字段类型要与你表一致）
        // 如果 audit.getDoctorId() 其实是 String，就改成 String doctorId
        Long doctorId = audit.getDoctorId();
        if (doctorId != null) {
            Doctor doctor = doctorService.selectDoctorById(doctorId);
            if (doctor != null) {
                DocterVO docterVO = BeanCopyUtils.copy(doctor, DocterVO.class);
                vo.setDocterVO(docterVO);
            }
        }

        // 3) 项目信息
        Long projectId = audit.getProjectId();
        if (projectId != null) {
            Project project = projectService.selectProjectById(projectId);
            if (project != null) {
                ProjectVO projectVO = BeanCopyUtils.copy(project, ProjectVO.class);
                vo.setProjectVO(projectVO);
            }
        }

        // 4) 业务员信息（你原来缺了 set 回 vo）
        Long companyUserId = audit.getCompanyUserId();
        if (companyUserId != null) {
            CompanyUser companyUser = companyUserService.selectCompanyUserById(companyUserId);
            if (companyUser != null) {
                CompanyUserVO companyUserVO = BeanCopyUtils.copy(companyUser, CompanyUserVO.class);

                Long companyId = companyUserVO.getCompanyId();
                if (companyId != null) {
                    Company company = companyService.selectCompanyById(companyId);
                    if (company != null) {
                        companyUserVO.setCompanyName(company.getCompanyName());
                    }
                }

                vo.setCompanyUserVO(companyUserVO);
            }
        }

        // 获取审核流程
        Long finishAuditInstanceId = audit.getFinishAuditInstanceId();
        List<AuditFlow> auditFlows = auditService.getAuditFlows(finishAuditInstanceId);
        List<AuditFlowVO> auditFlowVOS = BeanCopyUtils.copyList(auditFlows, AuditFlowVO.class);

        for (AuditFlowVO auditFlowVO : auditFlowVOS) {

            // 1) 审核状态中文
            auditFlowVO.setStatusName(AuditStatus.fromCode(auditFlowVO.getStatus()).getDesc());

            // 2) 统一算出“要展示的审核人ID”
            //    优先 auditUserId，其次从 auditUserIds 取第一个
            Long displayUserId = auditFlowVO.getAuditUserId();
            if (displayUserId == null) {
                displayUserId = AuditFlowUtils.parseFirstIdFromAuditUserIds(auditFlowVO.getAuditUserIds());
            }

            if (displayUserId == null) {
                auditFlowVO.setAuditUserName("-");
                continue;
            }

            // 3) 统一算出“审核人类型”
            //    VO 约定：0 销售(company_user) / 1 系统用户(sys_user)
            Integer typeCode = auditFlowVO.getAuditUserType();

            // ✅ 如果类型为空：给一个策略
            // - step=0 申请人：你们大概率是系统用户发起 => 默认 1
            // - 其他节点：类型为空就走“先查 sys_user 再查 company_user”兜底
            boolean isStep0 = auditFlowVO.getStepNumber() != null && auditFlowVO.getStepNumber() == 0;

            if (typeCode == null) {
                if (isStep0) {
                    typeCode = 1; // ✅ 申请人默认系统用户（按你们约定）
                } else {
                    // 非 step=0：类型缺失，走兜底双查（下面会处理）
                    typeCode = -1;
                }
            }

            // 4) 根据类型查用户名
            String name = "-";

            if (typeCode == 1) {
                // 系统用户
                SysUser sysUser = sysUserService.selectUserById(displayUserId);
                if (sysUser != null) name = sysUser.getUserName();

            } else if (typeCode == 0) {
                // 销售/公司用户
                CompanyUser cu = companyUserService.selectCompanyUserById(displayUserId);
                if (cu != null) name = cu.getUserName();

            } else {
                // typeCode == -1：兜底双查（先 sys_user 后 company_user）
                SysUser sysUser = sysUserService.selectUserById(displayUserId);
                if (sysUser != null) {
                    name = sysUser.getUserName();
                    // 顺便把类型补回去（可选）
                    auditFlowVO.setAuditUserType(1);
                } else {
                    CompanyUser cu = companyUserService.selectCompanyUserById(displayUserId);
                    if (cu != null) {
                        name = cu.getUserName();
                        auditFlowVO.setAuditUserType(0);
                    }
                }
            }

            auditFlowVO.setAuditUserName(name);
        }

        vo.setAuditFlowVO(auditFlowVOS);

        //材料
        List<TaskMaterialInfo> taskMaterialInfos = taskMaterialInfoService.selectTaskMaterialInfoByTaskId(taskId);
        if (Objects.isNull(taskMaterialInfos)) {
            taskMaterialInfos = new ArrayList<>();
        }
        vo.setTaskMaterialInfos(taskMaterialInfos);
        return vo;
    }

    /**
     * 处理创建审核中的字典值
     *
     * @param auditTaskInfoVO
     */
    private void handleDictBytTaskCreateAuditInfo(AuditTaskInfoVO auditTaskInfoVO) {
        List<SysDictData> taskBelongTypeList = sysDictTypeService.selectDictDataByType("task_belong_type");
        Map<String, String> belongTypeMap = taskBelongTypeList.stream()
                .collect(Collectors.toMap(
                        SysDictData::getDictValue,
                        SysDictData::getDictLabel,
                        (v1, v2) -> v1
                ));

        List<SysDictData> taskUnit = sysDictTypeService.selectDictDataByType("task_unit");
        Map<String, String> taskUnitMap = taskUnit.stream()
                .collect(Collectors.toMap(
                        SysDictData::getDictValue,
                        SysDictData::getDictLabel,
                        (v1, v2) -> v1
                ));

        auditTaskInfoVO.setBelongTypeName(Objects.nonNull(auditTaskInfoVO.getBelongType()) ? belongTypeMap.get(auditTaskInfoVO.getBelongType() + "") : "");
        auditTaskInfoVO.setTaskUnitName(Objects.nonNull(auditTaskInfoVO.getTaskUnit()) ? taskUnitMap.get(auditTaskInfoVO.getTaskUnit() + "") : "");

        if (StringUtils.isNotNull(auditTaskInfoVO.getCompanyUserId())) {
            String companyUserNameById = CompanyUserCacheService.getCompanyUserNameById(auditTaskInfoVO.getCompanyUserId());
            if (StringUtils.isNotNull(companyUserNameById)) {
                auditTaskInfoVO.setCompanyUserName(companyUserNameById);
            }
        }
    }

    @Override
    public int updateSpotCheck(TaskSpotCheckUpdateReqVO req) {
        // 业务校验：isSpotCheck=1 时，人/时间必须有
        if (Integer.valueOf(1).equals(req.getIsSpotCheck())) {
            if (req.getSpotCheckUserId() == null) {
                throw new BusinessException("抽检人不能为空");
            }
            if (req.getSpotCheckTime() == null) {
                throw new BusinessException("抽检时间不能为空");
            }
        }

        // isSpotCheck=0 -> 清空抽检人/时间
        if (Integer.valueOf(0).equals(req.getIsSpotCheck())) {
            req.setSpotCheckUserId(null);
            req.setSpotCheckTime(null);
        }
        return taskInfoMapper.updateSpotCheck(req);

    }

    @Override
    public List<TaskInfo> selectPendingTasksForGen(Long companyId, Long departmentId, List<Long> taskTypeIds) {
        return taskInfoMapper.selectPendingTasksForGen(companyId, departmentId, taskTypeIds);
    }

    @Autowired
    private ICompanyDeptService companyDeptService;

    @Override
    public List<TaskStatsDTO> getTaskCompleteStats(GetTaskCompleteStatsVO param) {
        List<TaskStatsDTO> taskCompleteStats = taskInfoMapper.getTaskCompleteStats(param);
        for (TaskStatsDTO task : taskCompleteStats) {
            if (ObjectUtils.isNotNull(task.getDeptId())) {
                CompanyDept companyDept = companyDeptService.selectCompanyDeptById(task.getDeptId());
                if (ObjectUtils.isNotNull(companyDept)) {
                    task.setDeptName(String.format("%d_%s", companyDept.getDeptId(), companyDept.getDeptName()));
                }
            }

            if (ObjectUtils.isNotNull(task.getDoctorId())) {
                Doctor doctor = doctorService.selectDoctorById(Long.valueOf(task.getDoctorId()));
                if (ObjectUtils.isNotNull(doctor)) {
                    task.setDoctorName(String.format("%d_%s", doctor.getId(), doctor.getDoctorName()));
                }
            }

            if (ObjectUtils.isNotNull(task.getCompanyUserId())) {
                CompanyUser companyUser = companyUserService.selectCompanyUserById(Long.valueOf(task.getCompanyUserId()));
                if (ObjectUtils.isNotNull(companyUser)) {
                    task.setCompanyUserName(String.format("%d_%s", companyUser.getUserId(), companyUser.getUserName()));
                }
            }
        }
        return taskCompleteStats;
    }

    @Override
    public List<TaskStatsDTO> getTaskCreateStats(GetTaskCompleteStatsVO param) {
        List<TaskStatsDTO> taskCreateStats = taskInfoMapper.getTaskCreateStats(param);
        for (TaskStatsDTO task : taskCreateStats) {
            if (ObjectUtils.isNotNull(task.getDeptId())) {
                CompanyDept companyDept = companyDeptService.selectCompanyDeptById(task.getDeptId());
                if (ObjectUtils.isNotNull(companyDept)) {
                    task.setDeptName(String.format("%d_%s", companyDept.getDeptId(), companyDept.getDeptName()));
                }
            }

            if (ObjectUtils.isNotNull(task.getDoctorId())) {
                Doctor doctor = doctorService.selectDoctorByDoctorId(task.getDoctorId());
                if (ObjectUtils.isNotNull(doctor)) {
                    task.setDoctorName(String.format("%d_%s", doctor.getId(), doctor.getDoctorName()));
                }
            }

            if (ObjectUtils.isNotNull(task.getCompanyUserId())) {
                CompanyUser companyUser = companyUserService.selectCompanyUserById(Long.valueOf(task.getCompanyUserId()));
                if (ObjectUtils.isNotNull(companyUser)) {
                    task.setCompanyUserName(String.format("%d_%s", companyUser.getUserId(), companyUser.getUserName()));
                }
            }
        }
        return taskCreateStats;
    }

    @Override
    public BigDecimal getTaskCompleteStatsCount(GetTaskCompleteStatsVO param) {
        return taskInfoMapper.getTaskCompleteStatsCount(param);
    }

    @Override
    public BigDecimal getTaskCreateStatsCount(GetTaskCompleteStatsVO param) {
        return taskInfoMapper.getTaskCreateStatsCount(param);
    }


    @Override
    public List<TaskInfo> selectTaskInfoByIds(List<Long> taskIds) {
        if (taskIds == null || taskIds.isEmpty()) {
            return java.util.Collections.emptyList();
        }
        return taskInfoMapper.selectTaskInfoByIds(taskIds);
    }

    @Override
    public TaskDeliveryDto getTaskDelivery(Long taskId) {
        TaskDeliveryDto taskDeliveryDto = taskInfoMapper.getTaskDelivery(taskId);
        return taskDeliveryDto;
    }

    @Transactional
    @Override
    public Long copyCreateTask(Long taskId) {
        // 校验原任务是否存在
        TaskInfo originalTask = taskInfoMapper.selectTaskInfoById(taskId);
        if (originalTask == null) {
            throw new BusinessException("原任务不存在，taskId=" + taskId);
        }

        // 获取当前操作人信息
        PlatEnum platEnum = LoginContextManager.getNowPlatEnum();
        Long operatorUserId = null;
        Integer caUserType = null;

        // 优先尝试从当前平台获取用户信息
        if (PlatEnum.ADMIN.equals(platEnum)) {
            operatorUserId = LoginContextManager.getCurrentUserId();
            caUserType = CreateAuditUserTypeEnum.SYSTEM_USER.getCode();
        } else if (PlatEnum.COMPANY.equals(platEnum) || PlatEnum.COMPANY_APP.equals(platEnum)) {
            operatorUserId = LoginContextManager.getCurrentCompanyUserId();
            caUserType = CreateAuditUserTypeEnum.COMPANY_USER.getCode();
        }


        // 复制任务数据
        TaskInfo newTask = new TaskInfo();

        // 复制基础信息
        newTask.setDeptId(originalTask.getDeptId());                      // 归属部门ID
        newTask.setProjectId(originalTask.getProjectId());                // 归属项目ID
        newTask.setCostShareId(originalTask.getCostShareId());            // 费用分摊ID
        newTask.setCompanyId(originalTask.getCompanyId());                // 公司ID
        newTask.setCompanyUserId(originalTask.getCompanyUserId());        // 业务员ID
        newTask.setDoctorId(originalTask.getDoctorId());                  // 讲者ID

        // 复制任务配置
        newTask.setTaskType(originalTask.getTaskType());                  // 任务类型
        newTask.setTaskIntegral(originalTask.getTaskIntegral());          // 任务积分
        newTask.setTaskCount(originalTask.getTaskCount());                // 任务数量
        newTask.setTaskUnit(originalTask.getTaskUnit());                  // 任务单位
        newTask.setBelongType(originalTask.getBelongType());              // 归属类型
        newTask.setProductId(originalTask.getProductId());                // 归属产品ID

        // 复制时间计划（可选：根据业务需求决定是否复制）
        newTask.setPlanStartTime(originalTask.getPlanStartTime());        // 计划开始时间
        newTask.setPlanEndTime(originalTask.getPlanEndTime());            // 计划结束时间

        // 复制备注信息
        newTask.setRemark(originalTask.getRemark());                      // 备注

        // 初始化新任务状态
        newTask.setTaskStatus(TaskStatusEnum.UN_FINISHED.getCode());      // 任务状态：未完成
        newTask.setCreateAuditStatus(0);                                  // 创建审核状态：待审核
        newTask.setFinishAuditStatus(TaskFinishAuditStatus.NOCREATE.getCode()); // 完成审核状态：未创建
        newTask.setServiceConfirmStatus(ServiceConfirmStatusEnum.PENDING.getCode()); // 服务确认单状态：待确认
        newTask.setFinishStatus(0L);                                      // 完结状态：初始化
        newTask.setAuditStatus(0L);                                       // 审核状态：初始化
        newTask.setIsSpotCheck(0L);                                       // 是否抽检：否
        newTask.setIsSupplementLive(0L);                                  // 是否申请补充直播间任务：否
        newTask.setDeleted(0L);                                           // 删除标识：未删除

        // 设置操作人信息
        newTask.setCreateTime(DateUtils.getNowDate());                    // 创建时间
        newTask.setCaUserType(caUserType);                                // 创建审核人类型
        newTask.setApplyTime(DateUtils.getNowDate());                     // 任务申请时间

        // 生成临时任务编号
        newTask.setTaskNo("TMP_" + UUID.randomUUID().toString().replace("-", ""));

        // 生成任务名称
        String doctorName = doctorMapper.selectDoctorNameById(newTask.getDoctorId());
        String taskTypeStr = DictUtils.getDictLabel("task_type", String.valueOf(newTask.getTaskType()));
        newTask.setTaskName(String.format("%s医生的%s", doctorName, taskTypeStr));

        // 插入新任务
        taskInfoMapper.insertTaskInfo(newTask);

        // 生成正式任务编号
        String taskNo = "CRW" + String.format("%014d", newTask.getId());
        newTask.setTaskNo(taskNo);

        // 初始化审核流程
        handleCreatAuditInit(newTask, operatorUserId);
        handleFinishAuditInit(newTask, operatorUserId);

        // 更新任务信息
        taskInfoMapper.updateTaskInfo(newTask);

        return newTask.getId();
    }


}
