<script setup>
import { getMainList } from '@/api/system/depart.js'
import { getRoleList } from '@/api/system/role'
import {
    getUserList,
    addUser,
    modUser,
    byUserIdfnRole,
    byUserIduPRole,
    delUser,
    restPwdUser
} from '@/api/system/user.js'
const { proxy } = getCurrentInstance()

//部门树
const deptName = ref('')
const deptOptions = ref([])
const deptOptionsEdit = ref([])
const filterNode = (value, data) => {
    if (!value) return true
    return data.name.indexOf(value) !== -1
}
watch(deptName, val => {
    proxy.$refs['deptTreeRef'].filter(val)
})

//查询
const params = ref({
    deptId: null,
    page: 1,
    size: 20
})
const total = ref(0)
const tableData = ref([])
//用户列表
function getUserListData() {
    getUserList(params.value).then(res => {
        tableData.value = res.data.records
        total.value = res.data.total
    })
}
//查询按钮
function searchUserListBtn() {
    console.log(params.value)
    getUserListData()
}
//重置
function resetParamsBtn() {
    params.value = {
        deptId: null,
        page: 1,
        size: 20
    }
    getUserListData()
}
function sizeChange(e) {
    params.value.size = e
    getUserListData()
}

function currentChange(e) {
    params.value.page = e
    getUserListData()
}
//部门点击
function treeNodeClick(value) {
    params.value.deptId = value.id
    getUserListData()
}
//部门数据
function getDeptTreeData() {
    getMainList().then(res => {
        deptOptions.value = res.data
        deptOptionsEdit.value = res.data
    })
}
//角色数据
const roleData = ref([])
function getRoleListData() {
    getRoleList({
        page: 1,
        size: 100000
    }).then(res => {
        roleData.value = res.data.records
    })
}
getDeptTreeData()
getUserListData()
getRoleListData()

//编辑

function filterMethod(value) {
    deptOptionsEdit.value = [...deptOptions].filter(item =>
        item.name.includes(value)
    )
}

const form = ref({
    userName: null,
    depId: null,
    roleIds: null,
    realName: null,
    phone: null,
    email: null
})
const rules = ref({
    depId: [{ required: true, message: '部门不能为空', trigger: 'blur' }],
    roleIds: [{ required: true, message: '角色不能为空', trigger: 'blur' }],
    userName: [{ required: true, message: '用户名不能为空', trigger: 'blur' }]
})

function reset() {
    form.value = {
        userName: null,
        depId: null,
        roleIds: null,
        realName: null,
        phone: null,
        email: null
    }
    if (proxy.$refs['userRef']) {
        proxy.$refs['userRef'].resetFields()
    }
}

const title = ref('')
const open = ref(false)

