<template>
    <el-dialog class="cn-operate-dialog" v-model="dialogVisible" :title="title">
        <el-scrollbar>
            <el-form :inline="true" :model="form" label-width="120px" :rules="rules">
                <el-form-item label="用户名" prop="name">
                    <el-input v-model="form.name" placeholder="请输入昵称" />
                </el-form-item>
                <el-form-item label="登录名" prop="loginName">
                    <el-input v-model="form.loginName" placeholder="请输入登录名" />
                </el-form-item>
                <el-form-item label="默认密码" prop="password" v-if="title === '新增用户'">
                    <el-input v-model="form.password" placeholder="请输入密码" disabled />
                </el-form-item>
                <el-form-item label="权限类型" prop="type">
                    <el-select 
                        v-model="form.type"
                        @change="changeValue"
                        disabled
                        placeholder="请选择权限类型"
                    >
                        <el-option
                            v-for="(item, index) in UserTypeOption"
                            :label="item.label"
                            :value="item.value"
                            :key="index"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="用户类型" prop="casualUser">
                    <el-select  v-model="form.casualUser" placeholder="请选择权限类型">
                        <el-option
                            v-for="(item, index) in TypeOptions"
                            :label="item.label"
                            :value="item.value"
                            :key="index"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="所属部门" prop="deptId">
                    <Area style="width: 100%" v-model="form.deptId" />
                </el-form-item>
                <el-form-item label="角色" prop="role">
                    <el-select  v-model="form.role" placeholder="请选择角色" multiple collapse-tags>
                        <el-option
                            v-for="(item, index) in roleOptions"
                            :label="item.label"
                            :value="item.value"
                            :key="index"
                        ></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="form.phone" placeholder="请输入手机号" />
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="form.email" placeholder="请输入描述" />
                </el-form-item>
                <el-form-item label="起始IP" prop="limitIpStart">
                    <el-input v-model="form.limitIpStart" placeholder="请输入描述" />
                </el-form-item>
                <el-form-item label="结束IP" prop="limitIpEnd">
                    <el-input v-model="form.limitIpEnd" placeholder="请输入描述" />
                </el-form-item>
                <el-form-item label="时间段" prop="limitTime">
                    <el-slider v-model="form.limitTime" range show-stops :max="24" />
                </el-form-item>
                <el-form-item label="短信通知" prop="smsNotice">
                    <el-radio-group v-model="form.smsNotice">
                        <el-radio-button :label="0">是</el-radio-button>
                        <el-radio-button :label="1">否</el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="邮件通知" prop="emailNotice">
                    <el-radio-group v-model="form.emailNotice">
                        <el-radio-button :label="0">是</el-radio-button>
                        <el-radio-button :label="1">否</el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="用户ID">
                    <div style="display: flex; width: 100%">
                        <el-radio-group v-model="useId">
                            <el-radio-button :label="1">是</el-radio-button>
                            <el-radio-button :label="0">否</el-radio-button>
                        </el-radio-group>
                        <el-input
                            :disabled="title !== '新增用户'"
                            v-model="form.id"
                            placeholder="请输入用户id"
                            v-if="useId"
                            style="flex: 1"
                            class="ml10"
                        ></el-input>
                    </div>
                </el-form-item>
            </el-form>
        </el-scrollbar>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submit">确认</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script lang="ts" setup>
import { ref, inject } from 'vue'
import { reactive } from 'vue'
import TableStore from '@/utils/tableStore'
import { ElMessage, FormItemRule } from 'element-plus'
import { roleList } from '@/api/user-boot/role'
import { add, edit } from '@/api/user-boot/user'
import { useAdminInfo } from '@/stores/adminInfo'
import Area from '@/components/form/area/index.vue'

