<template>
    <HcCard actionSize="lg" scrollbar>
        <HcCardItem ui="hac-card-item mt-4" style="height:160px">
            <div class="user-avatar-box">
                <div class="user-avatar" v-loading="avatarLoading">
                    <img :src="userInfo['avatar'] || avatarPng" alt=""/>
                    <div class="user-avatar-upload">
                        <el-upload class="upload-dom" :action="action" :accept="accept" :headers="getTokenHeader()"
                                   :data="upData" :show-file-list="false" :on-success="uploadFinish"
                                   :on-error="uploadError" :before-upload="beforeUpload">
                            <HcIcon name="camera" fill/>
                        </el-upload>
                    </div>
                </div>
                <div class="user-name truncate">{{ userInfo['real_name'] || '游客' }}
                    <div class="el-upload__tip" style="margin-top: 27px;">支持.jpg 、png格式</div>
                </div>
            </div>
            <div class="btn_box">
                <el-button type="primary" size="large" @click="updatePassword" v-if="!updatePasswordshow">
                    <span>修改密码</span>
                </el-button>
                <el-button type="primary" size="large" @click="submit" :loading="saveUserLoading">
                    <span>保存</span>
                </el-button>
            </div>
        </HcCardItem>
        <HcCardItem ui="hac-card-item mt-4" :class="updatePasswordshow  ? 'half-height' : 'all-height'">
            <template #header>
                <div class="hac-card-title">基础信息</div>
            </template>
            <div>
                <el-form ref="formUserRef" :model="formUserModel" :rules="formUserRules" size="large"
                         label-width="auto">
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="用户姓名:">
                                <el-input v-model="formUserModel.real_name"/>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="身份证号:">
                                <el-input v-model="formUserModel.idNumber" placeholder=""/>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="手机号码:" :prop="basicFormEdit?'phone':''">
                                <el-input v-model="formUserModel.phone" placeholder="请输入绑定手机"/>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="所属岗位:">
                                <el-select v-model="formUserModel.position" class=" block" placeholder="请选择"
                                           size="large" disabled>
                                    <el-option
                                        v-for="item in posotionoptions"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="登录账号:">
                                <el-input v-model="formUserModel.account" placeholder="" disabled/>
                            </el-form-item>
                        </el-col>


                    </el-row>
                </el-form>
            </div>
        </HcCardItem>

        <HcCardItem ui="hac-card-item mt-4" style="height:38%" v-if="updatePasswordshow">
            <template #header>
                <div class="hac-card-title">修改密码</div>
            </template>
            <div>
                <el-form ref="formUserPassRef" :model="formUserPassModel" :rules="formUserPassRules"
                         label-position="left" label-width="auto"
                         size="large">
                    <el-form-item label="原密码:" prop="oldPassword">
                        <el-input v-model="formUserPassModel.oldPassword" placeholder="请输入原密码"
                                  autocomplete="new-password"
                                  show-password type="password"/>
                    </el-form-item>

                    <el-form-item label="新的密码:" prop="newPassword">
                        <el-input v-model="formUserPassModel.newPassword" placeholder="请输入新的密码"
                                  autocomplete="new-password"
                                  show-password type="password"/>
                    </el-form-item>
                    <el-form-item label="确认新密码:" prop="newPassword1">
                        <el-input v-model="formUserPassModel.newPassword1" placeholder="请输入确认新密码"
                                  autocomplete="new-password"
                                  show-password type="password"/>
                    </el-form-item>
                </el-form>

            </div>
        </HcCardItem>
    </HcCard>

</template>

<script setup>
import {ref, watch} from "vue";
import {useAppStore} from "~src/store";
import avatarPng from '~src/assets/images/avatar.png';
import {getTokenHeader} from '~src/api/request/header';
import userApi from '~src/api/modules/userInfo/index.js'
import {arrIndex, formValidate, getArrValue, isPhone} from "js-fast-way"
import md5 from 'js-md5';

const useAppState = useAppStore()

//全局变量信息
const userInfo = ref(useAppState.getUserInfo);
const basicFormEdit = ref(false)

//上传组件参数
const action = '/api/blade-resource/oss/endpoint/put-file';
const accept = 'image/png,image/jpg,image/jpeg';
const upData = ref({})

//上传前
const avatarLoading = ref(false)
const beforeUpload = () => {
    avatarLoading.value = true
    return true
}

