<template>
    <div class="userManagement">
        <div class="form-header">
            <el-form :inline="true" :model="formInline" class="demo-form-inline">
                <el-form-item label="用户名称">
                    <el-input v-model="formInline.user" clearable></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="handleData()">查询</el-button>
                    <el-button type="success" icon="el-icon-plus" @click="handleAdd()">新增</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="form-box">
            <el-table :data="tableData" height="350px" style="width: 100%" :header-cell-class-name="HeaderCell" stripe
                border>
                <el-table-column label="序号" type="index" width="80" align="center">
                </el-table-column>
                <el-table-column label="用户名" align="center">
                    <template slot-scope="scope">
                        <span style="margin-left: 10px">{{ scope.row.username }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="id" align="center">
                    <template slot-scope="scope">
                        <span style="margin-left: 10px">{{ scope.row.id }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" align="center">
                    <template slot-scope="scope">
                        <span style="margin-left: 10px">{{ scope.row.createTime }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="手机号" align="center">
                    <template slot-scope="scope">
                        <span style="margin-left: 10px">{{ scope.row.phone }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="名称" align="center">
                    <template slot-scope="scope">
                        <span style="margin-left: 10px">{{ scope.row.tenantName }}</span>
                    </template>
                </el-table-column>

                <el-table-column label="状态" align="center">
                    <template slot-scope="scope">
                        <span style="margin-left: 10px">{{ scope.row.status }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="类型" align="center">
                    <template slot-scope="scope">
                        <span style="margin-left: 10px">{{ scope.row.usertype }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="284px" align="center">
                    <template slot-scope="scope">
                        <el-button style="width:94px;" size="mini" type="success" icon="el-icon-document"
                            @click="handleFP(scope.row.id)">分配角色</el-button>
                        <el-button style="width:66px; padding: 7px;" size="mini" type="warning" icon="el-icon-edit"
                            @click="handleXG(scope.row.id)">修改</el-button>
                        <el-button style="width:66px; padding: 7px;" size="mini" type="danger" icon="el-icon-delete"
                            @click="handleDE(scope.row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 第四步绑定自定义属性 -->
            <pagination :total="obj.total" @handleSize="handleSizeChange" @handleCurrent="handleCurrentChange">
            </pagination>
        </div>
        <!-- 弹出框 -->
        <el-dialog :title="title" :visible.sync="dialogFormVisible" top="30vh">
            <el-form :model="formFP" ref="formFP" :rules="rules">
                <el-form-item label="用户名称" :label-width="formLabelWidth" prop="tenantName" v-if="title == '分配角色'">
                    <el-input v-model="formFP.tenantName" autocomplete="off" :disabled="title == '分配角色'"></el-input>
                </el-form-item>
                <el-form-item label="用户名" :label-width="formLabelWidth" prop="username" v-if="title == '修改信息'">
                    <el-input v-model="formFP.username" autocomplete="off"></el-input>
                </el-form-item>
                <!--  -->
                <el-form-item label="用户名" :label-width="formLabelWidth" prop="username" v-if="title == '新增用户'">
                    <el-input v-model="formFP.username" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="手机号" :label-width="formLabelWidth" prop="phone" v-if="title == '新增用户'">
                    <el-input v-model="formFP.phone" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="所属租户" :label-width="formLabelWidth" prop="tenantId" v-if="title == '新增用户'">
                    <el-select v-model="formFP.tenantId" placeholder="请选择用户角色" style="width: 100%;">
                        <el-option v-for="item in tenantIdoptions" :key="item.id" :label="item.label" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="账号类型" :label-width="formLabelWidth" prop="usertype" v-if="title == '新增用户'">
                    <el-select v-model="formFP.usertype" placeholder="请选择账号类型" style="width: 100%;">
                        <el-option :label="'安卓'" :value="1"></el-option>
                        <el-option :label="'web'" :value="2"></el-option>
                    </el-select>
                </el-form-item>
                <!--  -->
                <el-form-item label="手机号" :label-width="formLabelWidth" prop="phone" v-if="title == '修改信息'">
                    <el-input v-model="formFP.phone" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="用户角色" :label-width="formLabelWidth" v-if="title == '分配角色'">
                    <el-select v-model="formFP.tenantType" placeholder="请选择用户角色" style="width: 100%;">
                        <el-option v-for="item in Roleoptions" :key="item.id" :label="item.label" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="handlesubmit(1)" v-if="title == '分配角色'">确 定</el-button>
                <el-button type="primary" @click="handlesubmit(2)" v-if="title == '修改信息'">确 定</el-button>
                <el-button type="primary" @click="handlesubmit(3)" v-if="title == '新增用户'">确 定</el-button>
            </div>
        </el-dialog>
    </div>



</template>
<script>
// 第一步引入组件
import pagination from "../pagination/pagination.vue";
import apiServe from "@/utils/api.js";
import axios from "axios";
export default {
    // 第二步 注册组件
    components: {
        pagination,
    },
    data() {
        return {
            tenantId: "",
            data: [],
            // 查询
            formInline: {
                user: "",
            },
            tableData: [],
            obj: {
                // 页码
                page: 1,
                // 每页多少条
                rows: 10,
                // 默认选中哪一页
                currentPage: 1,
                // 定义总条数
                total: null,
            },
            // 弹出框
            Roleoptions: [],
            tenantIdoptions: [],
            Rolevalue: '',
            title: "",
            formFP: {
                tenantName: '',
                tenantType: "",
                phone: "",
                username: "",
                tenantId: "",
                usertype: null
            },
            formLabelWidth: '120px',
            dialogFormVisible: false,
            rules: {
                phone: [
                    {
                        required: true,
                        message: '请输入手机号',  // 修正错误文案
                        trigger: 'blur'
                    },
                    {
                        pattern: /^1[3-9]\d{9}$/,  // 手机号正则
                        message: '请输入正确的手机号码',
                        trigger: 'blur'
                    }
                ],
                // 其他字段保持原有规则...
                username: [
                    { required: true, message: '请输入用户名', trigger: 'change' }
                ],
                tenantName: [
                    { required: true, message: '请输入用户名称', trigger: 'change' }
                ],
                tenantId: [
                    { required: true, message: '请选择所属租户', trigger: 'change' }
                ],
                usertype: [
                    { required: true, message: '请选择账号类型', trigger: 'change' }
                ],
            },
            // 租户id
            zuhu: "",
        }
    },
    methods: {

        // 表头单元格样式
        HeaderCell() {
            return 'HeaderCellClass';
        },

        handleData() {
            let data = {
                pageNo: this.obj.page,
                pageSize: this.obj.rows,
                tenantld: 1,
                username: this.formInline.user
            };
            apiServe.admin("get", data).then((res) => {
                // console.log(res,"获取的数据");
                // 将请求成功的数据赋值给表格
                if (res) {
                    this.data = res.data;
                    this.tableData = res.data.list;
                    this.obj.total = Number(res.data.total)
                    // console.log(this.obj.total,"获取的数据总数");

                }
            });
        },
        // 分配角色
        handleFP(id) {
            this.zuhu = id;
            this.title = "分配角色";
            this.dialogFormVisible = true;
            let Roleadminid = ""
            // 根据用户id查询角色和租户id
            apiServe.Roleid("get", { id: id }).then((res) => {
                if (res.data.tenantId) {
                    this.formFP.tenantName = res.data.username
                    this.formFP.tenantType = res.data.roleVos[0].roleName
                    Roleadminid = res.data.tenantId
                    let dataFP = {

                    };
                    let data = {
                        tenantId: Roleadminid,
                    };
                    // 根据租户id查询角色选项
                    apiServe.Roleadmin("get", data).then((res) => {
                        dataFP = res.data;
                        this.Roleoptions = dataFP.map(val => ({
                            id: val.id,
                            label: val.roleName,
                        }))

                    });
                }



            });

        },

        // 修改信息
        handleXG(id) {
            this.zuhu = id;
            this.title = "修改信息";
            this.dialogFormVisible = true;
            apiServe.Roleid("get", { id: id }).then((res) => {
                if (res.data.tenantId) {
                    this.formFP.username = res.data.username
                    this.formFP.phone = res.data.phone
                }

            });


        },

        //删除用户
        handleDE(id) {
            const token = localStorage.getItem('token');
            // console.log(token);
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                axios.delete("http://81.70.146.224:11500/users/user-manage/" + id, {
                    headers: {
                        'Authorization': `${token}`, // 将 token 放在请求头中
                    }
                }).then((res) => {
                    if (res) {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        this.handleData(); // 刷新数据
                    }
                });
            })
        },
        // 新增用户
        handleAdd() {
            this.title = '新增用户';
            this.dialogFormVisible = true;
            // 重置表单数据
            this.formFP = {
                tenantName: '',
                tenantType: "",
                phone: "",
                username: "",
                tenantId: "",
                usertype: null
            };
            // 等待 DOM 更新后重置表单验证状态
            this.$nextTick(() => {
                if (this.$refs.formFP) {
                    this.$refs.formFP.resetFields();
                }
            });
            // 获取租户选项
            apiServe.TenantXZ('get', {}).then(res => {
                this.tenantIdoptions = res.data.map(item => ({
                    id: item.id,
                    label: item.name
                }));
            });
        },
        handlesubmit(val) {
            this.$refs.formFP.validate((valid) => {
                if (!valid) {
                    console.log('error submit!!');
                    return false;
                }

                // 公共方法：显示消息并关闭弹窗
                const showMessageAndClose = (message, type = 'success') => {
                    this.$message({ message, type });
                    this.dialogFormVisible = false;
                };

                // 根据 val 的值执行不同操作
                switch (val) {
                    case 1: {// 分配角色
                        const assignData = {
                            userId: this.zuhu,
                            roleIds: [this.formFP.tenantType],
                        };
                        apiServe.RoleFP("post", assignData)
                            .then((res) => {
                                this.handleData()
                                showMessageAndClose('恭喜你，分配成功');
                                console.log(res);
                            })
                            .catch((error) => {
                                showMessageAndClose('分配失败', 'error');
                                console.error(error);
                            });
                        break;
                    }
                    case 2: {// 修改信息
                        const updateData = {
                            id: this.zuhu,
                            phone: this.formFP.phone,
                            username: this.formFP.username,
                        };
                        apiServe.RoleXG("put", updateData)
                            .then((res) => {
                                if (res.data.code === 200) {
                                    this.handleData()
                                    showMessageAndClose('恭喜你，修改成功');
                                } else {
                                    showMessageAndClose('修改失败', 'error');
                                }
                                console.log(res);
                            })
                            .catch((error) => {
                                showMessageAndClose('修改失败', 'error');
                                console.error(error);
                            });
                        break;
                    }
                    case 3: {// 新增信息
                        const createData = {
                            phone: this.formFP.phone,
                            tenantId: this.formFP.tenantId,
                            username: this.formFP.username,
                            usertype: this.formFP.usertype,
                        };
                        apiServe.RoleXZ("post", createData)
                            .then((res) => {
                                // 刷新表单
                                this.handleData()
                                console.log(res.code);
                                if (res.code === 200) {

                                    showMessageAndClose('新增成功');
                                } else {
                                    showMessageAndClose('新增失败', 'error');
                                }
                                console.log(res);
                            })
                            .catch((error) => {
                                showMessageAndClose('新增失败', 'error');
                                console.error(error);
                            });
                        break;
                    }
                    default:
                        console.error('未知的操作类型:', val);
                        break;
                }
            });
        },
        // 分页开始
        handleSizeChange(val) {
            console.log(val, "接收");
            // 当我点击每页多少条的时候赋值并重新渲染页面
            this.obj.rows = val;
            this.handleData();
        },
        handleCurrentChange(val) {
            console.log(val, "接收");
            // 当我点击页码的时候将页码赋值给变量并重新渲染页面
            this.obj.page = val;
            this.handleData();
        },
        // 分页结束

    },
    mounted() {
        // 从本地读取数据
        this.tenantId = localStorage.getItem("tenantId")
        console.log(this.tenantId)
        this.handleData()
    }
}
</script>
<style lang="scss" scoped>
.userManagement::v-deep {
    .form-header {
        box-shadow: 0 0 5px #d0d0d0;
        border-radius: 5px;
        text-align: left;
        background-color: #fff;
        padding: 10px;
        padding-left: 30px;

        .el-form-item {
            margin-bottom: 0;
        }
    }

    .form-box {
        margin-top: 10px;
        padding: 10px;
        background-color: #fff;
        box-shadow: 0 0 5px #d0d0d0;
        border-radius: 5px;
        /* // calc():高度时100%-超出的部分 */
        height: calc(100vh - 235px);


        .HeaderCellClass {
            background: #859CB7;
            color: #fff;
        }


    }

    .pagination {
        padding-top: 10px;
        text-align: center;
    }

}
</style>