package com.fs.audit.service.impl;

import com.fs.audit.domain.Audit;
import com.fs.audit.domain.AuditFlow;
import com.fs.audit.enums.AuditStatus;
import com.fs.audit.enums.AuditTypeEnum;
import com.fs.audit.service.AuditService;
import com.fs.audit.service.IAuditDetailService;
import com.fs.audit.utils.AuditFlowUtils;
import com.fs.audit.vo.AuditDetailVO;
import com.fs.audit.vo.AuditFlowDetailVO;
import com.fs.common.BeanCopyUtils;
import com.fs.common.core.domain.entity.SysUser;
import com.fs.company.domain.CompanyUser;
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.domain.DoctorLevelApply;
import com.fs.doctor.domain.WithdrawRecords;
import com.fs.doctor.service.IDoctorLevelApplyService;
import com.fs.doctor.service.IDoctorService;
import com.fs.doctor.service.IWithdrawRecordsService;
import com.fs.system.service.ISysUserService;
import com.fs.task.service.ITaskInfoService;
import com.fs.task.vo.audit_Info.TaskAuditInfoVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 审核详情服务实现
 * 根据不同业务类型动态返回对应的业务数据
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AuditDetailServiceImpl implements IAuditDetailService {

    private final AuditService auditService;
    private final ISysUserService sysUserService;
    private final ICompanyUserService companyUserService;

    // 讲者相关
    private final IDoctorService doctorService;
    private final IDoctorLevelApplyService doctorLevelApplyService;
    private final IWithdrawRecordsService withdrawRecordsService;

    // 任务相关
    private final ITaskInfoService taskInfoService;

    // 交付物相关
    private final ICtArticleService ctArticleService;
    private final ICtShortVideoService ctShortVideoService;
    private final ICtLongVideoService ctLongVideoService;

    @Override
    public AuditDetailVO<?> getAuditDetail(Long auditId) {
        // 查询审核实例
        Audit audit = auditService.getAudit(auditId);
        if (audit == null) {
            throw new IllegalArgumentException("审核实例不存在: " + auditId);
        }

        // 查询审核流程并填充审核人信息
        List<AuditFlow> auditFlows = auditService.getAuditFlows(auditId);
        List<AuditFlowDetailVO> flowDetails = buildAuditFlowDetails(auditFlows);

        //  根据业务类型查询业务数据
        Object businessData = getBusinessData(audit);

        AuditDetailVO<Object> result = new AuditDetailVO<>();
        result.setAudit(audit);
        result.setAuditFlows(flowDetails);
        result.setBusinessData(businessData);
        result.setBusinessTypeDesc(getBusinessTypeDesc(audit.getAuditType()));

        return result;
    }

    /**
     * 构建审核流程详情列表
     */
    private List<AuditFlowDetailVO> buildAuditFlowDetails(List<AuditFlow> auditFlows) {
        return auditFlows.stream().map(flow -> {
            AuditFlowDetailVO detailVO = BeanCopyUtils.copy(flow, AuditFlowDetailVO.class);

            // 设置审核状态名称
            if (flow.getStatus() != null) {
                AuditStatus status = AuditStatus.fromCode(flow.getStatus());
                if (status != null) {
                    detailVO.setStatusName(status.getDesc());
                }
            }

            // 确定要展示的审核人ID（优先 auditUserId，其次从 auditUserIds 取第一个）
            Long displayUserId = flow.getAuditUserId();
            if (displayUserId == null) {
                displayUserId = AuditFlowUtils.parseFirstIdFromAuditUserIds(flow.getAuditUserIds());
            }

            if (displayUserId == null) {
                detailVO.setAuditUserName("-");
                return detailVO;
            }

            // 根据审核人类型查询姓名
            Integer typeCode = flow.getAuditUserType();
            String userName = getUserName(displayUserId, typeCode, flow.getStepNumber());
            detailVO.setAuditUserName(userName);

            return detailVO;
        }).collect(Collectors.toList());
    }

    /**
     * 根据用户ID和类型获取用户名
     */
    private String getUserName(Long userId, Integer typeCode, Integer stepNumber) {
        // 如果类型为空，step=0 默认为系统用户，其他情况兜底双查
        boolean isStep0 = stepNumber != null && stepNumber == 0;
        if (typeCode == null) {
            typeCode = isStep0 ? 1 : -1;
        }

        String userName = "-";

        if (typeCode == 1) {
            // 系统用户
            SysUser sysUser = sysUserService.selectUserById(userId);
            if (sysUser != null) {
                userName = sysUser.getUserName();
            }
        } else if (typeCode == 0) {
            // 公司用户
            CompanyUser companyUser = companyUserService.selectCompanyUserById(userId);
            if (companyUser != null) {
                userName = companyUser.getUserName();
            }
        } else {
            // typeCode == -1: 兜底双查（先 sys_user 后 company_user）
            SysUser sysUser = sysUserService.selectUserById(userId);
            if (sysUser != null) {
                userName = sysUser.getUserName();
            } else {
                CompanyUser companyUser = companyUserService.selectCompanyUserById(userId);
                if (companyUser != null) {
                    userName = companyUser.getUserName();
                }
            }
        }

        return userName;
    }

    /**
     * 根据业务类型获取业务数据
     */
    private Object getBusinessData(Audit audit) {
        String auditType = audit.getAuditType();
        Long businessId = audit.getBusinessId();

        if (businessId == null) {
            return null;
        }

        // 根据审核类型枚举判断
        AuditTypeEnum typeEnum = AuditTypeEnum.getById(auditType);
        if (typeEnum == null) {
            log.warn("未知的审核类型: {}", auditType);
            return null;
        }

        switch (typeEnum) {
            case DOCTOR_AUDIT:
                // 讲者审核：返回 Doctor 信息
                return doctorService.selectDoctorById(businessId);

            case GRADE_AUDIT:
                // 定级审核：返回 DoctorLevelApply 信息
                return doctorLevelApplyService.getDoctorApplyDetailInfoById(businessId);

            case WITHDRAW_AUDIT:
                // 提现审核：返回 WithdrawRecords 信息
                return withdrawRecordsService.selectWithdrawRecordsByWithdrawId(businessId);

            case TASK_CREATE_AUDIT:
                // 创建任务审核：返回 TaskAuditInfoVO
                return taskInfoService.getTaskCreateAuditInfo(businessId);

            case TASK_COMPLETE_AUDIT:
                // 完成任务审核：返回 TaskAuditInfoVO
                return taskInfoService.getTaskFinishAuditInfo(businessId);

            default:
                log.warn("未处理的审核类型: {}", typeEnum);
                return null;
        }
    }

    /**
     * 获取业务类型描述
     */
    private String getBusinessTypeDesc(String auditType) {
        AuditTypeEnum typeEnum = AuditTypeEnum.getById(auditType);
        return typeEnum != null ? typeEnum.getDesc() : auditType;
    }
}
