import { sendFetch, PageProps } from './index'
import { ResPage, ResResult } from './type'
import { organizationTypeEnum } from '@/store/organization'
import * as URL from "./URL";
import { ElMessage } from "element-plus";
import { throttle, encodePwd } from "@/util";

const error = throttle((msg: string) => ElMessage.error(msg), 2000);
const success = throttle((msg: string) => ElMessage.success(msg), 2000);

export type OrganizationType = {
    ancestors: string
    contact: string
    orderNum: number
    orgId: number
    parentId: number
    orgName: string
    password: string
    type: organizationTypeEnum | null
    userName: string
    confirmPwd?: string,
    msgAuthCode?: string

}

export const addOrgFetch = async (params: Partial<OrganizationType>) => {
    const api = await sendFetch<ResResult>(URL.addOrganization, {
        method: "post",
        body: JSON.stringify(params),
    }, {
        useResult: true
    });
    if (api.code === 0) {
        success('添加成功')
    } else {
        if (api.code === 2008) {
            success(api.message)
        } else {
            error(api.message)
            throw (api.message)
        }
    }

}


export const alterOrgFetch = (params: Partial<OrganizationType>) =>
    sendFetch<PageProps<OrganizationType>>(URL.alterOrganization, {
        method: "post",
        body: JSON.stringify(params),
    });
export const delOrgFetch = (params: Partial<OrganizationType>) =>
    sendFetch<PageProps<OrganizationType>>(URL.delOrganization, {
        method: "post",
        body: JSON.stringify(params),
    });
export const getOrgListFetch = (params: PageProps<Partial<OrganizationType>>) =>
    sendFetch<ResPage<PageProps<OrganizationType>>>(URL.organizationPage, {
        method: "post",
        body: JSON.stringify(params),
    });


export const getOrgListFetchList = () =>
    sendFetch<ResPage<PageProps<OrganizationType>>>(URL.organizationPageList, {
        method: "post",
        body: JSON.stringify({}),
    });


export const registerOrganization = (params: any) => {
    const password = encodePwd(params.password)
    return sendFetch<ResResult>(URL.registerOrganization, {
        method: "post",
        body: JSON.stringify({ ...params, password, confirmPwd: password }),
    }, {
        noToken: true
    });

}