function submitForm() {
    proxy.$refs['userRef'].validate(valid => {
        if (valid) {
            if (form.value.id != undefined) {
                modUser(form.value).then(res => {
                    if (res.code == 200) {
                        byUserIduPRole(form.value.id, {
                            roleIds: form.value.roleIds.join(',')
                        }).then(result => {
                            if (result.code == 200) {
                                getUserListData()
                                open.value = false
                                ElMessage({
                                    message: res.msg,
                                    type: 'success'
                                })
                            } else {
                                ElMessage({
                                    message: res.msg,
                                    type: warning
                                })
                            }
                        })
                    } else {
                        ElMessage({
                            message: res.msg,
                            type: warning
                        })
                    }
                })
            } else {
                addUser(form.value).then(res => {
                    if (res.code == 200) {
                        byUserIduPRole(res.data.id, {
                            roleIds: form.value.roleIds.join(',')
                        }).then(result => {
                            if (result.code == 200) {
                                getUserListData()
                                open.value = false
                                ElMessage({
                                    message: res.msg,
                                    type: 'success'
                                })
                            } else {
                                ElMessage({
                                    message: res.msg,
                                    type: warning
                                })
                            }
                        })
                    } else {
                        ElMessage({
                            message: res.msg,
                            type: warning
                        })
                    }
                })
            }
        } else {
            console.log('检验不通过')
        }
    })
}
function cancel() {
    open.value = false
    reset()
}
function addUserBtn() {
    open.value = true
    title.value = '新增'
}
function modUserBtn(row) {
    console.log(row)
    reset()
    let { userName, deptId, name, mobile, email, id } = row
    form.value = {
        userName,
        depId: deptId,
        realName: name,
        phone: mobile,
        email,
        id
    }
    byUserIdfnRole(id).then(res => {
        form.value.roleIds = res.data.map(item => item.id)
        open.value = true
        title.value = '修改'
    })
}
function delUserBtn(row) {
    ElMessageBox.confirm('是否确认删除"' + row.userName + '"?', '删除警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        delUser({ ids: row.id }).then(res => {
            console.log(res)
            if (res.code == 200) {
                getUserListData()
                ElMessage({
                    message: res.msg,
                    type: 'success'
                })
            } else {
                ElMessage({
                    message: res.msg,
                    type: warning
                })
            }
        })
    })
}
const selectionChangeData = ref([])
function selectionChange(value) {
    selectionChangeData.value = value
}
function delUserMoreBtn() {
    if (selectionChangeData.value.length <= 0) {
        ElMessage({
            message: '请先选择要删除的数据',
            type: 'warning'
        })
        return
    }
    ElMessageBox.confirm('是否确认删除?', '删除警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        let arr = []
        selectionChangeData.value.forEach(element => {
            arr.push(element.id)
        })
        delUser({ ids: arr.join(',') }).then(res => {
            console.log(res)
            if (res.code == 200) {
                getUserListData()
                ElMessage({
                    message: res.msg,
                    type: 'success'
                })
            } else {
                ElMessage({
                    message: res.msg,
                    type: warning
                })
            }
        })
    })
}

function resetUserPwdBtn(row) {
    ElMessageBox.confirm('是否确认重置"' + row.userName + '"密码?', '删除警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        restPwdUser({ id: row.id }).then(res => {
            if (res.code == 200) {
                getUserListData()
                ElMessage({
                    message: res.msg,
                    type: 'success'
                })
            } else {
                ElMessage({
                    message: res.msg,
                    type: warning
                })
            }
        })
    })
}
</script>

