<template>
    <!-- 用户管理 -->
    <div class="app-container">
        <TableModel :formLabel="formLabel" :showOperation="true" :showRightTools="true" ref="userTableRef"
            :columnsList="columnsList" :request-api="listUser">
            <template #form="{ queryParams }">
                <el-form-item prop="deptId" style="width: 240px;">
                    <treeselect v-model="queryParams.deptId" :options="treeDataList" placeholder="请选择部门" value-key="id"
                        :disable-branch-nodes="false" noChildrenText="没有数据了" noOptionsText="没有数据了" noResultsText="没有搜索结果"
                        />
                </el-form-item>
            </template>
            <template slot="btn">
                <el-button plain size="mini" type="primary" icon="el-icon-plus" v-hasPermi="['system:user:add']"
                    @click="handleAdd">
                    新增
                </el-button>
            </template>
            <template slot="deptName" slot-scope="{ data }">
                <span>{{ data.dept.deptName || '--' }}</span>
            </template>
            <template slot="roleName" slot-scope="{ data }">
                <span>{{ data.roles[0].roleName || '--'}}</span>
            </template>
            <template slot="handle" slot-scope="{ data }">
                <el-button plain size="mini" type="primary" icon="el-icon-edit" v-hasPermi="['system:user:edit']"
                    @click="handleUpdate(data)">
                    修改
                </el-button>
                <el-button plain size="mini" type="danger" icon="el-icon-delete" v-hasPermi="['system:user:remove']"
                    @click="handleDelete(data)" v-if="!data.admin">
                    删除
                </el-button>
                <el-button plain size="mini" style="color: #039088"
                    @click="handleResetPwd(data)" v-hasPermi="['system:user:remove']">
                    重置密码
                </el-button>
            </template>
        </TableModel>
        <!-- 新增/编辑 -->
        <UserForm v-if="isflag" :isAdd="isAdd" :rowData="row" @handleQuery="handleQuery" :title="title"
            @closeDialog="closeDialog" @showColose="showColose" :dataForm="row" :disabled="loading" :width="600" />
    </div>
</template>

<script>
import TableModel from '@/components/TableModel'
import { columnsList, formLabel } from './config'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {
    listUser,
    delUser
} from '@/api/system/user'
import { getDeptSelectApi,getRoleSelectApi } from '@/api/select'
import UserForm from './profile/userForm'


export default {
    name: 'DataClassManage',
    components: {
        TableModel,
        UserForm,
        Treeselect
    },
    data() {
        return {
            formLabel,
            columnsList,
            listUser,
            title: "",
            isflag: false,
            isAdd: '',
            row: {},
            loading: false,
            treeDataList:[],
        }
    },

    created() {
        this.initData();
        
    },

    methods: {
        async initData() {
            await getDeptSelectApi().then(res => {
                this.treeDataList = this.convertToVueTree(res.data);
            });
            const item = this.formLabel.find(item => item.f_model === 'roleId');
            await getRoleSelectApi().then(res => {
                console.log(res.data)
                res.data.forEach(item => {
                    item.label = item.name;
                    item.value = item.id;
                });
                this.$set(item, 'f_selList', res.data)
            });
        },
        
        /** 新增按钮操作 */
        handleAdd() {
            this.title = "新增";
            this.isAdd = 'add';
            this.isflag = true;
        },
        closeDialog() {
            this.isflag = false;
        },
        showColose() {
            this.isflag = false;
        },
        /** 修改操作 */
        handleUpdate(row) {
            this.title = "修改";
            this.isAdd = 'edit';
            this.row = row;
            this.isflag = true;
        },
        /* 搜索操作 */
        handleQuery() {
            this.$refs.userTableRef.getTableList()
        },
        /** 删除操作 */
        handleDelete(row) {
            this.$modal.confirm(`是否确认删除此数据项？`).then(() => {
                // 显示加载遮罩
                this.$modal.loading("正在删除，请稍候...");
                delUser({ id: row.id }).then(res => {
                    this.$modal.closeLoading();
                    if (res.code === 200) {
                        this.$modal.msgSuccess("删除成功");
                        this.handleQuery();
                    } else {
                        this.$modal.msgError(res.msg);
                    }
                }).catch(error => {
                    this.$modal.closeLoading();
                    this.$modal.msgError(error);
                });
            }).catch(() => {
                // 用户取消删除，不需要处理
            });
        },
        // 树数据过滤 - 支持无限层级转换
        convertToVueTree(data, level = 1) {
            if (!data || !Array.isArray(data)) {
                return []
            }

            return data.map(item => {
                const node = {
                    id: item.deptId,
                    label: item.deptName,
                }

                if (item.children && Array.isArray(item.children) && item.children.length > 0) {
                    if (level < 3) {
                        const children = this.convertToVueTree(item.children, level + 1)
                        if (children.length > 0) node.children = children
                    }
                }

                return node
            })
        },
        /** 重置密码按钮操作 */
        handleResetPwd(row) {
            this.$prompt('请输入"' + row.userName + '"的新密码', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                closeOnClickModal: false,
                inputPattern:
                    /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\w\d\s]).{8,20}$/,
                inputErrorMessage:
                    '用户密码长度必须介于 8 和 20 之间，且包含大小写字母、数字和特殊字符',
                inputValidator: (value) => {
                    if (/<|>|"|'|\||\\/.test(value)) {
                        return '不能包含非法字符：< > " \' \\\ |'
                    }
                },
            })
                .then(({ value }) => {
                    resetUserPwd(row.userId, value).then((response) => {
                        this.$modal.msgSuccess('修改成功，新密码是：' + value)
                    })
                })
                .catch(() => {})
        },
    },
}
</script>
