import {reactive} from "vue";
import useLoading from "~/store/loading";
import request from "~/utils/request";
import {showFailToast, showSuccessToast} from "vant";
import {CourseGroup} from "~/types";
import useUser from "~/store/user";
import {Router} from "vue-router";
import useCourseSection from "~/store/qumu-section";


const initialEntity = (): CourseGroup => ({
    id: undefined,
    group_name: '',
    course_sections: [],
    org_visible: false,
} as CourseGroup);

const store = reactive<{list: CourseGroup[]}>({
    current: initialEntity(),
    list: [],
    hanging: false,
});


export default function useCourseGroup(router?: Router) {


    const { load_start, load_done } = useLoading()

    const {store:{current:{hty_id}}, getHtyUser} = useUser();

    const {query_by_ids} = useCourseSection()

    async function query(): Promise<boolean> {
        load_start()
        const {r, d, e} = await request({url: '/api/v1/ws/find_course_group_by_hty_id/' + hty_id});
        load_done()
        if (r) {
            let hty_ids = new Set<string>();
            let qs_ids = new Set<string>();
            d.forEach(({created_by, updated_by, course_section_ids}: CourseGroup) => {
                if (created_by) {
                    hty_ids.add(created_by)
                }
                if (updated_by) {
                    hty_ids.add(updated_by)
                }
                if (course_section_ids) {
                    course_section_ids.vals.forEach(v => qs_ids.add(v))
                }
            });
            Promise.all([...hty_ids].map(x => getHtyUser(x))).then((users) => {
                d.forEach(qsg => {
                    let creator = users.find(u => u.hty_id === qsg.created_by);
                    if (creator) {
                        qsg.creator_name = creator.real_name
                    }
                    let updator = users.find(u => u.hty_id === qsg.updated_by);
                    if (updator) {
                        qsg.updator_name = updator.real_name
                    }
                })
            })
            let sections = await query_by_ids([...qs_ids]);
            if (sections) {
                d.forEach(x => {
                    x.course_sections = (x.course_section_ids?.vals || []).map(y => sections.find(z => z.id === y))
                })
            }
            store.list = d;
        } else {
            showFailToast(e);
        }
        return Promise.resolve(r);
    }

    async function read(id: string) {
        console.log("read...", id)
        if (!id) return;
        load_start()
        const {r, d, e} = await request({
            url: `/api/v1/ws/find_course_group_by_ids`, method: "POST", data: {vals: [id]}
        });
        if (r && d.length) {
            store.current = d[0];
            store.current.course_sections = await query_by_ids(store.current.course_section_ids?.vals || []);
        } else {
            reset();
            showFailToast(e);
        }
        load_done()
    }

    async function create() {
        let {current: {group_name, course_sections, teachers, org_visible}} = store;
        if (!group_name) {
            showSuccessToast("请输入分组名称！")
            return Promise.reject();
        }
        let data = {group_name, teachers, created_by: hty_id, org_visible}
        data.course_section_ids = {vals: course_sections.map(x => x.id)};
        load_start()
        const {r, d, e} = await request({
            url: `/api/v1/ws/create_course_group`, method: 'POST', data
        });
        load_done()
        if (r) {
            showSuccessToast({message: '课节创建成功', onClose: () => router?.replace(`/course/group/detail?id=${d}`)});
            reset()
        } else {
            showFailToast(e);
        }
    }

    async function update() {
        let {current: {group_name, course_sections, ...rest}} = store;
        if (!group_name) {
            showSuccessToast("请输入分组名称！")
            return Promise.reject();
        }
        let data = {group_name, ...rest, updated_by: hty_id}
        data.course_section_ids = {vals: course_sections.map(x => x.id)};
        load_start()
        const {r, e} = await request({url: `/api/v1/ws/update_course_group`, method: 'POST', data});
        load_done()
        if (r) {
            showSuccessToast({message: '课节保存成功', onClose: () => router?.replace(`/course/group/detail?id=${data.id}`)});
            reset();
        } else {
            showFailToast(e);
        }
    }

    async function remove(id: string) {
        load_start()
        const {r, e} = await request({method: "POST", url: `/api/v1/ws/delete_course_group/${id}`});
        load_done()
        if (r) {
            showSuccessToast({message: '课节删除成功！'});
            router?.replace("/course/group")
        } else {
            showFailToast(e);
        }
    }

    function reset() {
        store.current = initialEntity()
    }


    return {
        store, query, create, update, remove, reset, read
    };

}
