import {HtyRoles, NotifyParam} from "~/types";
import request from "~/utils/request";
import useLoading from "~/store/loading";
import useComment from "~/store/comment";

export default function useNotify(){

    const { load_start, load_done } = useLoading()
    const { get_comment } = useComment()


    async function get_role_id(role_key: HtyRoles) {
        const { r, d, e } = await request({url: `/api/v1/uc/find_role_by_key/${role_key}`});
        if (r) return d.hty_role_id;
    }

    async function notify_uc(params: NotifyParam, role_key: HtyRoles) {
        return notify(params, role_key, 'uc')
    }
    async function notify_ws(params: NotifyParam, role_key: HtyRoles) {
        return notify(params, role_key, 'ws')
    }
    async function notify_kc(params: NotifyParam, role_key: HtyRoles) {
        return notify(params, role_key, 'kc')
    }

    async function notify(params: NotifyParam, role_key: HtyRoles, module = 'uc'){
        load_start();
        let role_id = await get_role_id(role_key);
        let {comment_id} = params;
        if (comment_id) {
            // save comment data to push_info
            let comment = get_comment(comment_id)
            if (comment) {
                let {ref_resources, ...rest} = comment;
                params.comment = rest;
            }
        }
        const { r, d, e } = await request({
            url: `/api/v1/${module}/notify`,
            method: 'POST', data: {...params, to_role_id: role_id}
        });
        load_done();
        if(r) {
            return Promise.resolve(d);
        } else {
            console.error('notify error...', e);
            return Promise.resolve();
        }
    }

    return { notify_uc, notify_ws, notify_kc }
}
