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

interface CourseStore {
    list: Course[]
}

const state = reactive<CourseStore>({
    list: []
});

export default function useCourse() {

    const { load_start, load_done } = useLoading()

    async function query(): Promise<boolean> {
        load_start()
        const {r, d, e} = await request({url: '/api/v1/ws/find_all_courses'});
        load_done()
        if (r) {
            state.list = Array.isArray(d) ? d : [];
            if (!Array.isArray(d)) {
                showFailToast('课程数据格式异常，已自动回退为空列表');
            }
        } else {
            showFailToast(e);
        }
        return Promise.resolve(r);
    }

    async function read(id: string): Promise<Course | undefined> {
        load_start();
        const {r, d, e} = await request({url: `/api/v1/ws/find_course_by_id/${id}`});
        load_done();
        if (r) {
            return d;
        }
        showFailToast('没找到指定课程体系，请刷新后操作');
    }

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

    async function update(data: Course) {
        load_start()
        const {r, e} = await request({url: `/api/v1/ws/update_course`, 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_by_id/${id}`,
            method: 'post'
        });
        load_done()
        if (r) {
            showSuccessToast({message: '课程体系删除成功！'});
            await query();
        } else {
            showFailToast(e);
        }
    }


    return {
        store: state, query, create, update, remove, read
    };


}
