package cn.com.poc.human_resources.aggregate.impl;

import cn.com.gsst.dify_client.DifyChatClient;
import cn.com.gsst.dify_client.DifyClientFactory;
import cn.com.gsst.dify_client.callback.ChatStreamCallback;
import cn.com.gsst.dify_client.enums.FileTransferMethod;
import cn.com.gsst.dify_client.enums.FileType;
import cn.com.gsst.dify_client.enums.ResponseMode;
import cn.com.gsst.dify_client.event.MessageEndEvent;
import cn.com.gsst.dify_client.event.MessageEvent;
import cn.com.gsst.dify_client.exception.DifyApiException;
import cn.com.gsst.dify_client.model.chat.ChatMessage;
import cn.com.gsst.dify_client.model.chat.ChatMessageResponse;
import cn.com.gsst.dify_client.model.file.FileInfo;
import cn.com.poc.common.constant.CommonConstant;
import cn.com.poc.common.utils.DocumentLoad;
import cn.com.poc.common.utils.JsonUtils;
import cn.com.poc.common.utils.SSEUtil;
import cn.com.poc.common.utils.StringUtils;
import cn.com.poc.human_resources.aggregate.HumanResourceService;
import cn.com.poc.human_resources.convert.BizHumanResourceResumeConvert;
import cn.com.poc.human_resources.entity.BizHumanResourcePositionEntity;
import cn.com.poc.human_resources.entity.BizHumanResourceResumeEntity;
import cn.com.poc.human_resources.entity.HumanResourcePositionBaseInfo;
import cn.com.poc.human_resources.entity.position.BaseInfo;
import cn.com.poc.human_resources.entity.position.Job;
import cn.com.poc.human_resources.entity.position.Por;
import cn.com.poc.human_resources.entity.resume.Resume;
import cn.com.poc.human_resources.query.PositionListQueryCondition;
import cn.com.poc.human_resources.query.PositionListQueryItem;
import cn.com.poc.human_resources.service.BizHumanResourcePositionService;
import cn.com.poc.human_resources.service.BizHumanResourceResumeService;
import cn.com.poc.thirdparty.resource.demand.ai.entity.largemodel.LargeModelDemandResult;
import cn.com.yict.framemax.core.exception.BusinessException;
import cn.com.yict.framemax.data.model.PagingInfo;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author alex.yao
 * @date 2025/9/28
 */
@Service
public class HumanResourceServiceImpl implements HumanResourceService {

    private String DIFY_BASE_URL = "https://dify.gsstcloud.com/v1";

    @Resource
    private BizHumanResourcePositionService bizHumanResourcePositionService;

    @Resource
    private BizHumanResourceResumeService bizHumanResourceResumeService;

    @Override
    public Resume uploadResume(String fileURL, Long positionId, Long userId) throws Exception {
        BizHumanResourcePositionEntity bizHumanResourcePositionEntity = bizHumanResourcePositionService.get(positionId);

        Map<String, Object> inputs = new LinkedHashMap<>();
        inputs.put("position", JsonUtils.serialize(bizHumanResourcePositionEntity));

        List<FileInfo> files = new ArrayList<>();
        files.add(FileInfo.builder()
                .type(FileType.DOCUMENT)
                .transferMethod(FileTransferMethod.REMOTE_URL)
                .url(fileURL)
                .build());

        // 创建聊天客户端
        DifyChatClient chatClient = DifyClientFactory.createChatClient(DIFY_BASE_URL, "app-1MRun3ecfLOzFS96xcWYCOOX");

        // 创建聊天消息
        ChatMessage message = ChatMessage.builder()
                .query("run")
                .user(userId.toString())
                .files(files)
                .inputs(inputs)
                .responseMode(ResponseMode.BLOCKING)
                .build();

        // 发送消息并获取响应
        ChatMessageResponse response = chatClient.sendChatMessage(message);
        if (response == null || StringUtils.isBlank(response.getAnswer())) {
            throw new BusinessException("提取简历失败");
        }
        Resume resume = JsonUtils.deSerialize(response.getAnswer(), Resume.class);
        this.saveResume(userId, fileURL, positionId, resume);
        return resume;
    }

