import {reactive} from 'vue';
import request from "../utils/request";
import {showFailToast, showSuccessToast} from "vant";
import {CourseSection, UserGroup} from "~/types";
import useLoading from "~/store/loading";
import { Router } from 'vue-router';
import useUser from "~/store/user";

interface UserGroupstate {
    hanging: boolean,
    current: UserGroup,
    mine: UserGroup[],
    assigned: UserGroup[]
}

const store = reactive<UserGroupstate>({
    hanging: false,
    current: {users: {vals: []}} as unknown as UserGroup,
    mine: [],
    assigned: []
});

export default function useUserGroup(router?: Router) {

    const { load_start, load_done } = useLoading()
    const {store: {current: cur_user}, getHtyUser} = useUser()

    async function query(key: "mine" | "assigned"): Promise<boolean> {
        load_start()
        let url = {mine: "get_user_groups_of_current_user", assigned: "get_user_groups_by_owner_id/" + cur_user.hty_id}[key];
        const {r, d, e} = await request({
            url: `/api/v1/uc/${url}`, data: {is_deleted: false}
        });
        load_done()
        if (r) {
            store[key] = d;
            let hty_ids = new Set(d.map(x => x.created_by));
            Promise.all([...hty_ids].filter(x => !!x).map(getHtyUser)).then((users) => {
                store[key].forEach(group => {
                    let creator = users.find(u => u.hty_id === group.created_by);
                    if (creator) {
                        group.creator_name = creator.real_name
                    }
                })
            })
        } else {
            showFailToast(e);
        }
        return Promise.resolve(r);
    }

    function validate({group_name, group_type, users}: UserGroup) {
        if (!group_name) {
            showFailToast("请输入小组名称！")
            return false;
        }
        if (!group_type) {
            showFailToast("请选择小组类型！")
            return false;
        }
        if (!users?.vals?.length) {
            showFailToast("请添加小组成员！")
            return false;
        }
        return true;
    }

    async function create() {
        if (!validate(store.current)) return;
        load_start()
        const {r, d, e} = await request({
            url: `/api/v1/uc/create_user_group`, method: 'POST', data: {...store.current, created_by: cur_user.hty_id}
        });
        load_done()
        if (r) {
            showSuccessToast({message: '小组创建成功！'});
            await query("mine");
            router?.push('/user-group/detail?id=' + d)
        } else {
            showFailToast(e);
        }
    }

    async function update() {
        if (!validate(store.current)) return;
        load_start()
        const {r, e} = await request({url: `/api/v1/uc/update_user_group`, method: 'POST', data: {...store.current}});
        load_done()
        if (r) {
            showSuccessToast({message: '小组更新成功'});
            await query("mine");
            router?.push('/user-group/detail?id=' + store.current.id)
        } else {
            showFailToast(e);
        }
    }

    async function remove(id: string) {
        load_start()
        const {r, e} = await request({
            url: `/api/v1/uc/delete_user_group/${id}`,
            method: 'post'
        });
        load_done()
        if (r) {
            showSuccessToast({message: '小组删除成功！'});
        } else {
            showFailToast(e);
        }
    }

    function reset() {
        if (!store.hanging) {
            store.current = {users: {vals: []}} as unknown as UserGroup;
        }
        store.hanging = false;
    }


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


}
