<template>
    <!-- 用户 -->
    <div class="ba-user-container">
        <el-container class="defaultContainer">
            <el-aside class="defaultAside">
                <el-main class="treeMain">
                    <el-tree
                        style="max-width: 600px; margin-top: 2.2%"
                        ref="treeRefUserList"
                        :data="userData"
                        :props="defaultProps"
                        node-key="id"
                        :load="loadNode"
                        lazy
                        @node-click="handleNodeClick"
                        :default-expanded-keys="['1']"
                    />
                </el-main>
            </el-aside>
            <el-container class="defaultMainContainer">
                <el-header class="defaultHeader">
                    <div class="searchPart">
                        <el-input v-model="input2" class="searchInput" placeholder="根据账户中文名查询"></el-input>
                        <el-button @click="userFromQuery" type="primary" :icon="Search" class="defaultBtn">查询</el-button>
                    </div>
                    <el-button size="large" type="primary" :icon="CirclePlusFilled" class="defaultBtn" @click="addUserFromData">新增</el-button>
                </el-header>
                <el-main class="defaultMain">
                    <el-table ref="multipleTableRef" :data="tableData" class="tablePart">
                        <el-table-column type="selection" />
                        <el-table-column property="account" label="账户名称" />
                        <el-table-column property="userName" label="账户中文名" />
                        <el-table-column property="address" label="操作">
                            <template #default="scope">
                                <span style="color: #0064aa; cursor: pointer" @click="viewUsers(scope)">查看 </span>
                                <span style="color: #0064aa"> | </span>
                                <span style="color: #0064aa; cursor: pointer" @click="userFromDelete(scope)"> 删除 </span>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div style="display: flex; justify-content: right">
                        <el-pagination
                            v-model:current-page="currentPage"
                            v-model:page-size="currentPageSize"
                            :total="pageTotal"
                            :page-sizes="pagePagination"
                            background
                            :pager-count="7"
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            layout="prev, pager, next, jumper,sizes,total"
                        ></el-pagination>
                    </div>
                </el-main>
            </el-container>
            <!-- 用户新增页面 -->
            <el-dialog v-model="visibleParam" title="新增账户" width="500" :before-close="handleCloseParam">
                <el-form
                    ref="formRef"
                    :inline="true"
                    label-width="auto"
                    :model="formUserAdd"
                    :rules="rules"
                    style="padding: 24px 40px; font-size: 14px; line-height: 1.5; word-wrap: break-word; font-size: 20px"
                >
                    <el-form-item label="账户名称:" prop="account">
                        <el-input v-model="formUserAdd.account" placeholder="" clearable />
                    </el-form-item>

                    <el-form-item label="账户密码:" prop="password">
                        <el-input v-model="formUserAdd.password" placeholder="" type="password" show-password clearable />
                    </el-form-item>
                    <el-form-item label="职员名称:" prop="userName">
                        <el-input v-model="formUserAdd.userName" placeholder="" clearable />
                    </el-form-item>
                    <el-form-item label="职员邮箱:" prop="email">
                        <el-input v-model="formUserAdd.email" placeholder="" clearable />
                    </el-form-item>
                    <el-form-item label="联系电话:" prop="phone">
                        <el-input v-model="formUserAdd.phone" placeholder="" clearable />
                    </el-form-item>
                    <el-form-item label="角色权限:" prop="roleList">
                        <el-select v-model="formUserAdd.roleList" placeholder="选择菜单权限" multiple style="width: 240px">
                            <el-option v-for="item in allPermissionData" :key="item.id" :label="item.roleName" :value="item.id" />
                        </el-select>
                    </el-form-item>

                    <avatar @selectAvatar="selectAddName">
                        <template #randerData>
                            <el-form-item label="头像选择:" prop="profilePicture">
                                <el-input v-model="formUserAdd.profilePicture" placeholder="" clearable></el-input>
                            </el-form-item>
                        </template>
                    </avatar>
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="visibleParam = false"> 取消 </el-button>
                        <el-button type="primary" @click="addOnSubmit">提交</el-button>
                    </div>
                </template>
            </el-dialog>
            <!-- 用户修改页面 -->
            <el-dialog v-model="visibleParamUpData" title="查看账户" width="500" :before-close="handleCloseParamUp">
                <el-form
                    ref="formRef"
                    :inline="true"
                    label-width="auto"
                    :model="formUserUpData"
                    :rules="rules"
                    style="padding: 24px 40px; font-size: 14px; line-height: 1.5; word-wrap: break-word; font-size: 20px"
                >
                    <el-form-item label="账户名称:" prop="account">
                        <el-input v-model="formUserUpData.account" placeholder="" clearable />
                    </el-form-item>

                    <el-form-item label="账户密码:">
                        <el-space>
                            <el-button @click="showPwd">重置密码</el-button>
                        </el-space>
                    </el-form-item>
                    <el-form-item label="职员名称:" prop="userName">
                        <el-input v-model="formUserUpData.userName" placeholder="" clearable />
                    </el-form-item>
                    <el-form-item label="职员邮箱:" prop="email">
                        <el-input v-model="formUserUpData.email" placeholder="" clearable />
                    </el-form-item>
                    <el-form-item label="联系电话:" prop="phone">
                        <el-input v-model="formUserUpData.phone" placeholder="" clearable />
                    </el-form-item>

                    <el-form-item label="角色权限:" prop="roleList">
                        <el-select v-model="formUserUpData.roleList" placeholder="选择菜单权限" multiple style="width: 240px">
                            <el-option v-for="item in allPermissionData" :key="item.id" :label="item.roleName" :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <avatar @selectAvatar="selectUpdataName">
                        <template #randerData>
                            <el-form-item label="头像选择:" prop="profilePicture">
                                <el-input v-model="formUserUpData.profilePicture" placeholder="" clearable></el-input>
                            </el-form-item>
                        </template>
                    </avatar>
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="visibleParamUpData = false"> 取消 </el-button>
                        <el-button type="primary" @click="upDataOnSubmit">提交</el-button>
                    </div>
                </template>
            </el-dialog>
            <!-- 删除确认弹框 -->
            <el-dialog v-model="userDeleteDialog" title="操作提示" width="500" :before-close="handleCloseDelete">
                <span>确定是否删除?</span>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="userDeleteDialog = false">取消</el-button>
                        <el-button type="primary" @click="userDeleteDialog1"> 确定 </el-button>
                    </div>
                </template>
            </el-dialog>
            <!-- 修改密码弹框 -->
            <el-dialog v-model="passWordDialog" title="修改密码" width="500" :before-close="handleClosePassWord">
                <el-form
                    ref="ChangePasswordFrom"
                    :inline="true"
                    label-width="auto"
                    :model="passWordProp"
                    :rules="passWordRules"
                    style="padding: 24px 40px; font-size: 14px; line-height: 1.5; word-wrap: break-word; font-size: 20px"
                >
                    <el-form-item label="新密码:" prop="newPassword">
                        <el-input v-model="passWordProp.newPassword" type="password" show-password placeholder="请输入新密码" clearable />
                    </el-form-item>
                    <el-form-item label="新密码确认:" prop="repeatPassword">
                        <el-input v-model="passWordProp.repeatPassword" type="password" show-password placeholder="请再次输入新密码" clearable />
                    </el-form-item>
                </el-form>

                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="passWordUpdata">保存修改</el-button>
                        <el-button type="primary" @click="passWordDialog = false"> 取消 </el-button>
                    </div>
                </template>
            </el-dialog>
        </el-container>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { Search, CirclePlusFilled } from '@element-plus/icons-vue'
