import { AddUserModel, UpdatePasswordDto } from '@/api/user/UserModel';
import { Result } from '@/http/request';
import { EditType, UsersType } from '@/type/BaseEnum';
import { ref, unref } from 'vue'
import { addUserApi, editUserApi, deleteUserApi, resetPasswordApi } from '@/api/user/user';
import useInstance from '@/hooks/useInstance';
import { cloneDeep } from '@/utils/cloneDeep';
import { UserDataPermissionDto } from '@/api/dataPermission/dataPermissionModel';
import { api_userDataPermissionSave } from '@/api/dataPermission/dataPermission';
import { useReturnData } from '@/utils/useReturnData';
import { useMessage } from '@/hooks/useMessage';
const { ElMessageBox } = useMessage()

const { resData } = useReturnData()
export default function useUser(getUserList) {
    //分配角色组件的ref属性
    const assignRoleRef = ref<{show:(name:string,useId:string | number) =>void}>();
    //全局属性
    const { global } = useInstance()

    //新增弹框ref属性
    const userAddRef = ref<{ show: (type: string, row?: AddUserModel) => void }>();

    //新增
    const addBtn = () => {
        //显示弹框
        userAddRef.value?.show(EditType.ADD)
    }
    //编辑
    const editBtn = (row: AddUserModel) => {
        //显示弹框
        userAddRef.value?.show(EditType.EDIT, row)
    }
    //删除
    const deleteBtn = async (id: number) => {
        let parm = {
            id: id
        }
        //信息提示
        let confirm = await global.$myconfirm('确定删除该数据吗?')
        if (confirm) {
            let res = await deleteUserApi(parm)
            if (res && res.code == 200) {
                global.$message({ message: res.msg, type: "success" })
                //刷新列表
                getUserList();
            }
        }
    }
    //分配角色
    const assignBtn = (row:AddUserModel) => {
        assignRoleRef.value?.show(row.loginName,row.id)
    }
    //新增、编辑保存
    const save = async (parm: AddUserModel, onclose: Fn) => {
        let res: Result;
        if (parm.type == EditType.ADD) {
            res = await addUserApi(parm)
        } else {
            res = await editUserApi(parm)
        }
        if (res && res.code == 200) {
            //刷新列表
            getUserList();
            //信息提示
            global.$message({ message: res.msg, type: 'success' })
            onclose()
        }
    }
    const dataPermisitonSetRef = ref<{ show: Fn }>()
    // 操作栏
    const handleClickChange = (row) => {
        const data = cloneDeep(row)
        switch (data.types) {
            case UsersType.RESET_PASSWORD:
                ElMessageBox.prompt('新密码:', '重置密码', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    inputPattern: /^.{6,}$/,
                    inputErrorMessage: '请输入重置密码（至少6个字符）',
                    inputPlaceholder: '请输入重置密码'
                  }).then(({ value }) => {
                        restPassword({ id: data.id,  newPassword: value})
                    })
                break;
            case UsersType.EDIT:
                editBtn(data)
                break;
            case UsersType.DATA_PERMISSION:
                unref(dataPermisitonSetRef)?.show(data)
                break;
            case UsersType.ASSIGN_ROLE:
                assignBtn(data)
                break;
            case UsersType.DELETE:
                deleteBtn(data.id)
                break;
        }
    }
    // 数据权限保存
    const hanelDataPermisitonSave = async (list: UserDataPermissionDto[], onclose: Fn, setLoading: Fn) => {
        if(list.length == 0) {
            setLoading(false)
            onclose()
            return
        }
        try {
            const res = await api_userDataPermissionSave(list)
            const resCode = resData(res, '操作成功')
            if(resCode !== 500) {
                onclose()
                getUserList()
            }
        } finally {
            setLoading(false)
        }
    }
    // 重置密码
    const restPassword = async (params: UpdatePasswordDto) => {
        const res = await resetPasswordApi(params)
        resData(res, '操作成功')
    }

    return {
        addBtn,
        editBtn,
        deleteBtn,
        assignBtn,
        userAddRef,
        save,
        assignRoleRef,
        dataPermisitonSetRef,
        handleClickChange,
        hanelDataPermisitonSave
    }
}