<template>
    <div class="personal-info-container">
        <el-card class="personal-info-header">
            <div class="header-content">
                <div class="avator-container">
                    <el-avatar :size="80" :src="photoUrl ? photoUrl : defaultImage"></el-avatar>
                    <el-upload
                        action="string"
                        :http-request="updateUserImage"
                        :show-file-list="false"
                    >
                        <el-button size="mini" type="primary">上传 </el-button>
                    </el-upload>
                </div>
                <div class="header-info">
                    <el-row>
                        <el-col :span="6">
                            <div>姓名：{{ form.fullname }}</div>
                        </el-col>
                        <el-col :span="6">
                            <div>账号：{{ form.account }}</div>
                        </el-col>
                        <el-col :span="6">
                            <div>性别：{{ form.sex }}</div>
                        </el-col>
                        <el-col :span="6">
                            <div>出生年月：{{ form.userExtend.birthday }}</div>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="6">
                            <div>手机：{{ form.mobile }}</div>
                        </el-col>
                        <el-col :span="6">
                            <div>邮箱：{{ form.email }}</div>
                        </el-col>
                        <el-col :span="6">
                            <div>
                                组织：{{
                                    userDetail.org && userDetail.org[0]
                                        ? userDetail.org[0].orgName
                                        : ''
                                }}
                            </div>
                        </el-col>
                        <el-col :span="6">
                            <div>
                                岗位：
                                {{ postName }}
                            </div>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <div>
                                角色：<span
                                    class="role"
                                    v-for="(item, index) in userDetail.role.roleName.split('|')"
                                    :key="item"
                                >
                                    <span v-if="index !== 0">、</span>{{ item }}
                                </span>
                            </div>
                        </el-col>
                    </el-row>
                </div>
            </div>
        </el-card>
        <el-card class="personal-info-bottom" body-style="overflow:auto">
            <el-form ref="formRef" :model="form" :rules="rules" label-position="top">
                <div class="title-info">个人信息更新</div>
                <el-row :gutter="20">
                    <el-col :span="4">
                        <el-form-item label="姓名" prop="fullname">
                            <el-input v-model="form.fullname" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="性别" prop="sex">
                            <el-select v-model="form.sex" placeholder="请选择">
                                <el-option
                                    v-for="item in options"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item
                            label="出生年月"
                            prop="userExtend.birthday"
                            :rules="rules.birthday"
                        >
                            <el-date-picker
                                v-model="form.userExtend.birthday"
                                value-format="YYYY-MM-DD"
                                type="date"
                                placeholder="请选择日期"
                            >
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item
                            label="身份证号"
                            prop="userExtend.idNumber"
                            :rules="rules.idNumber"
                        >
                            <el-input
                                v-model="form.userExtend.idNumber"
                                placeholder="请输入"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="邮箱" prop="email">
                            <el-input v-model="form.email" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="手机" prop="mobile">
                            <el-input v-model="form.mobile" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="4">
                        <el-form-item
                            label="职称"
                            prop="userExtend.jobTitle"
                            :rules="rules.jobTitle"
                        >
                            <el-input
                                v-model="form.userExtend.jobTitle"
                                placeholder="请输入"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item
                            label="文化程度"
                            prop="userExtend.diploma"
                            :rules="rules.diploma"
                        >
                            <el-input
                                v-model="form.userExtend.diploma"
                                placeholder="请输入"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item
                            label="入职时间"
                            prop="userExtend.hireDate"
                            :rules="rules.hireDate"
                        >
                            <el-date-picker
                                v-model="form.userExtend.hireDate"
                                value-format="YYYY-MM-DD"
                                type="date"
                                placeholder="请选择日期"
                            >
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="地址" prop="address">
                            <el-input v-model="form.address" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item
                            label="工作经历（入司后工作经历）"
                            prop="userExtend.workExperience"
                            :rules="rules.workExperience"
                        >
                            <el-input
                                type="textarea"
                                :autosize="{ minRows: 2, maxRows: 6 }"
                                v-model="form.userExtend.workExperience"
                                placeholder="请输入"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item
                            label="有何技能和特长(证书)"
                            prop="userExtend.skills"
                            :rules="rules.skills"
                        >
                            <el-input
                                type="textarea"
                                :autosize="{ minRows: 2, maxRows: 6 }"
                                v-model="form.userExtend.skills"
                                placeholder="请输入"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>
        <el-card class="personal-info-footer">
            <div style="text-align: center">
                <el-button type="primary" @click="updataInfo" :loading="saveing"> 保 存 </el-button>
            </div>
        </el-card>
    </div>