const adminInfo = useAdminInfo()
const tableStore = inject('tableStore') as TableStore
// do not use same name with ref
const form = reactive({
    id: '',
    name: '',
    password: '123456',
    email: '',
    limitIpStart: '',
    deptId: '',
    deptName: '',
    casualUser: 1,
    loginName: '',
    phone: '',
    limitIpEnd: '',
    limitTime: [1, 2],
    role: [],
    smsNotice: 0,
    emailNotice: 0,
    type: 0
})
const rules:Partial<Record<string, Array<FormItemRule>>> = {
    name: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
    role: [{ required: true, message: '角色不能为空', trigger: 'blur' }],
    password: [{ required: true, message: '用户密码不能为空', trigger: 'blur' }],
    loginName: [{ required: true, message: '登录名不能为空', trigger: 'blur' }],
    casualUser: [{ required: true, message: '用户类型不能为空', trigger: 'blur' }],
    smsNotice: [{ required: true, message: '短信通知不能为空', trigger: 'blur' }],
    emailNotice: [{ required: true, message: '邮件通知不能为空', trigger: 'blur' }],
    email: [
        { required: false, message: '邮箱不能为空', trigger: 'blur' },
        {
            type: 'email',
            message: "'请输入正确的邮箱地址",
            trigger: ['blur', 'change']
        }
    ],
    phone: [
        { required: false, message: '手机号不能为空', trigger: 'blur' },
        {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
        }
    ],
    limitTime: [{ required: true, message: '时间段不能为空', trigger: 'blur' }],
    limitIpStart: [
        { required: true, message: '起始IP不能为空', trigger: 'blur' },
        {
            required: true,
            validator: (rule: any, value: string, callback: any) => {
                let regexp = /^((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}$/
                let isCorrect = regexp.test(value)
                if (value == '') {
                    return callback(new Error('请输入IP地址'))
                } else if (!isCorrect) {
                    callback(new Error('请输入正确的IP地址'))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ],
    limitIpEnd: [
        { required: true, message: '结束IP不能为空', trigger: 'blur' },
        {
            required: true,
            validator: (rule: any, value: string, callback: any) => {
                let regexp = /^((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}$/
                let isCorrect = regexp.test(value)
                if (value == '') {
                    return callback(new Error('请输入IP地址'))
                } else if (!isCorrect) {
                    callback(new Error('请输入正确的IP地址'))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ]
}
const UserTypeOption = [
    { label: '管理员', value: 1 },
    { label: '普通用户', value: 2 }
]
const TypeOptions = [
    { label: '临时用户', value: 0 },
    { label: '长期用户', value: 1 }
]
const useId = ref(1)
const roleOptions = ref<treeData>()
const queryRole = () => {
    roleList(adminInfo.$state.userType).then((res: any) => {
        roleOptions.value = res.data.map((item: any) => {
            return {
                label: item.name,
                value: item.id
            }
        })
    })
}
queryRole()
const dialogVisible = ref(false)
const title = ref('新增菜单')
const open = (text: string, data?: anyObj) => {
    title.value = text
    dialogVisible.value = true
    if (data) {
        for (let key in form) {
            form[key] = data[key]
        }
        form.limitTime = data.limitTime.split('-')
        form.role = data.roleList
    } else {
        for (let key in form) {
            form[key] = ''
        }
        form.casualUser = 1
        form.limitTime = [0, 23]
        form.role = []
        form.smsNotice = 0
        form.emailNotice = 0
        useId.value = 1
        form.id = ''
        form.limitIpStart = '0.0.0.0'
        form.limitIpEnd = '255.255.255.255'
        form.password = '123456'
    }
    form.type = adminInfo.$state.userType + 1
}
const submit = async () => {
    let obj = JSON.parse(JSON.stringify(form))
    obj.limitTime = obj.limitTime.join('-')
    delete obj.password
    if (form.id) {
        await edit(obj)
        ElMessage.success('修改成功')
    } else {
        form.type = adminInfo.$state.userType + 1
        await add(obj)
        ElMessage.success('新增成功')
    }
    tableStore.index()
    dialogVisible.value = false
}

const changeValue = () => {}
defineExpose({ open })
</script>