    @Override
    public void positionAssistant(String demand, String type, String fileInfos, String jobInformation, String question, String dialoguesId, Long userId) throws DifyApiException, IOException, InterruptedException {
        // 创建聊天客户端
        DifyChatClient chatClient = DifyClientFactory.createChatClient(DIFY_BASE_URL, "app-YmVPoXmTh7ejERFbip3ADCYN");
        Map<String, Object> inputs = new LinkedHashMap<>();
        inputs.put("type", type);
        if (StringUtils.isNotBlank(demand)) {
            inputs.put("demand", demand);
        }
        if (StringUtils.isNotBlank(jobInformation)) {
            inputs.put("jobInfomations", jobInformation);
        }
        if (StringUtils.isNotBlank(fileInfos)) {
            inputs.put("fileinfos", fileInfos);
        }
        // 创建聊天消息
        ChatMessage message = ChatMessage.builder()
                .query(StringUtils.isBlank(question) ? "run" : question)
                .user(userId.toString())
                .inputs(inputs)
                .conversationId(StringUtils.isNotBlank(dialoguesId) ? dialoguesId : StringUtils.EMPTY)
                .responseMode(ResponseMode.STREAMING)
                .build();

        CountDownLatch countDownLatch = new CountDownLatch(1);
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = servletRequestAttributes.getResponse();
        // 发送消息并获取响应
        chatClient.sendChatMessageStream(message, new ChatStreamCallback() {
            SSEUtil sseUtil = new SSEUtil(response);

            @Override
            public void onMessage(MessageEvent event) {
                try {
                    if (StringUtils.isNotEmpty(event.getAnswer())) {
                        LargeModelDemandResult largeModelDemandResult = new LargeModelDemandResult();
                        largeModelDemandResult.setCode("0");
                        largeModelDemandResult.setMessage(event.getAnswer());
                        sseUtil.send(JsonUtils.serialize(event.getAnswer()));
                    }
                } catch (IOException e) {
                    sseUtil.completeByError(e.getMessage());
                    throw new RuntimeException(e);
                }
            }

            @Override
            public void onMessageEnd(MessageEndEvent event) {
                try {
                    sseUtil.send("[DONE]");
                } catch (IOException e) {
                    sseUtil.completeByError(e.getMessage());
                    throw new RuntimeException(e);
                } finally {
                    sseUtil.complete();
                    countDownLatch.countDown();
                }
            }
        });
        countDownLatch.await(60, TimeUnit.SECONDS);
    }


    @Override
    public BizHumanResourcePositionEntity saveOrUpdatePosition(BaseInfo baseInfo, Job job, Por por, Long id, Long memberId) throws Exception {

        BizHumanResourcePositionEntity bizHumanResourcePositionEntity = new BizHumanResourcePositionEntity();
        bizHumanResourcePositionEntity.setId(id);
        bizHumanResourcePositionEntity.setJobTitle(baseInfo.getJobTitle());
        bizHumanResourcePositionEntity.setDepartment(baseInfo.getDepartment());
        bizHumanResourcePositionEntity.setWorkLocation(baseInfo.getWorkLocation());
        bizHumanResourcePositionEntity.setJobNature(baseInfo.getJobNature());
        bizHumanResourcePositionEntity.setNumberOfRecruits(baseInfo.getNumberOfRecruits());
        bizHumanResourcePositionEntity.setWorkExperience(baseInfo.getWorkExperience());
        bizHumanResourcePositionEntity.setEducationalRe(baseInfo.getEducationalRe());
        bizHumanResourcePositionEntity.setSalaryRange(baseInfo.getSalaryRange());

        bizHumanResourcePositionEntity.setJobRequirements(job.getJobRequirements());
        bizHumanResourcePositionEntity.setJobDuties(job.getJobDuties());

        bizHumanResourcePositionEntity.setEssential(CollectionUtils.isNotEmpty(por.getEssential()) ? JsonUtils.serialize(por.getEssential()) : null);
        bizHumanResourcePositionEntity.setBonusPoints(CollectionUtils.isNotEmpty(por.getBonusPoints()) ? JsonUtils.serialize(por.getBonusPoints()) : null);
        bizHumanResourcePositionEntity.setExclusion(CollectionUtils.isNotEmpty(por.getExclusion()) ? JsonUtils.serialize(por.getExclusion()) : null);

        bizHumanResourcePositionEntity.setMemberId(memberId);
        return id != null ? bizHumanResourcePositionService.update(bizHumanResourcePositionEntity) : bizHumanResourcePositionService.save(bizHumanResourcePositionEntity);
    }