<template>
    <div>
        <el-card class="tjm_card_style_custom">
            <div class="tjm_card_title">查询表格</div>
            <div class="tjm_card_select">
                <div class="tjm_card_select_left">
                    <el-form
                        :inline="true"
                        :model="params"
                        label-width="80px"
                        :label-position="'left'"
                    >
                        <!-- <el-form-item label="用户编号">
                            <el-input v-model="params.code" clearable />
                        </el-form-item> -->
                        <el-form-item label="用户名称">
                            <el-input v-model="params.userName" clearable />
                        </el-form-item>
                        <el-form-item label="姓名">
                            <el-input v-model="params.realName" clearable />
                        </el-form-item>

                        <!-- <el-form-item label="创建时间">
                        <el-date-picker
                            v-model="params.date"
                            type="daterange"
                            placeholder="Pick a date"
                            clearable
                        />
                        </el-form-item>
                        <el-form-item label="用户状态">
                        <el-select
                            v-model="params.status"
                            clearable
                            placeholder="请选择"
                        >
                            <el-option label="启用" value="1" />
                            <el-option label="禁用" value="2" />
                        </el-select>
                        </el-form-item> -->
                        <el-form-item>
                            <el-button type="primary" @click="searchUserListBtn">
                                <el-icon class="tjm_btn_icon_right"><tjm-icon-ep-Plus /></el-icon>
                                搜索
                            </el-button>
                            <el-button @click="resetParamsBtn">
                                <el-icon class="tjm_btn_icon_right"><tjm-icon-ep-RefreshRight /></el-icon>
                                重置
                            </el-button>
                        </el-form-item>
                    </el-form>
                </div>
            </div>
            <el-divider />
            <div class="tjm_card_tools">
                <div class="tjm_card_tools_left">
                    <el-button type="primary" @click="addUserBtn">
                        <el-icon class="tjm_btn_icon_right"><tjm-icon-ep-Plus /></el-icon>
                        新增
                    </el-button>
                    <el-button type="danger" @click="delUserMoreBtn">
                        <el-icon class="tjm_btn_icon_right"><tjm-icon-ep-delete /></el-icon>
                        批量删除
                    </el-button>
                </div>
                <!-- <div class="tjm_card_tools_right">
                    <el-button>
                        <el-icon class="tjm_btn_icon_right"><tjm-icon-ep-download /></el-icon>
                        excel导出数据
                    </el-button>
                </div> -->
            </div>
            <div class="tjm_card_table">
                <div class="tjm_card_table_left" style="height: 450px; overflow: auto">
                    <el-input
                        v-model="deptName"
                        placeholder="请输入部门名称"
                        clearable
                        prefix-icon="Search"
                    />
                        <!-- default-expand-all -->
                    <el-tree
                        :data="deptOptions"
                        :props="{ label: 'name', children: 'children' }"
                        :expand-on-click-node="false"
                        ref="deptTreeRef"
                        node-key="id"
                        highlight-current
                        @node-click="treeNodeClick"
                        :filter-node-method="filterNode"
                        style="margin-top: 6px"
                    />
                </div>
                <div class="tjm_card_table_right">
                    <el-table
                        header-cell-class-name="tjm_cart_table_header"
                        :data="tableData"
                        border
                        width="100%"
                        @selection-change="selectionChange"
                    >
                        <el-table-column type="selection" width="55" />
                        <el-table-column type="index" label="序号" width="55" />
                        <el-table-column prop="userName" label="用户名" />
                        <el-table-column prop="deptName" label="所属部门" width="240" />
                        <el-table-column prop="name" label="姓名" />
                        <el-table-column prop="mobile" label="手机号" />
                        <el-table-column prop="email" label="电子邮箱" width="240" />
                        <el-table-column prop="state" label="用户状态">
                            <template #default="scope">
                                {{ ['启用', '禁用'][scope.row.state] }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="ope" label="操作">
                            <template #default="scope">
                                <el-tooltip content="修改" placement="top">
                                    <el-button
                                        link
                                        type="primary"
                                        icon="Edit"
                                        @click="modUserBtn(scope.row)"
                                    ></el-button>
                                </el-tooltip>
                                <el-tooltip content="删除" placement="top">
                                    <el-button
                                        link
                                        type="primary"
                                        icon="Delete"
                                        @click="delUserBtn(scope.row)"
                                    ></el-button>
                                </el-tooltip>
                                <el-tooltip content="重置密码" placement="top">
                                    <el-button
                                        link
                                        type="primary"
                                        icon="Key"
                                        @click="resetUserPwdBtn(scope.row)"
                                    ></el-button>
                                </el-tooltip>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
            <div class="tjm_card_pagination">
                <el-pagination
                    background
                    layout="total,sizes,prev, pager, next,"
                    :total="total"
                    :page-sizes="[20, 30, 100]"
                    @size-change="sizeChange"
                    @current-change="currentChange"
                />
            </div>
        </el-card>

        <!-- 编辑 -->
        <el-dialog :title="title" v-model="open" width="680px" append-to-body>
            <el-form ref="userRef" :model="form" :rules="rules" label-width="100px">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="用户名" prop="userName">
                            <el-input
                                v-model="form.userName"
                                placeholder="请输入用户名"
                                clearable
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="所属部门" prop="depId">
                            <el-tree-select
                                style="width: 100%"
                                v-model="form.depId"
                                :data="deptOptions"
                                filterable
                                :props="{ value: 'id', label: 'name', children: 'children' }"
                                value-key="id"
                                placeholder="选择所属部门"
                                check-strictly
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="角色" prop="roleIds">
                            <el-select
                                v-model="form.roleIds"
                                multiple
                                placeholder="请选择角色"
                                style="width: 100%"
                            >
                                <el-option
                                    v-for="item in roleData"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="姓名" prop="realName">
                            <el-input
                                v-model="form.realName"
                                placeholder="请输入姓名"
                                clearable
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="手机号" prop="phone">
                            <el-input
                                v-model="form.phone"
                                placeholder="请输入手机号"
                                clearable
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="邮箱" prop="email">
                            <el-input v-model="form.email" placeholder="邮箱" clearable />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<style lang="scss" scoped></style>