<template>
    <hc-body split>
        <template #left>
            <hc-card title="部门树" scrollbar>
                <template #extra>
                    <el-button hc-btn type="primary" :disabled="isNullES(searchForm.deptId)" @click="clearSearchDeptId">清空选择</el-button>
                </template>
                <hc-lazy-tree ref="lazyTreeRef" :is-root-expand="false" :h-props="treeProps" tree-key="id" @load="treeLoadNode" @node-tap="treeNodeTap">
                    <template #default="{ node }">{{ node.label }}</template>
                </hc-lazy-tree>
            </hc-card>
        </template>
        <hc-card w-to="1800">
            <template #headerToSearch>
                <div class="w-140px">
                    <el-select v-model="searchForm.type" placeholder="用户平台" filterable clearable block>
                        <el-option v-for="item in userTypeData" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </div>
                <div class="ml-2 w-340px">
                    <hc-search-input v-model="searchFormName" placeholder="请输入关键字" @search="searchClick">
                        <template #prepend>
                            <el-select v-model="searchFormType" placeholder="类型" clearable style="width: 100px">
                                <el-option label="登录账号" value="account" />
                                <el-option label="用户姓名" value="realName" />
                            </el-select>
                        </template>
                    </hc-search-input>
                </div>
            </template>
            <template #extraToHeader>
                <el-button hc-btn type="primary" @click="addUserClick">新增</el-button>
                <el-button hc-btn type="danger" @click="delUserClick">删除</el-button>
                <el-button hc-btn type="info" @click="roleUserClick">角色配置</el-button>
                <el-button hc-btn type="warning" @click="resetPasswordClick">密码重置</el-button>
                <!-- el-button hc-btn type="info">平台配置</el-button -->
                <el-button hc-btn type="danger" @click="lockUserClick">账号封禁</el-button>
                <el-button hc-btn type="success" @click="unlockUserClick">账号解封</el-button>
                <el-button hc-btn type="success" plain>导入</el-button>
                <el-button hc-btn type="warning" plain>导出</el-button>
            </template>
            <hc-table
                :column="tableColumn" :datas="tableData" :loading="tableLoading" :index-style="{ width: 60 }"
                is-check :check-style="{ width: 29 }" @selection-change="tableCheckChange"
            >
                <template #action="{ row }">
                    <el-link type="warning" @click="editRowClick(row)">修改</el-link>
                    <el-link v-del-com:[delRowClick]="row" type="danger">删除</el-link>
                </template>
            </hc-table>
            <template #action>
                <hc-pages :pages="searchForm" @change="pageChange" />
            </template>
        </hc-card>
        <!-- 新增编辑 -->
        <HcDataDialog v-model="isUserDataShow" :info="userItem" @finish="getTableData" />
        <!-- 角色配置 -->
        <HcRoleDialog v-model="isUserRoleShow" :users="userIds" :roles="userRoles" @finish="getTableData" />
    </hc-body>
</template>

<script setup>
import { nextTick, onActivated, ref } from 'vue'
import { useRoute } from 'vue-router'
import { HcDelMsg, HcFirmMsg } from 'hc-vue3-ui'
import { getDictionaryData } from '~uti/tools'
import { arrToId, getArrValue, getObjValue, isNullES } from 'js-fast-way'
import HcDataDialog from './modules/user/data.vue'
import HcRoleDialog from './modules/user/role.vue'
import deptApi from '~api/system/dept'
import mainApi from '~api/system/user'

//初始组合式
const useRoutes = useRoute()

onActivated(()=> {
    getUserTypeData()
    searchClick()
    setUseRoutes()
})

const setUseRoutes = async () => {
    const query = useRoutes.query
    const { type } = getObjValue(query)
    await nextTick()
    if (type === 'add') {
        addUserClick()
    }
}

//搜索表单
const searchFormType = ref('account')
const searchFormName = ref('')
const searchForm = ref({ deptId: null, current: 1, size: 30, total: 0 })

//获取用户平台
const userTypeData = ref([])
const getUserTypeData = async () => {
    userTypeData.value = await getDictionaryData('user_type')
}

//数据格式
const lazyTreeRef = ref(null)
const treeProps = {
    label: 'title',
    children: 'children',
    isLeaf: (item) => {
        return !item.hasChildren
    },
}
const treeLoadNode = async ({ item, level }, resolve) => {
    const parentId = level === 0 ? 0 : item.id
    const { data } = await deptApi.getDeptLazyTree(parentId)
    resolve(getArrValue(data))
}

//树节点被点击
const treeNodeTap = ({ data }) => {
    searchForm.value.deptId = data.id
    searchClick()
}

