import {RouteRecordRaw} from "vue-router";
import {flowConfig} from "/@/flow/designer/config/flow-config";
import {Session} from "/@/utils/storage";
import {locationHash, vueKeySys} from "/@/api/order/order-key-vue";
import {useUserInfo} from "/@/stores/userInfo";
import {validateNull} from "/@/utils/validate";
import {getToDoneDetail} from "/@/api/jsonflow/hi-job";
import * as doJob from "/@/api/jsonflow/do-job";
import {DIC_PROP} from "/@/flow/support/dict-prop";
import {paramsFilter} from "/@/flow";

// 移动端path
export const vueAppKeyHash = {
    flowview: 'jsonflow/flow-design/view'
    , jobview: 'order/run-application/view'
    , jobinitiate: 'order/flow-application/initiate'
    , jobinitagain: 'order/run-application/initiate'
    , jobform: 'order/run-application/flow'
}

export async function initJobDataByApp($route, props) {
    let appdata = flowConfig.mobileConfig.mobilePrefix
    let app = !validateNull($route.query[appdata]);
    if (!app) return
    let split = $route.query[appdata].split('-');
    let query = {orderId: split[1], id: split[2], flowInstId: split[3], runNodeId: split[4], elTabId: split[5], hiJob: split[6] === 'Y'}
    if (query.hiJob) {
        await handleToDoneDetail(query, props, '1')
    } else {
        await handleTodoDetail(query, props)
    }
    props.currJob.hiJob = query.hiJob
    props.currElTab.id = query.elTabId
}

export async function handleTodoDetail(row, data, isView?, isRead?, $message?, getDataList?) {
    let query = Object.assign({}, row, {order: null, elTabs: null});
    query = paramsFilter(query)
    await doJob.getTodoDetail(query).then(response => {
        if ($message) data.currJob = response.data
        // 兼容移动端
        else Object.assign(data.currJob, response.data);
        if (isRead !== '1' && isView !== '1' && DIC_PROP.NODE_STATUS[2].value === data.currJob.status) {
            if ($message) {
                $message.warning('当前任务已被其他办理人审批')
                getDataList();
            }
        } else {
            if (isView !== '1') {
                if (isRead === '1') data.currJob.hiJob = true
                doJob.isRead(data.currJob).then(() => {
                    row.isRead = '1'
                    // 独立标签都需执行
                    if (isRead === '1') getDataList();
                })
            } else data.currJob.hiJob = true
        }
    })
}

const channel = new BroadcastChannel('currJob_channel');
export async function handleFlowPreview($router, row, isView?, isRead?, $message?, flowJob?, getDataList?) {
    channel.onmessage = (event) => {
        flowJob.delJobLen();
        // getDataList();
    };
    row.isHiJob = '0'
    windowOpenFlow($router, row, isView, isRead)
}

function windowOpenFlow($router, row, isView?, isRead?, isApp?, isForm?) {
    let query = { id: row.id, flowInstId: row.flowInstId, isHiJob: row.isHiJob, isView, isRead, isApp, isForm }
    $router.push({
        name: dynamicRoutesFlow[0].name,
        query: query
    })
    /*const routeUrl = $router.resolve({
        path: dynamicRoutesFlow[0].path,
        query: query,
    });
    window.open(routeUrl.href, '_blank');*/
}

export async function handleToDoneDetail(row, data, isApp?, isForm?) {
    let query = Object.assign({}, row, {order: null, elTabs: null});
    query = paramsFilter(query)
    await getToDoneDetail(query).then(response => {
        // 兼容移动端
        if (isApp === '1') {
            Object.assign(data.currJob, response.data);
            return
        }
        data.currJob = response.data
        if (isForm === '1') {
            let elTabs = data.currJob.elTabs;
            data.currJob.elTabs = elTabs.filter(f => vueKeySys.sysPaths.includes(f.path))
            // 判断是否只配置表单
            if (validateNull(data.currJob.elTabs)) data.currJob.elTabs =  elTabs
        }
        // 历史查看标识
        data.currJob.hiJob = true
    })
}

export async function openFlowPreview($router, row, isForm?) {
    row.isHiJob = '1'
    windowOpenFlow($router, row, null, null, null, isForm)
}