</template>

<script lang="ts" setup name="PersonalInfo">
import { ref, reactive, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { updateUserInfo, getUserImg } from '@/api/system/user'
import { fileUpload } from '@/api/system/file'

const userStore = useUserStore()
const userDetail = userStore.getUserDetail

// 验证函数
const isEmail = (rule: any, value: any, callback: any) => {
    if (!value) {
        callback(new Error('邮箱不能为空'))
    } else {
        const reg = /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/
        const email = reg.test(value)
        if (!email) {
            callback(new Error('邮箱格式如:admin@163.com'))
        } else {
            callback()
        }
    }
}

const isMobileNumber = (rule: any, value: any, callback: any) => {
    if (!value) {
        callback(new Error('手机号不能为空'))
    } else {
        const reg = /^1[3-9]\d{9}$/
        const isPhone = reg.test(value)
        const numValue = Number(value)
        if (typeof numValue === 'number' && !isNaN(numValue)) {
            const strValue = numValue.toString()
            if (strValue.length < 0 || strValue.length > 12 || !isPhone) {
                callback(new Error('手机号码格式有误，请核查！'))
            } else {
                callback()
            }
        } else {
            callback()
        }
    }
}

const isCardId = (rule: any, value: any, callback: any) => {
    if (!value) {
        callback(new Error('身份证号不能为空'))
    } else {
        const reg = /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[0-2])(([0-2][1-9])|10|20|30|31)\d{3}(\d|X|x)$/
        const card = reg.test(value)
        if (!card) {
            callback(new Error('身份证格式有误，请核查！'))
        } else {
            callback()
        }
    }
}

// 响应式数据
const formRef = ref<FormInstance>()

const options = [
    { value: '男', label: '男' },
    { value: '女', label: '女' }
]

interface userInfo {
    userExtend: {
        birthday: string
        hireDate: string
        workExperience: string
        [key: string]: any
    }
    [key: string]: any
}

const form = reactive<userInfo>({
    userExtend: {
        workExperience: '',
        birthday: '',
        hireDate: ''
    }
})

const rules: FormRules = {
    fullname: [
        {
            required: true,
            message: '姓名不能为空',
            trigger: ['blur', 'change']
        }
    ],
    sex: [
        {
            required: true,
            message: '性别不能为空',
            trigger: ['blur', 'change']
        }
    ],
    birthday: [
        {
            required: true,
            message: '出生年月不能为空',
            trigger: ['blur', 'change']
        }
    ],
    idNumber: [
        {
            required: true,
            message: '身份证号不能为空',
            trigger: ['blur', 'change']
        },
        { validator: isCardId, trigger: 'blur' }
    ],
    email: [
        {
            required: true,
            message: '邮箱不能为空',
            trigger: ['blur', 'change']
        },
        { validator: isEmail, trigger: 'blur' }
    ],
    mobile: [
        {
            required: true,
            message: '手机号不能为空',
            trigger: ['blur', 'change']
        },
        { validator: isMobileNumber, trigger: 'blur' }
    ],
    userNumber: [
        {
            required: true,
            message: '工号不能为空',
            trigger: ['blur', 'change']
        }
    ],
    workType: [
        {
            required: true,
            message: '工种不能为空',
            trigger: ['blur', 'change']
        }
    ],
    jobTitle: [
        {
            required: true,
            message: '职称不能为空',
            trigger: ['blur', 'change']
        }
    ],
    diploma: [
        {
            required: true,
            message: '文化程度不能为空',
            trigger: ['blur', 'change']
        }
    ],
    hireDate: [
        {
            required: true,
            message: '入职时间不能为空',
            trigger: ['blur', 'change']
        }
    ],
    address: [
        {
            required: true,
            message: '地址不能为空',
            trigger: ['blur', 'change']
        }
    ],
    workExperience: [
        {
            required: true,
            message: '工作经历不能为空',
            trigger: ['blur', 'change']
        }
    ]
}

