package com.fs.his.service.impl;

import com.fs.common.core.domain.AjaxResult;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.spring.SpringUtils;
import com.fs.company.domain.CompanyUser;
import com.fs.company.mapper.CompanyUserMapper;
import com.fs.his.domain.FsAiWorkflow;
import com.fs.his.domain.FsAiWorkflowEdge;
import com.fs.his.domain.FsAiWorkflowNode;
import com.fs.his.domain.FsAiWorkflowNodeType;
import com.fs.his.mapper.FsAiWorkflowEdgeMapper;
import com.fs.his.mapper.FsAiWorkflowMapper;
import com.fs.his.mapper.FsAiWorkflowNodeMapper;
import com.fs.his.mapper.FsAiWorkflowNodeTypeMapper;
import com.fs.his.param.FsAiWorkflowSaveParam;
import com.fs.his.param.FsAiWorkflowUpdateBindWCParam;
import com.fs.his.service.IFsAiWorkflowService;
import com.fs.his.vo.FsAiWorkflowExportVO;
import com.fs.his.vo.FsAiWorkflowNodeVoiceVo;
import com.fs.his.vo.FsAiWorkflowVO;
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.util.*;
import java.util.stream.Collectors;

/**
 * AI工作流Service业务层处理
 *
 * @author fs
 * @date 2026-01-06
 */
@Service
public class FsAiWorkflowServiceImpl implements IFsAiWorkflowService {

    @Autowired
    private FsAiWorkflowMapper fsAiWorkflowMapper;
    @Autowired
    private FsAiWorkflowNodeMapper fsAiWorkflowNodeMapper;
    @Autowired
    private FsAiWorkflowEdgeMapper fsAiWorkflowEdgeMapper;
    @Autowired
    private FsAiWorkflowNodeTypeMapper fsAiWorkflowNodeTypeMapper;

    private static List<String> aiCallNodeTypes = Arrays.asList("param", "ai_chat","end");
    @Override
    public FsAiWorkflowVO selectFsAiWorkflowById(Long workflowId) {
        FsAiWorkflow workflow = fsAiWorkflowMapper.selectFsAiWorkflowById(workflowId);
        if (workflow == null) {
            return null;
        }
        FsAiWorkflowVO vo = new FsAiWorkflowVO();
        BeanUtils.copyProperties(workflow, vo);
        vo.setNodes(fsAiWorkflowNodeMapper.selectFsAiWorkflowNodeByWorkflowId(workflowId));
        vo.setEdges(fsAiWorkflowEdgeMapper.selectFsAiWorkflowEdgeByWorkflowId(workflowId));
        return vo;
    }