export async function replaceRouterRoute(route, router) {
    // 兼容移动端
    let appPath = '', appdata = flowConfig.mobileConfig.mobilePrefix;
    // 防止重复进入
    if (route.fullPath.indexOf('?' + appdata + '=') !== -1) {
        return
    }
    let index = route.fullPath.indexOf(appdata);
    if (index !== -1) {
        let last = route.fullPath.indexOf("-");
        if (route.fullPath.indexOf('?' + appdata + '=') !== -1) last = route.fullPath.indexOf("?");
        appPath = route.fullPath.substring(route.fullPath.indexOf("/") + 1, last);

        router.currentRoute.value.name = "flowRoutes." + appPath
        let fullPath = route.fullPath.replace('-', '?');
        fullPath = fullPath.replace('-', '=');
        fullPath = fullPath.replace(appPath, vueAppKeyHash[appPath]);

        let split = fullPath.split('=')[1].split('-');
        // 存储token 信息
        if (split[0].indexOf('_') !== -1) {
            // 判断是否微服务版本
            let tokenTenant = split[0].replace('_', '-').split('-')
            Session.set('tenantId', tokenTenant[0]);
            Session.set('token', tokenTenant[1].replaceAll('_', '-'));
        } else {
            Session.set('token', split[0]);
        }
        // 触发初始化用户信息 pinia
        await useUserInfo().setUserInfos();
        await router.replace(fullPath);
    }
}

export async function replaceRouterThirdRoute(route, router) {
    let fullPath = route.fullPath;
    // 防止重复进入
    if (fullPath.indexOf('tokenLoaded') !== -1) {
        // 防止刷新后无用户信息
        await useUserInfo().setUserInfos();
        return
    }
    // 三方系统单点
    if (fullPath.indexOf('token') !== -1) {
        Session.clear()
        fullPath = fullPath.replace('token', 'tokenLoaded');
        // 存储token 信息
        Session.set('tenantId', route.query.tenantId);
        Session.set('token', route.query.token);
    } else {
        fullPath = route.fullPath + '&tokenLoaded=1';
    }
    // 必须获取用户信息
    await useUserInfo().setUserInfos();
    router.currentRoute.value.name = "staticRoutes.handleoajob"
    await router.replace(fullPath);
}

export function initJsonFlowViewByApp($route, props) {
    let appdata = flowConfig.mobileConfig.mobilePrefix
    let app = !validateNull($route.query[appdata]);
    if (app) {
        let split = $route.query[appdata].split('-');
        let query = {defFlowId: split[1], flowInstId: split[2] === 'undefined' ? '' : split[2]}
        Object.assign(props.currJob, query);
    }
}

export function windowLocationHrefParam(hash, param = '') {
    return window.location.href = window.location.origin + window.location.pathname + locationHash[hash] + param
}

export function windowLocationHref(hash) {
    window.location.href = window.location.origin + window.location.pathname + hash
}

/**
 * 定义静态路由（默认路由）
 */
export const staticRoutesFlow: Array<RouteRecordRaw> = [
    {
        path: '/jsonflow/flow-design/view',
        name: 'flowRoutes.flowview',
        component: () => import('/@/views/jsonflow/flow-design/view.vue'),
        meta: {
            isAuth: false,
        },
    },
    {
        path: '/order/run-application/view',
        name: 'flowRoutes.jobview',
        component: () => import('/@/views/order/run-application/view.vue'),
        meta: {
            isAuth: false,
        },
    },
    {
        path: '/order/flow-application/initiate',
        name: 'flowRoutes.jobinitiate',
        component: () => import('/@/views/order/flow-application/initiate.vue'),
        meta: {
            isAuth: false,
        },
    },
    {
        path: '/order/run-application/initiate',
        name: 'flowRoutes.jobinitagain',
        component: () => import('/@/views/order/run-application/initiate.vue'),
        meta: {
            isAuth: false,
        },
    },
    {
        path: '/order/run-application/flow',
        name: 'flowRoutes.jobform',
        component: () => import('/@/views/order/run-application/flow.vue'),
        meta: {
            isAuth: false,
        },
    }
];

/**
 * 定义静态路由（默认路由）
 * 前端添加路由，请在此处加
 */
export const dynamicRoutesFlow: Array<RouteRecordRaw> = [
    {
        path: '/flow/components/handle-job/handle',
        name: 'flowRoutes.handlejob',
        component: () => import('/@/flow/components/handle-job/handle.vue'),
        meta: {
            isKeepAlive: false,
            isHide: true,
        },
    },
    {
        path: '/jsonflow/flow-design/index',
        name: 'flowRoutes.flowdesign',
        component: () => import('/@/views/jsonflow/flow-design/index.vue'),
        meta: {
            isKeepAlive: false,
            isHide: true,
        },
    },
];
