import {useFlowJob} from "/@/flow/stores/flowJob";
import {ElNotification} from "element-plus";
import {flowConfig} from "/@/flow/designer/config/flow-config";

// 登录通知待办任务数
export function topJobList() {
    // 兼容移动端
    const route = useRoute();
    let index = route.fullPath.indexOf(flowConfig.mobileConfig.mobilePrefix);
    if (index !== -1) return
    useFlowJob().getJobList().then((jobLen) => {
        if (!jobLen || jobLen === 0) return
        ElNotification({
            title: "总任务数提醒",
            type: 'warning',
            dangerouslyUseHTMLString: true,
            message: `<a href="#" style="color:#FF4500;"><i class="iconfont icon-xianshimima"></i>当前总共&nbsp;${jobLen}&nbsp;条待办任务，请及时处理!</a>`,
            position: 'top-right',
            offset: 60,
            onClick: () => {
                useFlowJob().onTodoJobClick();
            }
        })
    })
}

// 消息通知工作流任务
export function notifyJsonFlowJob(res) {
    const data = JSON.parse(res.data)
    // 延迟解决可能没有工单数据
    setTimeout(() => {
        handleJsonFlowJob(data)
    }, 6000)
}

// 任务状态判断
function handleJsonFlowJob(data) {
    const opts: any = {}
    if (data.status === '0') { // 运行中
        const jobType = data.jobType === '0' ? '个人任务：' : '组任务：'
        const type = 'warning'
        const msg = '<a href="#" style="color:#FF4500;">' +
            '<i class="iconfont icon-xianshimima"></i>&nbsp;' + jobType + data.data + '</a>' + '，请及时处理'
        opts.onClick = function () {
            useFlowJob().onTodoJobClick();
        }
        jobNotify(opts, type, msg)
    } else { // 发起 或 结束
        const text = data.status === '-1' ? data.data : data.data + '已完成, 请悉知'
        const type = data.status === '-1' ? 'warning' : 'success'
        const msg = '<a href="#" style="color:#FF4500;">' + text + '</a>'
        jobNotify(opts, type, msg)
    }
}

// 任务提醒
function jobNotify(opts, type, msg) {
    useFlowJob().addJobLen();
    const defOpts = {
        title: '任务提醒',
        type: type,
        dangerouslyUseHTMLString: true,
        message: msg,
        offset: 60
    }
    ElNotification(Object.assign(defOpts, opts))
}

export function isJSON(str) {
    const jsonRegex = /^\s*[\[{].*[\]}]\s*$/;
    return jsonRegex.test(str);
}
