<template>
    <div class="router" style="padding: 20px;">
        <el-form :inline="true">
            <el-form-item>
                <el-button type="primary" size="small" @click="handleAdd">添加用户</el-button>
            </el-form-item>
        </el-form>
        <el-table :data="tableData" border scrollbar-always-on>
            <!-- <el-table-column type="selection"></el-table-column> -->
            <el-table-column v-for="i in tableColumn" :label="i.label" :prop="i.prop" align="center">
                <template #default="scope" v-if="i.prop == 'avatar'">
                    <el-avatar :src="scope.row.avatar"></el-avatar>
                </template>
                <template #default="scope" v-if="i.prop == 'fdate'">
                    {{ moment(scope.row.fdate).format("YYYY-MM-DD hh:mm:ss") }}
                </template>
            </el-table-column>
            <!-- 设置启用禁用 -->
            <el-table-column label="是否启用" align="center">
                <template #default="scope">
                    <el-switch v-model="scope.row.enabled" @change="switchChange($event, scope.row.userId)" />
                </template>
            </el-table-column>
            <el-table-column label="操作" width="135" align="center">
                <template #default="scope">
                    <el-link type="primary" :underline="false" @click="handleEdit(scope)">编辑</el-link>
                    <el-divider direction="vertical" />
                    <el-popconfirm title="确认删除?" @confirm="handleDelete(scope)">
                        <template #reference>
                            <el-link type="primary" :underline="false">删除</el-link>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>

        <pagination :page-data="userQuery" :total="total" @size-change="sizeChange" @current-change="currentChange" />

        <el-drawer v-model="showDrawer" :title="drawerTitle" size="40%" style="padding-right: 20px;"
            :before-close="handleClose">
            <el-form class="form" ref="formRef" :rules="rules" :model="formData" size="large" label-position="right"
                label-width="110px">
                <el-form-item v-for="item in formColumn" :prop="drawerTitle === '编辑' ? '' : item.prop"
                    :label="item.label">
                    <el-input v-if="item.type == 'input'" v-model="formData[item.prop]" :placeholder="item.placeholder"
                        :disabled="drawerTitle === '编辑' ? item?.disabled : false">
                    </el-input>

                    <el-upload v-if="item.type == 'avatar'" :action="uploadPath" :show-file-list="false"
                        :headers="headers" :on-success="uploadPicUrl" class="avatar-uploader"
                        accept=".jpg,.jpeg,.png,.gif">
                        <img class="avatar" :src="formData[item.prop]" />
                    </el-upload>
                    <el-date-picker v-if="item.type == 'date'" v-model="formData[item.prop]" format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD"></el-date-picker>
                    <el-select v-if="item.type == 'select'" v-model="formData[item.prop]" multiple style="width: 300px">
                        <el-option v-for="i in roles" :key="i.id" :label="i.roleName" :value="i.id"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="handleClose">关闭</el-button>
                <el-button type="primary" @click="handleSubmit">保存</el-button>
            </template>
        </el-drawer>
    </div>
</template>
<script setup lang="ts">
import { reactive, ref, watch, computed } from 'vue'
import { ElMessageBox } from 'element-plus';
import { addUser, getUserInfo, editUser, deleteUser, getAllRole, findRoleByUser, userEnabled } from '@/services/api/user/userAPI'
import { uploadPath } from "@/services/api/storage";
import moment from 'moment';
import pagination from '@/components/pagination/index.vue'

const tableColumn = reactive([
    {
        label: '用户账号',
        prop: 'username'
    },
    {
        label: '用户名',
        prop: 'name'
    },
    {
        label: '工作地点',
        prop: 'fworkAddr'
    },
    {
        label: '状态',
        prop: 'fstate'
    },
    {
        label: '英文名',
        prop: 'fenglishName'
    },
    {
        label: '头像',
        prop: 'avatar'
    },
    {
        label: '创建人',
        prop: 'fcreator'
    },
    {
        label: '创建日期',
        prop: 'fdate'
    }
])
const tableData = ref([])
const formRef = ref()
const formColumn = reactive([
    {
        label: '用户账号',
        prop: 'username',
        type: 'input',
        placeholder: '请输入用户账号',
        disabled: true
    },
    {
        label: '用户名',
        prop: 'name',
        type: 'input',
        placeholder: '请输入用户名'
    },
    {
        label: '用户介绍',
        prop: 'introduction',
        type: 'input',
        placeholder: '请输入用户介绍'
    },
    {
        label: '工号',
        prop: 'fworkNo',
        type: 'input',
        placeholder: '请输入工号'
    },
    {
        label: '工作地点',
        prop: 'fworkAddr',
        type: 'input',
        placeholder: '请输入工作地点'
    },
    {
        label: '状态',
        prop: 'fstate',
        type: 'input',
        placeholder: '请输入状态'
    },
    {
        label: '角色分配',
        prop: 'roles',
        type: 'select',
        placeholder: '分配角色'
    },
    {
        label: '职位',
        prop: 'fposition',
        type: 'input',
        placeholder: '请输入职位'
    },
    {
        label: '手机',
        prop: 'fphone',
        type: 'input',
        placeholder: '请输入手机'
    },
    {
        label: '邮箱',
        prop: 'fmail',
        type: 'input',
        placeholder: '请输入邮箱'
    },
    {
        label: '入职日期',
        prop: 'finductionDate',
        type: 'date',
        placeholder: '请输入入职日期'
    },
    {
        label: '英文名',
        prop: 'fenglishName',
        type: 'input',
        placeholder: '请输入英文名'
    },
    {
        label: '部门',
        prop: 'fdept',
        type: 'input',
        placeholder: '请输入部门'
    },
    {
        label: '头像',
        prop: 'avatar',
        type: 'avatar'
    }
])
const rules = reactive<any>({
    username: [
        { required: true, message: '请输入用户账号', trigger: 'blur' },
        { min: 6, message: '长度应不小于6个字符', trigger: 'blur' },
        // { max: 16, message: '长度应不大于16个字符', trigger: 'blur' },
        // { pattern: /^[A-z][A-z0-9]/, message: '用户名不能为数字开头且数字字母组成', trigger: 'blur' }
    ],
    name: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 2, message: '长度应不小于2个字符', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入登录密码', trigger: 'blur' },
        { min: 6, message: '长度应不小于6个字符', trigger: 'blur' }
    ],
    fphone: [{
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: "请输入正确的手机号",
        trigger: "blur",
    }],
    fmail: [{ type: 'email', message: '请输入正确的电子邮件地址', trigger: ['blur', 'change'] }]
})
const formData = ref<any>({})
const avatarUrl = ref()
const drawerTitle = ref('')
const showDrawer = ref(false)
const userQuery = ref({
    pageNo: 1,
    pageSize: 10
})
const total = ref()
const roles = ref<any>([])
const headers = computed(() => {
    return { Authorization: sessionStorage.getItem("token") };
});

