<template>
    <el-dialog class="cn-operate-dialog" v-model.trim="dialogVisible" width="800" :title="title">
        <el-form :model="form" ref="formRef" label-width="auto" class="form-two" :rules="rules">
            <el-form-item label="用户名" prop="name">
                <el-input maxlength="32" show-word-limit    v-model.trim="form.name" placeholder="请输入昵称" />
            </el-form-item>
            <el-form-item label="登录名" prop="loginName">
                <el-input maxlength="32" show-word-limit    v-model.trim="form.loginName" placeholder="请输入登录名" />
            </el-form-item>
            <el-form-item label="默认密码" prop="password" v-if="title === '新增用户'">
                <el-input maxlength="32" show-word-limit 
                    
                    
                    v-model.trim="form.password"
                    placeholder="请输入密码"
                    disabled
                />
            </el-form-item>
            <el-form-item label="权限类型" prop="type">
                <el-select v-model.trim="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.trim="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 v-model.trim="form.deptId" />
            </el-form-item> -->
            <el-form-item label="角色" prop="role">
                <el-select v-model.trim="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 maxlength="32" show-word-limit    v-model.trim="form.phone" placeholder="请输入手机号" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input maxlength="32" show-word-limit    v-model.trim="form.email" placeholder="请输入描述" />
            </el-form-item>
            <el-form-item label="时间段" prop="limitTime">
                <el-slider v-model.trim="form.limitTime" style="width: 95%" range  :max="24" />
            </el-form-item>
            <el-form-item label="起始IP" prop="limitIpStart">
                <el-input maxlength="32" show-word-limit    v-model.trim="form.limitIpStart" placeholder="请输入描述" />
            </el-form-item>
            <el-form-item label="结束IP" prop="limitIpEnd">
                <el-input maxlength="32" show-word-limit    v-model.trim="form.limitIpEnd" placeholder="请输入描述" />
            </el-form-item>

            <el-form-item label="短信通知" prop="smsNotice">
                <el-radio-group v-model.trim="form.smsNotice" style="width: 200px">
                    <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.trim="form.emailNotice" style="width: 200px">
                    <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.trim="useId">
                        <el-radio-button :label="1">是</el-radio-button>
                        <el-radio-button :label="0">否</el-radio-button>
                    </el-radio-group>
                    <el-input maxlength="32" show-word-limit 
                        
                        
                        :disabled="title !== '新增用户'"
                        v-model.trim="form.id"
                        placeholder="请输入用户id"
                        v-if="useId"
                        style="flex: 1"
                        class="ml10"
                    ></el-input>
                </div>
            </el-form-item>
        </el-form>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submit" :loading="loading">确定</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'
import { Arrayable } from 'element-plus/es/utils'

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 formRef = ref()
const loading = ref(false)
const rules: Partial<Record<string, Arrayable<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 },
    { label: 'APP用户', value: 3 },
]
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) => {
    formRef.value?.resetFields()
    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 = 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 () => {

    formRef.value.validate(async (valid: any) => {
        if (valid) {
            loading.value = true
            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
            loading.value = false
        }
    })
}

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