package com.fs.live.service.impl;

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

import com.fs.audit.dto.CreateAuditRequestDTO;
import com.fs.audit.enums.AuditTypeEnum;
import com.fs.audit.service.AuditService;
import com.fs.common.config.LoginContextManager;
import com.fs.common.enums.LiveBroadcastEnum;
import com.fs.common.enums.TaskLabelEnum;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.DictUtils;
import com.fs.doctor.domain.Doctor;
import com.fs.doctor.mapper.DoctorMapper;
import com.fs.live.dto.LiveBroadcastDto;
import com.fs.live.dto.TaskLiveDto;
import com.fs.task.domain.TaskInfo;
import com.fs.task.enums.TaskFinishAuditStatus;
import com.fs.task.enums.TaskFinishStatusEnum;
import com.fs.task.enums.TaskStatusEnum;
import com.fs.task.mapper.TaskInfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fs.live.mapper.LiveBroadcastMapper;
import com.fs.live.domain.LiveBroadcast;
import com.fs.live.service.ILiveBroadcastService;

/**
 * 直播列表Service业务层处理
 * 
 * @author fs
 * @date 2026-03-10
 */
@Service
public class LiveBroadcastServiceImpl implements ILiveBroadcastService 
{
    @Autowired
    private LiveBroadcastMapper liveBroadcastMapper;
    @Autowired
    private DoctorMapper doctorMapper;
    @Autowired
    private AuditService auditService;
    @Autowired
    private TaskInfoMapper taskInfoMapper;

    private static final String LIVE_PUSHER_BASE_URL = "http://132.232.83.221:8083/#/live-pusher?doctorId=";


    /**
     * 查询直播列表
     * 
     * @param id 直播列表主键
     * @return 直播列表
     */
    @Override
    public LiveBroadcast selectLiveBroadcastById(Long id)
    {
        return liveBroadcastMapper.selectLiveBroadcastById(id);
    }

    /**
     * 查询直播列表列表
     * 
     * @param liveBroadcast 直播列表
     * @return 直播列表
     */
    @Override
    public List<LiveBroadcast> selectLiveBroadcastList(LiveBroadcast liveBroadcast)
    {
        List<LiveBroadcast> liveBroadcasts = liveBroadcastMapper.selectLiveBroadcastList(liveBroadcast);
        List<LiveBroadcast> newLive = new ArrayList<>();

        liveBroadcasts.forEach(item -> {
            String targetId = TaskLabelEnum.live + "-" + item.getId();
            TaskInfo taskInfo = taskInfoMapper.getTaskByTargetId(targetId);
            if (taskInfo != null){
                // 获取枚举值
                TaskFinishStatusEnum statusEnum = TaskFinishStatusEnum.fromCode(taskInfo.getFinishStatus().intValue());
                taskInfo.setFinishStatusName(statusEnum.getDesc());
                TaskLiveDto taskLiveDto = new TaskLiveDto();
                BeanUtils.copyProperties(taskInfo, taskLiveDto);
                item.setTaskLiveDto(taskLiveDto);
                newLive.add(item);
            }

        });
        return newLive.stream()
                .filter(item -> {
                    // 可以根据 TaskLiveDto 中的属性进行过滤
                    if (liveBroadcast.getFinishStatus() != null) {
                        return item.getTaskLiveDto().getFinishStatus().equals(liveBroadcast.getFinishStatus());
                    }
                    return true;
                })
                .collect(Collectors.toList());
    }

    @Override
    public List<LiveBroadcast> selectliveList(LiveBroadcast liveBroadcast) {
        List<LiveBroadcast> liveBroadcasts = liveBroadcastMapper.selectLiveBroadcastList(liveBroadcast);
        return liveBroadcasts;
    }

    /**
     * 新增直播列表
     * 
     * @param liveBroadcast 直播列表
     * @return 结果
     */
    @Override
    public int insertLiveBroadcast(LiveBroadcast liveBroadcast)
    {
        liveBroadcast.setCreateTime(DateUtils.getNowDate());
        Doctor doctor = doctorMapper.selectDoctorById(liveBroadcast.getDoctorId());
        liveBroadcast.setDoctorId(doctor.getId());
        liveBroadcast.setDoctorTitle(doctor.getJobTitle());
        liveBroadcast.setDepartment(doctor.getDepartment());
        liveBroadcast.setDoctorName(doctor.getDoctorName());
        liveBroadcast.setLiveUrl(LIVE_PUSHER_BASE_URL + doctor.getDoctorId());
        liveBroadcast.setHospitalName(doctor.getInstitution());
        liveBroadcast.setStatus(LiveBroadcastEnum.WAIT_START.getCode());
        Long currentCompanyId = LoginContextManager.getCurrentCompanyId();
        liveBroadcast.setCompanyId(currentCompanyId);

        return liveBroadcastMapper.insertLiveBroadcast(liveBroadcast);
    }

    /**
     * 修改直播列表
     * 
     * @param liveBroadcast 直播列表
     * @return 结果
     */
    @Override
    public int updateLiveBroadcast(LiveBroadcast liveBroadcast)
    {
        liveBroadcast.setUpdateTime(DateUtils.getNowDate());
        return liveBroadcastMapper.updateLiveBroadcast(liveBroadcast);
    }

    /**
     * 批量删除直播列表
     * 
     * @param ids 需要删除的直播列表主键
     * @return 结果
     */
    @Override
    public int deleteLiveBroadcastByIds(Long[] ids)
    {
        return liveBroadcastMapper.deleteLiveBroadcastByIds(ids);
    }

    /**
     * 删除直播列表信息
     * 
     * @param id 直播列表主键
     * @return 结果
     */
    @Override
    public int deleteLiveBroadcastById(Long id)
    {
        return liveBroadcastMapper.deleteLiveBroadcastById(id);
    }

    @Override
    public void closeLive(LiveBroadcastDto liveBroadcastDto) {
        LiveBroadcast liveBroadcast = new LiveBroadcast();
        liveBroadcast.setActualEndTime(new Date());
        liveBroadcast.setId(liveBroadcastDto.getSysLiveId());
        liveBroadcast.setStatus(LiveBroadcastEnum.END_START.getCode());
        liveBroadcastMapper.updateLiveBroadcast(liveBroadcast);

        String targetId = TaskLabelEnum.live + "-" + liveBroadcastDto.getSysLiveId();
        TaskInfo entity = taskInfoMapper.getTaskByTargetId(targetId);
        entity.setFinishAuditStatus(TaskFinishAuditStatus.PENDING.getCode());
        entity.setAuditStatus(TaskStatusEnum.UN_FINISHED.getCode().longValue());

        // 提交完成任务审核流
        handleFinishAuditInit(entity, entity.getCompanyUserId());
        taskInfoMapper.updateTaskInfo(entity);
    }

    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(taskInfo.getCompanyId());
        createAuditRequestDTO.setCompanyId(taskInfo.getCompanyId());
        Long finishAuditInstanceId = auditService.createAudit(createAuditRequestDTO);
        taskInfo.setFinishAuditInstanceId(finishAuditInstanceId);
    }

    @Override
    public List<LiveBroadcast> selectLiveBroadcastBaseList(LiveBroadcast liveBroadcast) {
      return liveBroadcastMapper.selectLiveBroadcastList(liveBroadcast);
    }
}
