<template>
    <div class="user-setting">
        <div class="row flex-center">
            <el-upload drag 
            :action="getUploadActionUrl()" 
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            class="avatar-upload" v-loading="loadingImg">
                <el-avatar :size="72" :src="userInfo.photo" shape="square" class="bg-transparent"></el-avatar>
                <div class="after-overlayer">上传</div>
            </el-upload>
        </div>
        <div class="q-mt-xl q-mb-md row flex-center items-center" style="height:26px;">
            <template v-if="!isEditorNickname">
                <div>{{ userInfo.nickname }}</div>
                <IconWrite :size="16" class="q-ml-md cusor-pointer" 
                @click="()=>editorNicknameHandler(nicknameRef,0)"></IconWrite>
            </template>
            <input type="text" ref="nicknameRef" class="nickname" 
            v-model="userInfo.nickname" :autofocus="true" v-show="isEditorNickname" @blur="()=>{isEditorNickname=false,bindHandler()}">
        </div>
        <!-- <div class="text-small text-info text-center">用户ID:9020345764199812103</div> -->
        <div class="q-mt-lg setting-body rounded">
            <!-- <div class="setting-item">
                <div>
                    <div class="text-dark">手机</div>
                    <div class="">+86 173****7817</div>
                </div>
                <el-button>更换手机</el-button>
            </div> -->
            <div class="setting-item">
                <div>
                    <div class="text-dark">邮箱</div>
                    <div class="">{{Mailbox?Mailbox:'绑定邮箱后，可以更方便的登录、管理稿定账号'}}</div>
                </div>
                <el-button @click="bindDatas(1)">{{Mailbox?'更换邮箱':'立即绑定'}}</el-button>
            </div>
            <!-- <div class="setting-item">
                <div>
                    <div class="text-dark">微信</div>
                    <div class="">已绑定</div>
                </div>
                <el-button>解出绑定</el-button>
            </div>
            <div class="setting-item">
                <div>
                    <div class="text-dark">QQ</div>
                    <div class="">绑定QQ后，可以通过QQ授权登录</div>
                </div>
                <el-button>立即绑定</el-button>
            </div> -->
            <div class="setting-item">
                <div>
                    <div class="text-dark">密码</div>
                    <div class="">已设置</div>
                </div>
                <el-button  @click="bindDatas(2)">更换密码</el-button>
            </div>
        </div>
        <div class="q-mt-lg setting-body rounded">
            <div class="setting-item">
                <div>
                    <div class="text-dark">推送内容</div>
                    <div class="">开启后，我们将会通过服务邮箱或微信公众号向你推送最新的功能更新与模板更新。</div>
                </div>
                <el-switch v-model="pushAdStatus" />
            </div>
        </div>
    </div>
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="430" @close="closeForm">
        <el-form ref="bindFormRef" :model="model" :rules="rules" label-width="0px" size="large" class="full-width" :disabled="loading"> 
            <template v-if="dialogType==1">
                <el-form-item label="" prop="mail">
                    <el-input v-model="model.mail" placeholder="邮箱">
                        <template #suffix>
                            <el-button link :disabled="!mailRegex.test(model.mail)" :loading="sending" 
                            v-if="!isCountdown" @click="sendVerifyCode">{{ isSend?'重新发送':'发送验证码' }}</el-button>
                            <template v-else>
                                <el-countdown title="" format="ss" :value="countValue" value-style="font-size:14px;color:#f89c53;" class="inline q-mx-sm" @finish="()=>isCountdown=false" />s
                            </template>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item label="" prop="code">
                    <el-input v-model="model.code" placeholder="验证码" />
                </el-form-item>
            </template>
            <template v-if="dialogType==2">
                <el-form-item label="" prop="oldpwd">
                    <el-input v-model="model.oldpwd" type="password" placeholder="原密码" autocomplete="new-password" show-password/>
                </el-form-item>
                <el-form-item label="" prop="pwd">
                    <el-input v-model="model.pwd" type="password" placeholder="新密码" autocomplete="new-password" show-password/>
                </el-form-item>
            </template>
            <!-- <el-form-item label="">
                <vue-hcaptcha ref="invisibleHcaptchaBind" sitekey="46e00e53-ddb2-4e7b-9c51-621534c2f1f5" @verify="verifyHandler"></vue-hcaptcha>
            </el-form-item> -->
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogVisible = false" class="ppt-button" size="large" >取消</el-button>
                <el-button type="primary" @click="submitForm(bindFormRef)" class="ppt-button" size="large" :loading="loading">
                  确定<template v-if="dialogType==1">{{Mailbox?'换绑':'绑定'}}</template><template v-else>更换</template>
                </el-button>
              </div>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { ElMessage, FormInstance, FormRules } from 'element-plus';
