<template>
    <div class="container-box">
        <div class="header-bar">
            <h2>用户管理</h2>
            <div class="header-actions">
                <el-button type="primary" @click="handleAddUser">
                    <el-icon>
                        <Plus />
                    </el-icon>
                    添加用户
                </el-button>
                <el-button @click="refresh">
                    <el-icon>
                        <Refresh />
                    </el-icon>
                    刷新
                </el-button>
            </div>
        </div>

        <el-divider></el-divider>

        <!-- 用户列表表格 -->
        <el-table :data="users" style="width: 100%" v-loading="loading">
            <el-table-column prop="id" label="ID" align="center" fixed="left" width="80" />
            <el-table-column prop="account" label="账号" align="center" width="120" />
            <el-table-column prop="name" label="姓名" align="center" width="120">
                <template #default="scope">
                    <span class="name-link" @click="handlePreview(scope.row)">{{ scope.row.name }}</span>
                </template>
            </el-table-column>
            <el-table-column label="隶属单位" align="center">
                <template #default="scope">
                    {{ scope.row.affiliate_unit_name || scope.row.affiliate_unit || "-" }}
                </template>
            </el-table-column>
            <el-table-column label="部门" align="center">
                <template #default="scope">
                    {{ scope.row.department_name || scope.row.department || "-" }}
                </template>
            </el-table-column>
            <el-table-column prop="position" label="职位" align="center" />
            <el-table-column prop="account_status" label="账号状态" width="80" align="center">
                <template #default="scope">
                    <el-tag :type="getStatusValue(scope.row) === 1 ? 'success' : 'danger'">{{
                        getStatusValue(scope.row) === 1 ? "启用" : getStatusValue(scope.row) === 2 ? "离职" : "禁用"
                        }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="240" align="center" fixed="right">
                <template #default="scope"><!--  -->
                    <el-button size="small" @click="handlePreview(scope.row)">查看</el-button>
                    <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button size="small" type="warning" @click="handleChangePassword(scope.row)">
                        修改密码
                    </el-button>
                    <el-button v-if="scope.row.username !== 'admin' && scope.row.id !== 1" size="small" type="danger"
                        @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-bar">
            <el-pagination :current-page="page" :page-size="pageSize" :total="total" @current-change="handlePageChange"
                layout="total, prev, pager, next" />
        </div>

        <!-- 查看弹窗 -->
        <View ref="viewRef" />

        <!-- 修改密码弹窗 -->
        <ChangePass ref="changePassRef" @submit="fetchData" />

        <!-- 编辑弹窗 -->
        <Edit ref="editRef" @submit="fetchData" />
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Refresh } from "@element-plus/icons-vue";
import { getEmployeeList, deleteEmployee } from "@/api/erp";
import Edit from "./components/edit.vue";
import View from "./components/view.vue";
import ChangePass from "./components/changepass.vue";
import { useAuthStore } from "@/stores/auth";

const users = ref<any[]>([]);
const loading = ref(false);
const page = ref(1);
const pageSize = ref(10);
const total = ref(0);
const editRef = ref<any>(null);
const viewRef = ref<any>(null);
const changePassRef = ref<any>(null);

const getStatusValue = (row: any) => {
    const status = row.account_status ?? row.status ?? 0;
    return Number(status);
};

const authStore = useAuthStore();
const tenantId = (authStore.user as any)?.tid;

// console.log(tenantId);

// 获取列表数据
const fetchData = async (currentTenantId = tenantId) => {
    loading.value = true;
    try {
        const res = await getEmployeeList(currentTenantId);
        users.value = res.data || res || [];
        total.value = users.value.length;
    } catch (e: any) {
        ElMessage.error(e?.message || "获取列表失败");
    } finally {
        loading.value = false;
    }
};

// 刷新
const refresh = () => {
    fetchData(tenantId);
};

// 添加用户
const handleAddUser = () => {
    editRef.value?.openAdd();
};

// 编辑用户
const handleEdit = (row: any) => {
    editRef.value?.openEdit(row);
};

const handleChangePassword = (row: any) => {
    changePassRef.value?.openChangePass(row);
};

// 查看
const handlePreview = (row: any) => {
    viewRef.value?.openView(row);
};

// 删除用户
const handleDelete = async (row: any) => {
    try {
        await ElMessageBox.confirm(`确定删除用户 "${row.name}" 吗？`, "提示", {
            type: "warning",
        });
        await deleteEmployee(row.id);
        ElMessage.success("删除成功");
        fetchData(tenantId);
    } catch (e: any) {
        if (e !== "cancel") {
            ElMessage.error(e?.message || "删除失败");
        }
    }
};

// 分页变化
const handlePageChange = (val: number) => {
    page.value = val;
    fetchData(tenantId);
};

onMounted(() => {
    fetchData(tenantId);
});
</script>

<style lang="less" scoped>
.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    span {
        font-size: 1.4rem;
        font-weight: 700;
    }
}

:deep(.el-alert__title) {
    color: #f56c6c !important;
}

.name-link {
    color: #3973ff;
    cursor: pointer;
    text-decoration: none;
    transition: color 0.3s;

    &:hover {
        color: #66b1ff;
        text-decoration: underline;
    }
}
</style>