import defaultImage from '@/assets/img/layout/defaultPhoto.jpg'
const photoUrl = ref('')
const photo = ref('')
const saveing = ref(false)
const postName = ref('')

// 生命周期
onMounted(() => {
    getInfo()
})

// 方法
const updateUserImage = (param: any) => {
    const formData = new FormData()
    formData.append('files', param.file)
    fileUpload(formData)
        .then(async (response: any) => {
            photo.value = response.fileId
            form.photo = response.fileId
            const userPhotoData = await getUserImg(response.fileId)
            if (userPhotoData) {
                photoUrl.value = userPhotoData
            }
            param.onSuccess()
            updataInfo()
        })
        .catch(() => {
            param.onError()
        })
}

const getInfo = async () => {
    const post = userDetail.post
    for (const key in post) {
        postName.value = (post as any)[key].postName || ''
        ;(form as any).userExtend.workType = postName.value || ''
    }
    const userForm = userDetail.user

    const {
        birthday = '',
        hireDate = '',
        idNumber = '',
        workExperience = '',
        workType = '',
        jobTitle = '',
        diploma = '',
        skills = ''
    } = userDetail.userExtend || {}

    const userExtend = {
        birthday,
        hireDate,
        idNumber,
        workExperience,
        workType,
        jobTitle,
        diploma,
        skills,
        ...(userDetail.userExtend || {})
    }

    Object.assign(form, userForm)
    ;(form as any).userExtend = userExtend

    if ((form as any).photo) {
        const userPhotoData = await getUserImg((form as any).photo)
        if (userPhotoData) {
            photoUrl.value = userPhotoData
        }
    }
}

const updataInfo = async () => {
    formRef.value?.validate(async (valid, object) => {
        if (!valid) {
            ElMessage.warning(
                `有${Object.keys(object || {}).length}个字段未通过校验，请正确填写表单内容。`
            )
        } else {
            try {
                saveing.value = true
                await updateUserInfo(form)
                ElMessage.success('更新成功')
                // this.$bus.$emit('updataUserInfo')
                userStore.setUserDetail(form.account)
            } catch (err) {
                ElMessage.warning(err || '更新失败')
            } finally {
                saveing.value = false
            }
        }
    })
}
</script>

<style lang="scss" scoped>
.personal-info-container {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    padding: 16px;
    background-color: var(--theme-bg-custom);
    :deep(.el-card) {
        background-color: var(--theme-system-module-1);
    }
    .el-header {
        display: flex;
        align-items: center;
        border-bottom: 1px solid $system-border-color3;
    }

    .title {
        font-size: 16px;
    }

    .personal-info-header {
        margin-bottom: 16px;
    }

    .header-content {
        display: flex;
        height: 100%;
    }

    .avator-container {
        width: 120px;
        height: 100%;
        margin-right: 30px;
        box-sizing: border-box;
        text-align: center;
    }

    .header-info {
        width: calc(100% - 150px);
        padding: 6px 0;
        display: flex;
        flex-flow: column;
        justify-content: space-between;
        gap: 14px;
        div {
            font-size: 14px;
        }
        .role {
            font-size: 14px;
        }
    }
}

.el-card.is-always-shadow {
    border-radius: 20px;
}
.personal-info-bottom {
    height: calc(100% - 288px);
    margin-bottom: 16px;
    overflow: auto;
}
.personal-info-footer {
    height: 100px;
    display: flex;
    justify-content: center;
    align-items: center;
}
.title-info {
    font-size: 14px;
    font-weight: bold;
    margin-bottom: 10px;
    color: #43a1ff;
}
:deep(.el-form--label-top .el-form-item__label) {
    padding: 0;
}
:deep(.el-form-item) {
    margin-bottom: 14px;
}
</style>