import { useUserStore } from "@/store";
import { storeToRefs } from "pinia";
import { nextTick } from "vue";
import { ref, reactive } from "vue";
import { ApiResult } from '@/configs/axios';
import UserServices from '@/services/UserService'
import VueHcaptcha from "@hcaptcha/vue3-hcaptcha";
import { domainManager } from '@/utils/domainManager'
import AliyunUpload from '@/utils/upload/aliyun'
import CryptoJS from 'crypto-js'

const useUser = useUserStore()
const { userInfo } = storeToRefs(useUser)
const userTheme = useUser.getUserTheme
const isEditorNickname = ref(false)
const nicknameRef=ref<HTMLElement>()
const pushAdStatus = ref(false)
const dialogVisible = ref(false)
const dialogType = ref(null as any)
const dialogTitle = ref('')
const mailRegex = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$/
const model = ref({
    //account:'',
    oldpwd:'',
    pwd:'',
    mail:'',
    code:''
} as any)
const Mailbox = ref('')
const validateToken = ref('')
const invisibleHcaptchaBind = ref<VueHcaptcha|null>(null)
const bindFormRef = ref<FormInstance>()
const loading = ref(false)
const sending = ref(false)
const isSend = ref(false)
const isCountdown = ref(false)
const countValue = ref<number>(0)
const loadingImg = ref(false)
const validateMail = (rule:any,value:any,callback:any)=>{
    if (value === '') {
        callback(new Error('请输入你的邮箱账户'))
    }  else if (!mailRegex.test(value)) {
        callback(new Error("请输入正确的邮箱账户"))
    } else {
        callback()
    }
}
const rules = reactive<FormRules<RuleForm>>({
    oldpwd: [
        { required: true, message: '请输入你的原密码', trigger: 'blur' },
        { min: 6,max:20, message: '密码的长度应为6-20位', trigger: 'blur' },
    ],
    pwd:[
        { required: true, message: '请输入你的新密码', trigger: 'blur' },
        { min: 6,max:20, message: '密码的长度应为6-20位', trigger: 'blur' },
    ],
    mail:[
        { validator: validateMail, trigger: 'blur' }
    ],
    code:[
        { required: true, message: '请输入验证码', trigger: 'blur' },
        { min: 6,max:6, message: '验证码应为6位', trigger: 'blur' },
    ]
})

//上传头像地址
const getUploadActionUrl=()=>{
    let uid=userInfo.value.id;
   const url=domainManager().UploadUrl
   return url;
}

const handleAvatarSuccess=async (res:any)=>{
   console.log("handleAvatarSuccess_res",res);
}

const beforeAvatarUpload=async (res:any)=>{
    dialogType.value = 3
    loadingImg.value = true
    let filePath="/Upload/User/";
    let url  = await AliyunUpload.UploadAvatar(res, filePath);
    if(url!='') {
        userInfo.value.photo =url
        await bindHandler()
    }
}

const closeForm = () => {
    bindFormRef.value.clearValidate()
    bindFormRef.value.resetFields()
}

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return

    await formEl.validate(async (valid) => {
        loading.value=true
        if (valid) {
            // if (invisibleHcaptchaBind.value && validateToken.value == '') {
            //     invisibleHcaptchaBind.value.execute()
            //     loading.value=false
            //     return
            // }
            await bindHandler()
        }
        loading.value=false
    })
}