    @Override
    public List<FsAiWorkflow> selectFsAiWorkflowList(FsAiWorkflow fsAiWorkflow) {
        return fsAiWorkflowMapper.selectFsAiWorkflowList(fsAiWorkflow);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long saveFsAiWorkflow(FsAiWorkflowSaveParam param) {
        Date now = DateUtils.getNowDate();
        Long workflowId = param.getWorkflowId();

        if (workflowId == null) {
            // 新增
            FsAiWorkflow workflow = new FsAiWorkflow();
            workflow.setWorkflowName(param.getWorkflowName());
            workflow.setWorkflowDesc(param.getWorkflowDesc());
            workflow.setWorkflowType(param.getWorkflowType());
            workflow.setCanvasData(param.getCanvasData());
            workflow.setStatus(1);
            workflow.setVersion(1);
            workflow.setCreateTime(now);
            fsAiWorkflowMapper.insertFsAiWorkflow(workflow);
            workflowId = workflow.getWorkflowId();
        } else {
            // 更新
            FsAiWorkflow workflow = new FsAiWorkflow();
            workflow.setWorkflowId(workflowId);
            workflow.setWorkflowName(param.getWorkflowName());
            workflow.setWorkflowDesc(param.getWorkflowDesc());
            workflow.setWorkflowType(param.getWorkflowType());
            workflow.setCanvasData(param.getCanvasData());
            workflow.setUpdateTime(now);
            fsAiWorkflowMapper.updateFsAiWorkflow(workflow);
            // 删除旧的节点和连线
            fsAiWorkflowNodeMapper.deleteFsAiWorkflowNodeByWorkflowId(workflowId);
            fsAiWorkflowEdgeMapper.deleteFsAiWorkflowEdgeByWorkflowId(workflowId);
        }

        // 保存节点
        List<FsAiWorkflowNode> nodes = param.getNodes();
        if (nodes != null && !nodes.isEmpty()) {
            for (FsAiWorkflowNode node : nodes) {
                node.setWorkflowId(workflowId);
                node.setCreateTime(now);
            }
            fsAiWorkflowNodeMapper.batchInsertFsAiWorkflowNode(nodes);
        }

        // 保存连线
        List<FsAiWorkflowEdge> edges = param.getEdges();
        if (edges != null && !edges.isEmpty()) {
            for (FsAiWorkflowEdge edge : edges) {
                edge.setWorkflowId(workflowId);
                edge.setCreateTime(now);
            }
            fsAiWorkflowEdgeMapper.batchInsertFsAiWorkflowEdge(edges);
        }

        //更新工作流后，需要删除或新增录音节点对应的id

        List<String> nodeKeyOlds = fsAiWorkflowMapper.selectFsAiWorkflowNodeByWorkflowId(workflowId);
        List<Long> companyUserIds = fsAiWorkflowMapper.selectWorkflowCompanyUserByWfId(workflowId);

        // 提取新节点的nodeKey
        List<String> newNodeKeys = nodes.stream()
                .filter(node -> aiCallNodeTypes.contains(node.getNodeType()))
                .map(FsAiWorkflowNode::getNodeKey)
                .collect(Collectors.toList());

        // 找出新增的nodeKey（新节点中有，旧节点中没有）
        List<String> nodeKeyAdd = newNodeKeys.stream()
                .filter(key -> !nodeKeyOlds.contains(key))
                .collect(Collectors.toList());

        // 找出需要删除的nodeKey（旧节点中有，新节点中没有）
        List<String> nodeKeyDel = nodeKeyOlds.stream()
                .filter(key -> !newNodeKeys.contains(key))
                .collect(Collectors.toList());
        if (!nodeKeyDel.isEmpty())fsAiWorkflowMapper.deleteAiWorkflowCompanyUserVoice(workflowId, nodeKeyDel);
        if (!nodeKeyAdd.isEmpty())fsAiWorkflowMapper.addAiWorkflowCompanyUserVoice(workflowId,companyUserIds, nodeKeyAdd);
        return workflowId;
    }

    @Override
    public int updateFsAiWorkflowStatus(Long workflowId, Integer status) {
        FsAiWorkflow workflow = new FsAiWorkflow();
        workflow.setWorkflowId(workflowId);
        workflow.setStatus(status);
        workflow.setUpdateTime(DateUtils.getNowDate());
        return fsAiWorkflowMapper.updateFsAiWorkflow(workflow);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteFsAiWorkflowByIds(Long[] workflowIds) {
        return fsAiWorkflowMapper.deleteFsAiWorkflowByIds(workflowIds);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long copyFsAiWorkflow(Long workflowId) {
        FsAiWorkflowVO source = selectFsAiWorkflowById(workflowId);
        if (source == null) {
            return null;
        }
        Date now = DateUtils.getNowDate();

        // 复制工作流
        FsAiWorkflow workflow = new FsAiWorkflow();
        workflow.setWorkflowName(source.getWorkflowName() + "_副本");
        workflow.setWorkflowDesc(source.getWorkflowDesc());
        workflow.setWorkflowType(source.getWorkflowType());
        workflow.setCanvasData(source.getCanvasData());
        workflow.setStatus(0);
        workflow.setVersion(1);
        workflow.setCreateTime(now);
        fsAiWorkflowMapper.insertFsAiWorkflow(workflow);
        Long newWorkflowId = workflow.getWorkflowId();

        // 复制节点
        List<FsAiWorkflowNode> nodes = source.getNodes();
        if (nodes != null && !nodes.isEmpty()) {
            for (FsAiWorkflowNode node : nodes) {
                node.setNodeId(null);
                node.setWorkflowId(newWorkflowId);
                node.setCreateTime(now);
            }
            fsAiWorkflowNodeMapper.batchInsertFsAiWorkflowNode(nodes);
        }

        // 复制连线
        List<FsAiWorkflowEdge> edges = source.getEdges();
        if (edges != null && !edges.isEmpty()) {
            for (FsAiWorkflowEdge edge : edges) {
                edge.setEdgeId(null);
                edge.setWorkflowId(newWorkflowId);
                edge.setCreateTime(now);
            }
            fsAiWorkflowEdgeMapper.batchInsertFsAiWorkflowEdge(edges);
        }

        return newWorkflowId;
    }

    @Override
    public List<FsAiWorkflowNodeType> selectAllEnabledNodeTypes() {
        return fsAiWorkflowNodeTypeMapper.selectAllEnabledNodeTypes();
    }

    @Override
    public FsAiWorkflowExportVO exportWorkflowJson(Long workflowId) {
        FsAiWorkflowVO workflowVO = selectFsAiWorkflowById(workflowId);
        if (workflowVO == null) {
            return null;
        }

        // 获取节点类型映射
        List<FsAiWorkflowNodeType> nodeTypes = fsAiWorkflowNodeTypeMapper.selectAllEnabledNodeTypes();
        Map<String, String> typeNameMap = nodeTypes.stream()
                .collect(Collectors.toMap(FsAiWorkflowNodeType::getTypeCode, FsAiWorkflowNodeType::getTypeName));

        // 构建导出VO
        FsAiWorkflowExportVO exportVO = new FsAiWorkflowExportVO();
        exportVO.setWorkflowId(workflowVO.getWorkflowId());
        exportVO.setWorkflowName(workflowVO.getWorkflowName());
        exportVO.setWorkflowDesc(workflowVO.getWorkflowDesc());
        exportVO.setWorkflowType(workflowVO.getWorkflowType());
        exportVO.setWorkflowTypeName(getWorkflowTypeName(workflowVO.getWorkflowType()));
        exportVO.setVersion(workflowVO.getVersion());

        // 构建节点信息
        List<FsAiWorkflowNode> nodes = workflowVO.getNodes();
        Map<String, String> nodeNameMap = new HashMap<>();
        List<FsAiWorkflowExportVO.NodeInfo> nodeInfoList = new ArrayList<>();
        if (nodes != null) {
            for (FsAiWorkflowNode node : nodes) {
                nodeNameMap.put(node.getNodeKey(), node.getNodeName());
                FsAiWorkflowExportVO.NodeInfo nodeInfo = new FsAiWorkflowExportVO.NodeInfo();
                nodeInfo.setNodeKey(node.getNodeKey());
                nodeInfo.setNodeName(node.getNodeName());
                nodeInfo.setNodeType(node.getNodeType());
                nodeInfo.setNodeTypeName(typeNameMap.getOrDefault(node.getNodeType(), node.getNodeType()));
                nodeInfo.setNodeConfig(node.getNodeConfig());
                nodeInfo.setPosX(node.getPosX());
                nodeInfo.setPosY(node.getPosY());
                nodeInfo.setSortOrder(node.getSortOrder());
                nodeInfoList.add(nodeInfo);
            }
        }
        exportVO.setNodes(nodeInfoList);

        // 构建连接信息(按sortOrder排序)
        List<FsAiWorkflowEdge> edges = workflowVO.getEdges();
        List<FsAiWorkflowExportVO.EdgeInfo> edgeInfoList = new ArrayList<>();
        if (edges != null) {
            edges.sort(Comparator.comparing(e -> e.getSortOrder() != null ? e.getSortOrder() : 0));
            for (FsAiWorkflowEdge edge : edges) {
                FsAiWorkflowExportVO.EdgeInfo edgeInfo = new FsAiWorkflowExportVO.EdgeInfo();
                edgeInfo.setEdgeKey(edge.getEdgeKey());
                edgeInfo.setEdgeLabel(edge.getEdgeLabel());
                edgeInfo.setSourceNodeKey(edge.getSourceNodeKey());
                edgeInfo.setSourceNodeName(nodeNameMap.get(edge.getSourceNodeKey()));
                edgeInfo.setTargetNodeKey(edge.getTargetNodeKey());
                edgeInfo.setTargetNodeName(nodeNameMap.get(edge.getTargetNodeKey()));
                edgeInfo.setConditionExpr(edge.getConditionExpr());
                edgeInfo.setSortOrder(edge.getSortOrder());
                edgeInfoList.add(edgeInfo);
            }
        }
        exportVO.setEdges(edgeInfoList);

        return exportVO;
    }

    @Override
    public List<CompanyUser> listCompanyUser() {
        return SpringUtils.getBean(CompanyUserMapper.class).selectAllCompanyUserList();
    }

    private String getWorkflowTypeName(Integer workflowType) {
        if (workflowType == null) return "";
        switch (workflowType) {
            case 1: return "对话流程";
            case 2: return "任务流程";
            case 3: return "审批流程";
            default: return "";
        }
    }

    @Override
    public List<FsAiWorkflowNode> selectWorkflowNodesByCompanyUserId(Long companyUserId, List<String> nodeTypes) {
        // 根据企业用户ID查询工作流
        List<FsAiWorkflow> workflows = fsAiWorkflowMapper.selectFsAiWorkflowByCompanyUserId(companyUserId);
        if (workflows == null || workflows.isEmpty()) {
            return new ArrayList<>();
        }

        // 收集所有工作流的指定类型节点
        List<FsAiWorkflowNode> result = new ArrayList<>();
        for (FsAiWorkflow workflow : workflows) {
            List<FsAiWorkflowNode> nodes = fsAiWorkflowNodeMapper.selectNodesByWorkflowIdAndTypes(
                    workflow.getWorkflowId(), nodeTypes);
            if (nodes != null) {
                result.addAll(nodes);
            }
        }
        return result;
    }

    @Override
    public int updateNodeVoiceUrl(Long nodeId, String voiceUrl, Long companyUserId) {
        // 1. 查询节点是否存在
        FsAiWorkflowNode node = fsAiWorkflowNodeMapper.selectFsAiWorkflowNodeById(nodeId);
        if (node == null) {
            return -1; // 节点不存在
        }

        // 2. 查询节点所属的工作流
        FsAiWorkflow workflow = fsAiWorkflowMapper.selectFsAiWorkflowById(node.getWorkflowId());
        if (workflow == null) {
            return -1; // 工作流不存在
        }

        // 3. 校验工作流是否属于该企业用户
        if (workflow.getCompanyUserId() == null || !workflow.getCompanyUserId().equals(companyUserId)) {
            return -2; // 无权限
        }

        // 4. 更新voiceUrl
        FsAiWorkflowNode updateNode = new FsAiWorkflowNode();
        updateNode.setNodeId(nodeId);
        updateNode.setVoiceUrl(voiceUrl);
        return fsAiWorkflowNodeMapper.updateFsAiWorkflowNode(updateNode);
    }

    @Override
    public CompanyUser getCompanyUserById(Long id) {
        return SpringUtils.getBean(CompanyUserMapper.class).selectCompanyUserById( id);
    }

    @Override
    public Boolean checkCompanyUserBeUsed(Long companyUserId) {
        return fsAiWorkflowMapper.selectFsAiWorkflowCountByCompanyUserId(companyUserId) > 0;
    }

    @Override
    public AjaxResult updateWorkflowBindCompanyUser(FsAiWorkflowUpdateBindWCParam param) {
        if (param == null ||param.getWorkflowId() == null || param.getCompanyUserIds() == null || param.getCompanyUserIds().size() == 0) return AjaxResult.error("传参异常");
        FsAiWorkflow fsAiWorkflowResult = fsAiWorkflowMapper.selectFsAiWorkflowById(Long.valueOf(param.getWorkflowId().toString()));
        if (fsAiWorkflowResult == null)return AjaxResult.error("未查询到对应工作流，请刷新后重试");
        int i = fsAiWorkflowMapper.insertFsAiWorkflowCompanyUser(param.getWorkflowId(),param.getCompanyUserIds());
        List<FsAiWorkflowNode> fsAiWorkflowNodes = fsAiWorkflowNodeMapper.selectNodesByWorkflowIdAndTypes(param.getWorkflowId(), aiCallNodeTypes);
        fsAiWorkflowMapper.insertAiWorkflowCompanyUserVoice(param.getWorkflowId(), param.getCompanyUserIds(), fsAiWorkflowNodes);
        return AjaxResult.success("绑定成功");
    }

    @Override
    public AjaxResult getBindCompanyUserByWorkflowId(Long workflowId) {
        FsAiWorkflow fsAiWorkflow = fsAiWorkflowMapper.selectFsAiWorkflowById(workflowId);
        if (fsAiWorkflow == null) return AjaxResult.error("工作流不存在");
        return AjaxResult.success(fsAiWorkflowMapper.getBindCompanyUserByWorkflowId(workflowId));
    }

    @Override
    public List<FsAiWorkflowNodeVoiceVo> getMyWorkflowNodes(Long companyUserId) {
        return fsAiWorkflowMapper.getMyWorkflowNodes(companyUserId);
    }
}