    @Override
    public List<HumanResourcePositionBaseInfo> listPositions(Long userId, PagingInfo pagingInfo) throws Exception {
        PositionListQueryCondition condition = new PositionListQueryCondition();
        condition.setMemberId(userId);
        List<PositionListQueryItem> positionListQueryItems = bizHumanResourcePositionService.positionListQuery(condition, pagingInfo);
        List<HumanResourcePositionBaseInfo> result = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(positionListQueryItems)) {
            result = positionListQueryItems.stream().map(item -> {
                HumanResourcePositionBaseInfo baseInfo = new HumanResourcePositionBaseInfo();
                baseInfo.setId(item.getId());
                baseInfo.setJobTitle(item.getJobTitle());
                baseInfo.setWorkLocation(item.getWorkLocation());
                baseInfo.setJobNature(item.getJobNature());
                baseInfo.setWorkExperience(item.getWorkExperience());
                baseInfo.setResumeCount(item.getResumeCount());
                return baseInfo;
            }).collect(Collectors.toList());
        }
        return result;
    }

    @Override
    public BizHumanResourcePositionEntity getPositionDetail(Long userId, Long positionId) throws Exception {
        BizHumanResourcePositionEntity bizHumanResourcePositionEntity = new BizHumanResourcePositionEntity();
        bizHumanResourcePositionEntity.setId(positionId);
        bizHumanResourcePositionEntity.setMemberId(userId);
        bizHumanResourcePositionEntity.setIsDeleted(CommonConstant.IsDeleted.N);
        List<BizHumanResourcePositionEntity> entities = bizHumanResourcePositionService.findByExample(bizHumanResourcePositionEntity, null);
        if (CollectionUtils.isEmpty(entities)) {
            return null;
        }
        return entities.get(0);
    }

    @Override
    public void deletePositions(Long userId, Long... positionIds) throws Exception {
        if (userId == null) {
            throw new BusinessException("用户未登录");
        }
        if (positionIds == null || positionIds.length == 0) {
            return;
        }
        String lock = "deletePositions" + userId;
        synchronized (lock.intern()) {
            for (Long positionId : positionIds) {
                bizHumanResourcePositionService.deletedById(positionId);
            }
        }
    }

    @Override
    public BizHumanResourceResumeEntity saveResume(Long userId, String fileURL, Long positionId, Resume resume) throws Exception {
        BizHumanResourceResumeEntity bizHumanResourceResumeEntity = BizHumanResourceResumeConvert.resumeToEntity(resume);
        bizHumanResourceResumeEntity.setMemberId(userId);
        bizHumanResourceResumeEntity.setPosition(positionId);
        bizHumanResourceResumeEntity.setFileUrl(fileURL);
        return bizHumanResourceResumeService.save(bizHumanResourceResumeEntity);
    }

    @Override
    public BizHumanResourceResumeEntity updateResume(Long id, Long userId, String fileURL, Long positionId, Resume resume) throws Exception {
        BizHumanResourceResumeEntity bizHumanResourceResumeEntity = BizHumanResourceResumeConvert.resumeToEntity(resume);
        bizHumanResourceResumeEntity.setId(id);
        bizHumanResourceResumeEntity.setMemberId(userId);
        bizHumanResourceResumeEntity.setPosition(positionId);
        bizHumanResourceResumeEntity.setFileUrl(fileURL);
        return bizHumanResourceResumeService.update(bizHumanResourceResumeEntity);
    }

    @Override
    public List<BizHumanResourceResumeEntity> listResumes(Long userId, Long positionId, PagingInfo pagingInfo) throws Exception {
        BizHumanResourceResumeEntity bizHumanResourceResumeEntity = new BizHumanResourceResumeEntity();
        bizHumanResourceResumeEntity.setMemberId(userId);
        bizHumanResourceResumeEntity.setPosition(positionId);
        bizHumanResourceResumeEntity.setIsDeleted(CommonConstant.IsDeleted.N);
        return bizHumanResourceResumeService.findByExample(bizHumanResourceResumeEntity, pagingInfo).stream()
                .sorted(Comparator.comparing(BizHumanResourceResumeEntity::getCreatedTime).reversed())
                .collect(Collectors.toList());
    }

    @Override
    public BizHumanResourceResumeEntity getResumeDetail(Long userId, Long resumeId) throws Exception {
        BizHumanResourceResumeEntity bizHumanResourceResumeEntity = new BizHumanResourceResumeEntity();
        bizHumanResourceResumeEntity.setId(resumeId);
        bizHumanResourceResumeEntity.setMemberId(userId);
        bizHumanResourceResumeEntity.setIsDeleted(CommonConstant.IsDeleted.N);
        List<BizHumanResourceResumeEntity> entities = bizHumanResourceResumeService.findByExample(bizHumanResourceResumeEntity, null);
        if (CollectionUtils.isEmpty(entities)) {
            return null;
        }
        return entities.get(0);
    }

    @Override
    public void deleteResumes(Long userId, Long... resumeIds) throws Exception {
        if (userId == null) {
            throw new BusinessException("用户未登录");
        }
        if (resumeIds == null || resumeIds.length == 0) {
            return;
        }

        String lock = "deleteResumeLock" + userId;
        synchronized (lock.intern()) {
            for (Long resumeId : resumeIds) {
                bizHumanResourceResumeService.deletedById(resumeId);
            }
        }
    }
}