import { userQuery, userUpdate, userDelete, userAdd, userList, allRoleQuery } from '/@/api/backend/index'
import { ElTable, ElMessage, FormRules } from 'element-plus'
import type Node from 'element-plus/es/components/tree/src/model/node'
import Avatar from '/@/views/backend/auth/userInfo/avatar.vue'

const input2 = ref('')
interface Tree {
    label: string
    children?: Tree[]
    id: string
}

// 用户左边树
const treeQuery = reactive({
    parentOrgId: '',
})

const userData = ref()
const treeRefUserList = ref()
const getTree = () => {
    console.log(treeQuery, 'treeQuery')

    userList(treeQuery).then((res) => {
        console.log(res.data, '树用户111')
        userData.value = res.data
        nextTick(() => {
            treeRefUserList.value?.setCurrentKey(res.data[0]?.id!, false)
            formQuery.orgId = res.data[0].id
            RyUserQuery(formQuery)
            formQuery1.orgId = res.data[0].id
        })
    })
}

onMounted(() => {
    getTree()
    allPermission()
})

const formQuery = reactive({
    orgId: '',
    recursive: false,
    pageSize: 10,
    pageNum: 1,
})

const treeId = ref()

const handleNodeClick = (data: Tree) => {
    console.log(data.id, 'data')

    treeId.value = data.id
    formQuery.orgId = data.id
    console.log(formQuery, 444444444)
    RyUserQuery(formQuery)
}

const loadNode = (node: Node, resolve: (data: Tree[]) => void) => {
    if (node.level === 0) {
        return resolve([])
    }

    const treeQuery = reactive({
        parentOrgId: node.data.id,
    })

    userList(treeQuery)
        .then((res) => {
            console.log(res, '树')
            // userData.value = res.data
            return resolve(res.data)
        })
        .catch((err) => {
            console.log(err)
        })
}