//上传完成
const uploadFinish = async (res) => {
    const link = res?.data?.link ?? '';
    const user_id = userInfo.value?.user_id ?? '';
    if (link) {
        const {error, code} = await userApi.updateUserInfo({avatar: link, id: user_id})
        if (!error && code === 200) {
            avatarLoading.value = false
            userInfo.value.avatar = link
            window?.$message?.success('更换头像成功')
            useAppState.setUserInfo(userInfo.value)
        } else {
            avatarLoading.value = false
        }
    } else {
        window?.$message?.warning('上传头像异常，请稍后再试')
        avatarLoading.value = false
    }
}
//上传失败
const uploadError = () => {
    avatarLoading.value = false
    window?.$message?.warning('上传头像失败')
}
//基础信息表单
const formUserRef = ref(null)
const formUserModel = ref(userInfo.value)
const formUserPassRef = ref(null)
const formUserRules = {
    phone: {
        required: true,
        validator: (rule, value, callback) => {
            if (!value) {
                callback(new Error('请输入手机号'))
            } else if (!isPhone(value)) {
                callback(new Error('手机号码格式错误'))
            } else {
                callback()
            }
        },
        trigger: "blur"
    },
}
const formUserPassRules = {
    oldPassword: {
        required: true,
        trigger: "blur",
        message: "请输入原始密码"
    },
    newPassword: {
        required: true,
        validator(rule, value, callback) {
            const pass = formUserPassModel.value.newPassword1;
            if (!value) {
                callback(new Error("请输入新的密码"))
            } else if (pass && value !== pass) {
                callback(new Error("新的密码和确认新密码不一致"))
            }
            callback()
        },
        trigger: "blur"
    },
    newPassword1: {
        required: true,
        validator(rule, value, callback) {
            const pass = formUserPassModel.value.newPassword;
            if (!value) {
                callback(new Error("请输入确认新密码"))
            } else if (pass && value !== pass) {
                callback(new Error("新的密码和确认新密码不一致"))
            }
            callback()
        },
        trigger: "blur"
    }
}
const updatePasswordshow = ref(false)
const updatePassword = () => {
    updatePasswordshow.value = true
}
const submit = () => {
    // updatePasswordshow.value=false

    if (updatePasswordshow.value) {
        saveUpdatePassword()
    }
    saveUserInfoData()
    updatePasswordshow.value = false
}
const saveUserLoading = ref(false)
//保存用户信息
const saveUserInfoData = async () => {
    const {phone, user_id, idNumber} = formUserModel.value
    if (phone && isPhone(phone)) {
        saveUserLoading.value = true
        const {error, code} = await userApi.updateUserInfo({
            phone: phone,
            id: user_id,
            idNumber
        })
        if (!error && code === 200) {
            saveUserLoading.value = false
            window?.$message?.success('保存成功')
            userInfo.value.phone = phone
            useAppState.setUserInfo(userInfo.value)
        } else {
            saveUserLoading.value = false
        }
    }
}

const formUserPassModel = ref({oldPassword: '', newPassword: '', newPassword1: ''})
//更新密码
const saveUpdatePassword = async () => {
    const res = await formValidate(formUserPassRef.value)
    if (res) {
        const form = formUserPassModel.value;
        saveUserLoading.value = true
        const {error, code} = await userApi.updatePassword({
            oldPassword: md5(form?.oldPassword),
            newPassword: md5(form?.newPassword),
            newPassword1: md5(form?.newPassword1),
            plaintextPassword: form?.newPassword
        })
        if (!error && code === 200) {
            saveUserLoading.value = false
            window?.$message?.success('密码修改成功')
            formUserPassModel.value = {
                oldPassword: '',
                newPassword: '',
                newPassword1: ''
            }
        } else {
            saveUserLoading.value = false
        }
    }
}
const posotionoptions = ref([
    {label: '总经理', value: '1'}
])
</script>

<style lang="scss" scoped>
.user-avatar-box {
    display: flex;
    position: relative;
    text-align: left;
    // padding: 24px;
    .user-avatar {
        position: relative;
        height: 100px;
        width: 100px;
        border-radius: 50%;
        background: #d8d8d8;
        // margin: 24px 0 0;
        border: 2px solid #ffffff;
        // box-shadow: 7px 7px 8px 0 rgba(54,92,167,0.15), -7px -7px 8px 0 #ffffff, 4px 4px 8px 0 rgba(54,92,167,0.15), -4px -4px 8px 0 #ffffff;
        img {
            display: block;
            object-fit: cover;
            height: 100%;
            width: 100%;
            border-radius: 50%;
        }

        .user-avatar-upload {
            position: absolute;
            right: 0;
            bottom: 0;
            width: 24px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: #f1f5f8;
            border-radius: 50%;
            color: #838791;
            cursor: pointer;
            box-shadow: 4px 4px 8px 0 rgba(54, 92, 167, 0.15);
            transition: color 0.2s;

            &:hover {
                color: var(--el-color-primary);
            }
        }
    }

    .user-name {
        position: relative;
        margin-top: 20px;
        font-weight: bold;
        color: #1a1a1a;
        font-size: 28px;
        margin-left: 20px;
    }
}

.top-box {
    display: flex;
    // position: relative;
    height: 100%;

}

.btn_box {
    float: right;
    position: absolute;
    bottom: 10px;
    right: 0px;

}

.half-height {
    height: 50%;
}

.all-height {
    height: 100%;
}
</style>

<style lang="scss">

</style>