//清空树节点选择
const clearSearchDeptId = () => {
    searchForm.value.deptId = null
    lazyTreeRef.value?.treeRef?.setCurrentKey(null)
    searchClick()
}

//搜索
const searchClick = () => {
    searchForm.value.current = 1
    getTableData()
}

//分页
const pageChange = ({ current, size }) => {
    searchForm.value.current = current
    searchForm.value.size = size
    getTableData()
}

//表格数据
const tableColumn = ref([
    { key: 'account', name: '登录账号', width: 140, align: 'center' },
    { key: 'tenantName', name: '所属租户', width: 100, align: 'center' },
    { key: 'realName', name: '用户姓名', width: 100, align: 'center' },
    { key: 'roleName', name: '所属角色', width: 180, align: 'center' },
    { key: 'deptName', name: '所属部门' },
    { key: 'userTypeName', name: '用户平台' },
    { key: 'action', name: '操作', width: 100, align: 'center' },
])
const tableData = ref([])

//获取用户数据
const tableLoading = ref(false)
const getTableData = async () => {
    tableData.value = []
    tableLoading.value = true
    const form = {
        ...searchForm.value,
        total: null,
    }
    if (searchFormName.value) {
        form[searchFormType.value] = searchFormName.value
    }
    const { data } = await mainApi.page(form)
    tableLoading.value = false
    tableData.value = getArrValue(data?.records)
    searchForm.value.total = data?.total ?? 0
}

//表格被选择
const tableCheckKeys = ref([])
const tableCheckChange = (rows) => {
    tableCheckKeys.value = rows
}

//新增修改用户
const isUserDataShow = ref(false)
const userItem = ref({})

//新增用户
const addUserClick = () => {
    userItem.value = {}
    isUserDataShow.value = true
}

//修改账号
const editRowClick = (row) => {
    userItem.value = row
    isUserDataShow.value = true
}

//删除账号
const delRowClick = async ({ item }, resolve) => {
    await delUserData(item.id)
    resolve()
}

//批量删除
const delUserClick = () => {
    const rows = tableCheckKeys.value
    if (rows.length <= 0) {
        window.$message.warning('请先勾选要删除的用户')
        return
    }
    HcDelMsg(async (resolve) => {
        await delUserData(arrToId(rows, 'id'))
        resolve() //关闭弹窗的回调
    })
}

//删除用户
const delUserData = async (id) => {
    const { isRes } = await mainApi.del(id)
    if (!isRes) return
    window.$message.success('删除成功')
    getTableData().then()
}

//角色配置
const userRoles = ref([])
const userIds = ref([])
const isUserRoleShow = ref(false)
const roleUserClick = () => {
    const rows = tableCheckKeys.value
    if (rows.length <= 0) {
        window.$message.warning('请先勾选要操作的用户')
        return
    }
    //处理数据
    let newRoleUser = '', users = []
    for (let i = 0; i < rows.length; i++) {
        users.push(rows[i].id)
        if (isNullES(newRoleUser)) {
            newRoleUser = rows[i].roleId || ''
        } else {
            newRoleUser += ',' + rows[i].roleId || ''
        }
    }
    userIds.value = users
    //转为数组以及数组去重
    const roleUser = newRoleUser.split(',')
    userRoles.value = Array.from(new Set(roleUser))
    isUserRoleShow.value = true
}

//重置密码
const resetPasswordClick = () => {
    const rows = tableCheckKeys.value
    if (rows.length <= 0) {
        window.$message.warning('请先勾选要操作的用户')
        return
    }
    HcFirmMsg({
        title: '操作确认',
        text: '确认将密码重置为123456吗？',
    }, async (resolve) => {
        const ids = arrToId(rows)
        const { isRes } = await mainApi.resetPassword(ids)
        resolve() //关闭弹窗的回调
        if (!isRes) return
        window.$message.success('重置成功')
    })
}

//账号封禁
const lockUserClick = () => {
    const rows = tableCheckKeys.value
    if (rows.length <= 0) {
        window.$message.warning('请先勾选要操作的用户')
        return
    }
    HcFirmMsg(async (resolve) => {
        const ids = arrToId(rows)
        const { isRes } = await mainApi.lock(ids)
        resolve() //关闭弹窗的回调
        if (!isRes) return
        window.$message.success('操作成功')
    })
}

//账号解禁
const unlockUserClick = () => {
    const rows = tableCheckKeys.value
    if (rows.length <= 0) {
        window.$message.warning('请先勾选要操作的用户')
        return
    }
    HcFirmMsg(async (resolve) => {
        const ids = arrToId(rows)
        const { isRes } = await mainApi.unlock(ids)
        resolve() //关闭弹窗的回调
        if (!isRes) return
        window.$message.success('操作成功')
    })
}
</script>