const defaultProps = {
    children: 'children',
    label: 'name',
}

// 用户查询
interface userQuery {
    // rows?: any[]
}
const tableData = ref()
const RyUserQuery = (data: any) => {
    userQuery(data).then((res) => {
        if (res.code == 200) {
            console.log(res, 'res111')
            tableData.value = res.rows
            pageTotal.value = res.total
        } else {
            ElMessage.error({
                message: res.msg,
                type: 'error',
            })
        }
    })
}

interface User {
    date: string
    name: string
    address: string
}

const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref<User[]>([])

const handleSelectionChange = (val: User[]) => {
    multipleSelection.value = val
}

// 用户搜索
const formQuery1 = reactive({
    userName: '',
    orgId: '',
    pageSize: 10,
    pageNum: 1,
})
const userFromQuery = () => {
    formQuery1.userName = input2.value
    formQuery1.orgId = treeId.value
    RyUserQuery(formQuery1)
}

// 用户增加
const visibleParam = ref(false)
interface RuleUser {
    account: string
    password: string
    userName: string
    email: string
    phone: string
    orgId: string
    roleList: string[]
}
const formUserAdd = reactive({
    account: '',
    password: '',
    userName: '',
    email: '',
    phone: '',
    orgId: '',
    roleList: [],
    profilePicture: '',
})
const rules = reactive<FormRules<RuleUser>>({
    account: [
        {
            required: true,
            message: '用户名不能为空',
            trigger: 'blur',
        },
    ],
})
const addUserFromData = () => {
    visibleParam.value = true
    formUserAdd.account = ''
    formUserAdd.userName = ''
    formUserAdd.email = ''
    formUserAdd.phone = ''
    formUserAdd.orgId = ''
    formUserAdd.roleList = []
    formUserAdd.profilePicture = ''
}

const handleCloseParam = (data: any) => {
    visibleParam.value = false
    console.log(data)
}
const formRef = ref()
const addOnSubmit = () => {
    formRef.value.validate((valid: any) => {
        if (valid) {
            visibleParam.value = false
            formUserAdd.orgId = treeId.value
            console.log(formUserAdd, treeId.value, 'formUserAdd')

            userAdd(formUserAdd).then((res) => {
                if (res.code == 200) {
                    console.log(res, '新增')
                    formQuery.orgId = treeId.value
                    RyUserQuery(formQuery)
                } else {
                    ElMessage.error({
                        message: res.msg,
                        type: 'error',
                    })
                }
            })
        }
    })
}

// 页面修改
const visibleParamUpData = ref(false)

const formUserUpData = reactive({
    id: '',
    account: '',
    userName: '',
    password: '',
    email: '',
    phone: '',
    orgId: '',
    roleList: [],
    profilePicture: '',
})
const viewUsers = (data: any) => {
    console.log(data, '页面修改数据1')
    formRef.value?.resetFields()
    visibleParamUpData.value = true
    formUserUpData.id = data.row.id
    formUserUpData.account = data.row.account
    formUserUpData.password = ''
    formUserUpData.userName = data.row.userName
    formUserUpData.email = data.row.email
    formUserUpData.phone = data.row.phone
    formUserUpData.orgId = data.row.orgId
    formUserUpData.roleList = data.row.roleList.map((item: any) => {
        return item.id
    })
    formUserUpData.profilePicture = data.row.profilePicture
}
const upDataOnSubmit = () => {
    formRef.value.validate((valid: any) => {
        if (valid) {
            console.log(formUserUpData, formUserUpData.password, 'formUserUpData')

            userUpdate(formUserUpData).then((res) => {
                if (res.code == 200) {
                    console.log(res, '修改成功')
                    // ElMessage({
                    //     message: res.msg,
                    // })
                    RyUserQuery(formQuery)
                } else {
                    ElMessage.error({
                        message: res.msg,
                        type: 'error',
                    })
                }
            })
            visibleParamUpData.value = false
        }
    })
}

const handleCloseParamUp = () => {
    visibleParamUpData.value = false
}

// 页面删除
const userListDelete = reactive({
    id: '',
})
const userFromDelete = (data: any) => {
    userDeleteDialog.value = true
    userListDelete.id = data.row.id
}

const userDeleteDialog = ref(false)

const handleCloseDelete = () => {
    userDeleteDialog.value = false
}

const userDeleteDialog1 = () => {
    userDeleteDialog.value = false
    userDelete(userListDelete).then((res) => {
        if (res.code == 200) {
            setTimeout(() => {
                ElMessage({
                    message: res.msg,
                    type: 'success',
                })
            }, 1000)
            formQuery.orgId = treeId.value
            console.log(formQuery, 'formQuery')
            RyUserQuery(formQuery)
        } else {
            ElMessage.error({
                message: res.msg,
                type: 'error',
            })
        }
    })
}