function init() {
    getUserInfo(userQuery.value).then((res) => {
        if (res.code == 200) {
            tableData.value = res.data.records
            total.value = res.data.total
        }
    })
    getAllRole().then((res) => {
        if (res.code == 200) {
            roles.value = res.data
        }
    })
}

// 是否启用
const switchChange = (value: boolean, userId: any) => {
    userEnabled(userId).then((res: any) => {
        if (res.code === 200) {
            init()
        }
    })
}

// 上传头像
let uploadPicUrl = (res: any) => {
    avatarUrl.value = res.data.url;
    formData.value.avatar = res.data.url
}

let sizeChange = (val: number) => {
    userQuery.value.pageSize = val
    init()
}

let currentChange = (val: number) => {
    userQuery.value.pageNo = val
    init()
}

function handleEdit(scope: any) {
    formData.value = {}
    const params = {
        userId: scope.row.userId
    }
    findRoleByUser(params).then((res) => {
        if (res.code == 200) {
            formData.value.roles = res.data
        }
    })
    for (const i in scope.row) {
        formData.value[i] = scope.row[i]
    }
    for (const j in formColumn) {
        if (formColumn[j].prop == 'password') {
            formColumn.splice(Number(j), 1)
            break
        }
    }
    for (const k in formData.value) {
        if (k == 'password') {
            delete formData[k]
            break
        }
    }
    drawerTitle.value = '编辑'
    showDrawer.value = true
}

function handleAdd() {
    formData.value = {}
    drawerTitle.value = '添加'
    if (formColumn[1].prop !== 'password') formColumn.splice(1, 0, {
        label: '登录密码',
        prop: 'password',
        type: 'input',
        placeholder: '请输入登录密码'
    })
    showDrawer.value = true
}

function handleSubmit() {
    formRef.value?.validate((valid: Boolean, fields: any) => {
        if (valid) {
            if (drawerTitle.value == '添加') {
                if (avatarUrl.value)
                    formData.value = { ...{ avatar: avatarUrl.value }, ...formData.value }
                addUser(formData.value).then((res) => {
                    if (res.code == 200) {
                        init()
                        showDrawer.value = false
                    }
                })
            }
            if (drawerTitle.value == '编辑') {
                if (avatarUrl.value)
                    formData.value.avatar = avatarUrl.value
                editUser(formData.value).then((res: any) => {
                    if (res.code == 200) {
                        init()
                        showDrawer.value = false
                    }
                })

            }
        } else console.log(fields);
    })
}

function handleDelete(scope: any) {
    const params = {
        userId: scope.row.userId
    }
    deleteUser(params).then((res) => {
        if (res.code == 200) {
            init()
        }
    })
}

const updateCount = ref(0)
watch(() => formData.value, () => {
    updateCount.value++
}, { immediate: true, deep: true })

function handleClose() {
    if (updateCount.value > 4) {
        ElMessageBox.confirm(
            '是否提交已修改的内容?',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
            .then(() => {
                updateCount.value = 0
                handleSubmit()
            })
            .catch(() => {
                updateCount.value = 0
                formRef.value.resetFields()
                showDrawer.value = false
            })
    } else {
        updateCount.value = 0
        formRef.value.resetFields()
        showDrawer.value = false
    }
}

init()

</script>
<style scoped>
.form {
    overflow-x: hidden;
    overflow-y: auto;
    height: calc(100vh - 120px);
}

.avatar {
    width: 120px;
    height: 120px;
    display: block;
}

.el-dropdown-link {
    cursor: pointer;
    color: var(--el-color-primary);
    align-items: center;
}
</style>