import {reactive} from "vue";
import useLoading from "~/store/loading";
import request from "~/utils/request";
import {Toast, showFailToast, showSuccessToast} from "vant";
import {CourseCategory} from "~/types";


const store = reactive<{list: CourseCategory[]}>({
    list: []
});


export default function useCourseCategory() {


    const { load_start, load_done } = useLoading()


    function getDefault() {
        return store.list.find(x => x.is_default);
    }
    async function query(): Promise<boolean> {
        load_start()
        const {r, d, e} = await request({url: '/api/v1/ws/find_all_course_categories'});
        load_done()
        if (r) {
            store.list = d;
        } else {
            showFailToast(e);
        }
        return Promise.resolve(r);
    }

    async function create(data: CourseCategory) {
        load_start()
        const {r, d, e} = await request({
            url: `/api/v1/ws/create_course_category`, method: 'POST', data
        });
        load_done()
        if (r) {
            showSuccessToast({message: '课程体系类型创建成功！'});
            await query();
        } else {
            showFailToast(e);
        }
    }

    async function update(data: CourseCategory) {
        load_start()
        const {r, e} = await request({url: `/api/v1/ws/update_course_category`, method: 'POST', data});
        load_done()
        if (r) {
            showSuccessToast({message: '课程体系类型更新成功'});
            await query();
        } else {
            showFailToast(e);
        }
    }

    async function remove(id: string) {
        load_start()
        const {r, e} = await request({url: `/api/v1/ws/delete_course_category/${id}`});
        load_done()
        if (r) {
            showSuccessToast({message: '课程体系类型删除成功！'});
            await query();
        } else {
            showFailToast(e);
        }
    }

    function getByKey(key: string) {
        return store.list.find(x => x.category_key === key);
    }


    return {
        store, query, create, update, remove, getByKey, getDefault
    };

}