// 用户权限
const allPermissionData = ref()
// 用户权限
const roleName = {
    roleName: '',
}
const allPermission = () => {
    allRoleQuery(roleName).then((res) => {
        console.log(res.rows, 'resdata')
        allPermissionData.value = res.rows
        console.log(allPermissionData.value, '89898989111')
    })
}

//修改密码弹框
const passWordDialog = ref(false)
const passWordProp = reactive({
    newPassword: '',
    repeatPassword: '',
})

const passWordRules = {
    newPassword: [
        {
            validator: (rule: any, value: any, callback: any) => {
                if (value === '') {
                    callback(new Error('密码不能为空'))
                } else if (value && passWordProp.repeatPassword && value !== passWordProp.repeatPassword) {
                    callback(new Error('两次输入的密码不匹配'))
                } else {
                    callback()
                }
            },
            trigger: 'blur',
            required: true,
        },
    ],
    repeatPassword: [
        {
            validator: (rule: any, value: any, callback: any) => {
                if (value === '') {
                    callback(new Error('密码不能为空'))
                } else if (value && passWordProp.newPassword && value !== passWordProp.newPassword) {
                    callback(new Error('两次输入的密码不匹配'))
                } else {
                    callback()
                }
            },
            required: true,
            trigger: 'blur',
        },
    ],
}
const handleClosePassWord = () => {
    passWordDialog.value = false
}

const showPwd = () => {
    passWordDialog.value = true
}
const ChangePasswordFrom = ref()
const changePassWordData = reactive({
    id: formUserUpData.id,
    oldPassword: passWordProp.newPassword,
})
const passWordUpdata = () => {
    ChangePasswordFrom.value.validate((valid: any) => {
        if (valid) {
            // userChangePassword(changePassWordData)
            //     .then((res) => {
            //         if (res.code == 200) {
            //             ElMessage.success('修改成功')
            //             passWordDialog.value = false
            //         } else {
            //             ElMessage.error(res.msg)
            //         }
            //     })
            //     .catch(() => {
            //         ElMessage.error('修改失败')
            //     })
            formUserUpData.password = passWordProp.newPassword
            passWordDialog.value = false
        }
    })
}

// 新增页面头像接受
const selectAddName = (data: string) => {
    formUserAdd.profilePicture = data
}

// 修改页面头像接受
const selectUpdataName = (data: string) => {
    formUserUpData.profilePicture = data
}
// 分页
const pagePagination = [5, 10, 20, 30]
const currentPage = ref(1)
const currentPageSize = ref(pagePagination[0])
const handleSizeChange = (val: number) => {
    formQuery.pageSize = val
    RyUserQuery(formQuery)
}
const handleCurrentChange = (val: number) => {
    formQuery.pageNum = val
    RyUserQuery(formQuery)
}
const pageTotal = ref(0)
</script>

<style scoped lang="scss">
.el-row {
    margin-bottom: 20px;
    width: 99%;
    height: 823px;
}
.el-row:last-child {
    margin-bottom: 0;
}
.el-col {
    // border-radius: 4px;
    background-color: #fff;
}
@mixin searchInput($value) {
    margin-right: $value;
    width: 220px;
    height: 40px;
}
$defaultHeaderHeight: 60px;
$defaultMainHeight: calc(100% - 60px);
$paginationHeight: 32px;
.ba-user-container {
    width: 100%;
    height: 100%;
    // background-color: #fff;
    .defaultContainer {
        height: 100%;
        .defaultAside {
            width: 260px;
            height: 100%;
            border-right: 1px solid #eaebed;
            .treeHeader {
                display: flex;
                align-items: center;
                justify-content: center;
                height: $defaultHeaderHeight;
                .searchInput {
                    @include searchInput(0);
                }
            }
            .treeMain {
                height: $defaultMainHeight;
                .treePart {
                    height: 100%;
                }
            }
        }
        .defaultMainContainer {
            height: 100%;
            .defaultHeader {
                display: flex;
                justify-content: space-between;
                align-items: center;
                height: $defaultHeaderHeight;
                .searchPart {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                }
                .defaultBtn {
                    width: 88px;
                    height: 40px;
                }
                .searchInput {
                    @include searchInput(10px);
                }
            }
            .defaultMain {
                height: $defaultMainHeight;
                .tablePart {
                    height: calc(100% - $paginationHeight);
                }
                .tableOperate {
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    a {
                        margin: 5px;
                        color: #0064aa;
                        font-weight: 600;
                        &:hover {
                            cursor: pointer;
                        }
                    }
                }
            }
        }
    }
}
</style>
