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

export type UserType = {
    createBy: string
    createTime: string
    fdkkId: number
    head: string
    nickName: string
    orgId: number
    orgName: string
    status: number
    tbStatus: number
    updateBy: string
    updateTime: string
    userId: number
    userName: string
    roleNames: string
    confirmPwd?: string
    msgAuthCode?: string
    password?: string
    phoneNum?: string
}


export const getUserpageFetch = (params: any) =>
    sendFetch<ResPage<PageProps<UserType>>>(URL.userScenepage, {
        method: "post",
        body: JSON.stringify(params),
    });


export const addUserFetch = (params: any) =>
    sendFetch<ResPage<PageProps<UserType>>>(URL.addUser, {
        method: "post",
        body: JSON.stringify(params),
    });
export const editUserFetch = (params: Partial<UserType>) =>
    sendFetch<ResPage<PageProps<UserType>>>(URL.alterUser, {
        method: "post",
        body: JSON.stringify(params),
    });

export const delUserFetch = (params: Pick<UserType, 'userId'>) =>
    sendFetch<ResPage<PageProps<UserType>>>(
        URL.delUser,
        { method: "post", body: JSON.stringify({}) },
        { paths: { userId: params.userId } }
    );
export const updateUserStatusFetch = (params: Pick<UserType, 'userId' | 'status'>) =>
    sendFetch<ResPage<PageProps<UserType>>>(URL.changeUserStatus, {
        method: "post",
        body: JSON.stringify(params),
    });

export type ChangePasswordParam = Pick<UserType, 'confirmPwd' | 'msgAuthCode' | 'password' | 'phoneNum'>
export const changePassword = async (params: ChangePasswordParam) => {

    const ent = encodePwd(params.password)
    if (params.password !== params.confirmPwd) {
        ElMessage.error("当前密码与密码确认不一致！");
        return Promise.reject()
    } else {
        const api = await sendFetch<ResResult>(URL.changePassword, {
            method: "post",
            body: JSON.stringify({
                confirmPwd: ent,
                password: ent,
                msgAuthCode: params.msgAuthCode,
                phoneNum: params.phoneNum
            }),
        }, {
            useResult: true
        });
        if (api.code === 0) {
            ElMessage.success("编辑成功！");
        } else {
            ElMessage.error(api.message);
            throw (api.message)
        }
    }

}

export const getMsgAuthCode = (areaNum: string,
    phoneNum: string) =>
    sendFetch<ResResult>(URL.getMsgAuthCode, {
        method: "post",
        body: JSON.stringify({
            areaNum,
            phoneNum
        }),
    }, {
        useResult: true
    });