const bindHandler = async () =>{
    let response 
    if(dialogType.value==0) response = await UserServices.setMyNickNamed(userInfo.value.nickname)
    if(dialogType.value==1) response = await UserServices.setBindUserEmail(model.value.mail,model.value.code)
    if(dialogType.value==2) response = await UserServices.setModifyUserPwd(model.value.oldpwd,model.value.pwd)
    if(dialogType.value==3) response = await UserServices.ModifyUserPhoto(userInfo.value.photo)
    if(response){
        if(response.data.resultCode == ApiResult.SUCCESS){
            if(dialogType.value==1) {
                ElMessage.success({message:'绑定邮箱成功'})
                getInfo()
            }
            if(dialogType.value==2) {
                ElMessage.success({message:'更换密码成功'})
                useUser.setUserLoginOut()
            }
            dialogVisible.value = false
            dialogType.value = null
            loadingImg.value = false
            return
        }
        ElMessage.error({message:response.data.message})
        invisibleHcaptchaBind.value?.reset()
        validateToken.value=''
        loadingImg.value = false
    }
    
}

// 发送邮箱验证码
const sendVerifyCode = async () => {
    if(!mailRegex.test(model.value.mail) || sending.value) return
    sending.value= true
    
    const response = await UserServices.SendRegistCodeAsync(model.value.mail,1)
    if(response.data.resultCode == ApiResult.SUCCESS){
        ElMessage.success({message:'验证码已发送，请前往邮箱查看'})
        isCountdown.value = true
        countValue.value = Date.now() + 1000 * 60
        isSend.value = true
    } else {
        ElMessage.error({message:response.data.message})
    }
    sending.value= false
   
}

const bindDatas = (type:Number) =>{
    dialogType.value = type
    if(type==1) dialogTitle.value = Mailbox.value?'更换邮箱':'绑定邮箱'
    if(type==2) dialogTitle.value = '更换密码'
    dialogVisible.value = true
}

const editorNicknameHandler = (target:HTMLElement|undefined,type:Number)=>{
    dialogType.value = type
    isEditorNickname.value=true
    nextTick(()=>{
        if(target){
            target.focus()
        }
    })
}

const getInfo = async () => {
    const response  = await UserServices.GetMemberUserInfo()
    if(response.data.resultCode == ApiResult.SUCCESS){
        Mailbox.value = response.data.data.mail
    }
}

const verifyHandler = (token:string,ekey:string)=>{
    validateToken.value = token
}
getInfo()
</script>

<style>
.user-setting {
    width: 848px;
    padding-bottom: 24px;
    margin: 0 auto;
}
.user-setting .avatar-upload{
    width:72px;
    height: 72px;
    position: relative;
    border-radius:8px;
    overflow: hidden;
}
.user-setting .avatar-upload .el-upload-dragger{
    padding:0px !important;
    border-radius:8px;
    height: 72px;
}
.user-setting .avatar-upload .after-overlayer{
    position: absolute;
    top: 0;
    right: 0;
    left: 0;
    bottom: 0;
    background: rgba(0,0,0,.2);
    display: none;
    line-height: 72px;
    font-size: 16px;
    color:#FFF;
    text-align: center;
}
.user-setting .avatar-upload:hover .after-overlayer{
    display: block;
}
.user-setting .nickname{
    border:none;
    outline: none;
    padding: 5px;
    width: 180px;
    border-bottom: 1px dashed #000;
    font-size: 16px;
    font-family: pingfangr;
}
.user-setting .setting-body{
    border:1px solid rgba(0,0,0,.08)

}
.user-setting .setting-body .setting-item{
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 24px;
    font-size: 14px;
    line-height: 22px;
    color: #9da3ac;
    border-bottom:1px solid rgba(0,0,0,.08);
}
.user-setting .setting-body .setting-item:last-child{
    border: none;
}
</style>