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

interface CoursePackageStore {
  list: CoursePackage[];
  total: number;
  selectedGroups: CourseGroup[];
  hanging: boolean;
}

const state = reactive<CoursePackageStore>({
  list: [],
  total: 0,
  selectedGroups: [],
  hanging: false,
});

export default function useCoursePackage() {
  const {load_start, load_done} = useLoading();

  async function queryMyPackages(keyword?: string, page = 1, pageSize = 20): Promise<boolean> {
    load_start();
    const params = new URLSearchParams({page: String(page), page_size: String(pageSize)});
    if (keyword) params.set('keyword', keyword);
    const {r, d, e} = await request({url: `/api/v1/clazz/course-package/my-packages?${params}`});
    load_done();
    if (r) {
      const [list, totalPage, totalCount] = d as [CoursePackage[], number, number];
      state.list = Array.isArray(list) ? list : [];
      state.total = totalPage;
    } else {
      showFailToast(e);
    }
    return r;
  }

  async function queryPublicPackages(orgId?: string, keyword?: string, page = 1, pageSize = 20): Promise<boolean> {
    load_start();
    const params = new URLSearchParams({page: String(page), page_size: String(pageSize)});
    if (orgId) params.set('org_id', orgId);
    if (keyword) params.set('keyword', keyword);
    const {r, d, e} = await request({url: `/api/v1/clazz/course-package/public-packages?${params}`});
    load_done();
    if (r) {
      const [list, totalPage, totalCount] = d as [CoursePackage[], number, number];
      state.list = Array.isArray(list) ? list : [];
      state.total = totalPage;
    } else {
      showFailToast(e);
    }
    return r;
  }

  async function queryOrgPackages(keyword?: string, page = 1, pageSize = 20): Promise<boolean> {
    load_start();
    const params = new URLSearchParams({page: String(page), page_size: String(pageSize)});
    if (keyword) params.set('keyword', keyword);
    const {r, d, e} = await request({url: `/api/v1/clazz/course-package/org-packages?${params}`});
    load_done();
    if (r) {
      const [list, totalPage, totalCount] = d as [CoursePackage[], number, number];
      state.list = Array.isArray(list) ? list : [];
      state.total = totalPage;
    } else {
      showFailToast(e);
    }
    return r;
  }

  async function findById(id: string): Promise<CoursePackage | undefined> {
    load_start();
    const {r, d, e} = await request({url: `/api/v1/clazz/course-package/${id}`});
    load_done();
    if (r) return d;
    showFailToast(e);
    return undefined;
  }

  async function create(data: CoursePackage): Promise<any> {
    load_start();
    const {r, d, e} = await request({
      url: '/api/v1/clazz/course-package/create',
      method: 'POST',
      data,
    });
    load_done();
    if (r) {
      showSuccessToast({message: '课包创建成功！'});
      return d;
    }
    showFailToast(e);
    return undefined;
  }

  async function update(data: CoursePackage): Promise<boolean> {
    load_start();
    const {r, e} = await request({
      url: '/api/v1/clazz/course-package/update',
      method: 'POST',
      data,
    });
    load_done();
    if (r) {
      showSuccessToast({message: '课包更新成功！'});
    } else {
      showFailToast(e);
    }
    return r;
  }

  async function remove(id: string): Promise<boolean> {
    load_start();
    const {r, e} = await request({
      url: `/api/v1/clazz/course-package/delete/${id}`,
      method: 'POST',
    });
    load_done();
    if (r) {
      showSuccessToast({message: '课包删除成功！'});
    } else {
      showFailToast(e);
    }
    return r;
  }

  async function syncPackageItems(packageId: string, courseGroupIds: string[]): Promise<boolean> {
    load_start();
    const {r, e} = await request({
      url: '/api/v1/clazz/course-package/item/sync',
      method: 'POST',
      data: { package_id: packageId, course_group_ids: courseGroupIds },
    });
    load_done();
    if (!r) showFailToast(e);
    return r;
  }

  async function listPackageItems(packageId: string): Promise<CourseGroup[] | undefined> {
    load_start();
    const {r, d, e} = await request({url: `/api/v1/clazz/course-package/item/list/${packageId}`});
    load_done();
    if (r) {
      // d is Vec<CoursePackageItem>, each has course_group_id
      // fetch course_group details from htyws
      const items: any[] = d || [];
      if (!items.length) return [];
      const groupIds = items.map((i: any) => i.course_group_id);
      const {r: r2, d: d2, e: e2} = await request({
        url: '/api/v1/ws/find_course_group_by_ids',
        method: 'POST',
        data: {vals: groupIds},
      });
      if (r2) return d2 || [];
      return [];
    }
    showFailToast(e);
    return undefined;
  }

  async function publish(id: string, snapshot: any): Promise<boolean> {
    load_start();
    const {r, e} = await request({
      url: `/api/v1/clazz/course-package/publish/${id}`,
      method: 'POST',
      data: snapshot,
    });
    load_done();
    if (r) {
      showSuccessToast({message: '课包发布成功！'});
    } else {
      showFailToast(e);
    }
    return r;
  }

  async function unpublish(id: string): Promise<boolean> {
    load_start();
    const {r, e} = await request({
      url: `/api/v1/clazz/course-package/unpublish/${id}`,
      method: 'POST',
    });
    load_done();
    if (r) {
      showSuccessToast({message: '课包已下架！'});
    } else {
      showFailToast(e);
    }
    return r;
  }

  return {
    store: state,
    queryMyPackages,
    queryOrgPackages,
    queryPublicPackages,
    findById,
    create,
    update,
    remove,
    syncPackageItems,
    listPackageItems,
    publish,
    unpublish,
  };
}
