<template>
    <el-dialog draggable class="cn-operate-dialog" v-model="dialogVisible" :title="title">
        <el-form :model="form" class="form-two" label-width="auto" :rules="rules" ref="formRef">
            <el-form-item label="用户名" prop="name">
                <el-input v-model="form.name" placeholder="请输入昵称" maxlength="16" show-word-limit @input="handleInput('name', $event)" :disabled="title !== '新增用户'"/>
            </el-form-item>
            <el-form-item label="登录名" prop="loginName" >
                <el-input v-model="form.loginName" placeholder="请输入登录名"  maxlength="16" show-word-limit @input="handleInput('loginName', $event)" :disabled="title !== '新增用户'"/>
            </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="请选择权限类型" filterable>
                    <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="请选择用户类型类型" filterable>
                    <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 filterable>
                    <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 style="width: 80%" 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>

        <template #footer>
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submit">确认</el-button>
        </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 formRef = ref()
const adminInfo = useAdminInfo()
const tableStore = inject('tableStore') as TableStore
// do not use same name with ref
const form = reactive({
    id: '',
    name: '',
    // password: 'Jbdnzl@123',
    password: '123456',
    email: '',
    limitIpStart: '',
    deptId: '',
    deptName: '',
    casualUser: 1,
    loginName: '',
    phone: '',
    limitIpEnd: '',
    limitTime: [1, 2],
    role: [],
    smsNotice: 1,
    emailNotice: 1,
    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, 24]
        form.role = []
        form.smsNotice = 1
        form.emailNotice = 1
        useId.value = 0
        form.id = ''
        form.limitIpStart = '0.0.0.0'
        form.limitIpEnd = '255.255.255.255'
        // form.password = 'Jbdnzl@123'
        form.password = '123456'
    }
    form.type = adminInfo.$state.userType + 1
}
const submit = async () => {
     formRef.value.validate(async (valid: boolean) => {
        if (valid) {
             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 handleInput = (field: keyof typeof form, value: string) => {
    // 过滤空格
    const filteredValue = value.replace(/\s/g, '')
    if (filteredValue !== value) {
        form[field] = filteredValue as never
    }
}

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