<template>
<el-dialog v-model="dialogVisible" width="637" class="dialog-box" v-if="data"
    align-center
    destroy-on-close
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false">
    <template #header="{ close, titleId, titleClass }">
        <div class="msg-header" >
            <svg-icon icon-class="mtpwd" class="header-icon" />
            <div class="header-title">{{ t('forgotPassword.step2') }}</div>
            <div class="header-close" >
            <el-icon color="rgba(196, 196, 196, 1)" @click="close" ><Close /></el-icon>
            </div>
        </div>
    </template>
    <div class="msg-body" >
        <div style="display: flex;width: 100%;">
            <div class="account">{{ t('home.account') + ': ' + data.mt4_login }}</div>
        </div>
        <el-form v-if="curStep == 1" ref="postRef" :model="form" :rules="rules" autocapitalize="off" size="large" label-position="top" style="user-select: none;" >
            <el-form-item :label="t('home.mt4_password')" prop="mt4_password" v-if="type == 0" >
                <el-input type="password" v-model="form.mt4_password" show-password @input="handlePwd" />
            </el-form-item>
            <el-form-item v-if="type == 0">
                <password-validator v-if="form.mt4_password" ref="pv1" v-model="form.mt4_password" />
            </el-form-item>
            <el-form-item :label="t('home.mt4_password_investor')" prop="mt4_password_investor" v-if="type == 1" >
                <el-input type="password" v-model="form.mt4_password_investor" show-password @input="handlePwd" />
            </el-form-item>
            <el-form-item v-if="type == 1">
                <password-validator v-if="form.mt4_password_investor" ref="pv2" v-model="form.mt4_password_investor" />
            </el-form-item>
            <el-form-item >
                <el-button class="send-btn" @click="step1" style="width: 100%;" type="primary">{{ t('form.next') }}</el-button>
            </el-form-item>
        </el-form>
        <el-form v-else-if="curStep == 2" ref="step2Ref" :model="step2Form" :rules="step2Rules" class="login-form" hide-required-asterisk>
            <div :style="{visibility: sendStatus?'visible':'hidden'}" style="display: flex;align-items: center;margin-bottom: 20px;">
                <svg-icon icon-class="successMini" style="width: 20px;height: 20px;margin-right: 5px;" />
                <div style="font-size: 18px;font-weight: 400;" >{{ t('home.sendSuccess') }}</div>
            </div>
            <el-form-item prop="code">
                <el-input v-model="step2Form.code" type="text" size="large" auto-complete="off" style="width: 360px;margin-right: 14px;" :placeholder="t('forgotPassword.codePlaceholder')" >
                </el-input>
                <el-button plain class="send-btn" :disabled="disSend" @click="sendCode" >{{ sendBtnText }}</el-button>
            </el-form-item>
            <el-form-item >
                <el-button class="send-btn" @click="save" style="width: 100%;margin-top: 22px;" type="primary">{{ t('form.save') }}</el-button>
            </el-form-item>
        </el-form>
    </div>
</el-dialog>

</template>

<script setup>
import { useLocale } from 'element-plus'
import useAppStore from '@/store/modules/app'
import useUserStore from '@/store/modules/user'
import { ref, defineModel, watch, computed } from 'vue';
import { serverLang } from '@/utils/i18n'
import PasswordValidator from "@/components/PasswordValidator"
import { editOwnMtPassword, editOwnMtPasswordCheckCode, editOwnMtPasswordSendCode } from '@/api/account'

const { proxy } = getCurrentInstance();
const appStore = useAppStore()
const userStore = useUserStore()
const userInfo = ref(userStore.userInfo)
const { t } = useLocale()
const dialogVisible = defineModel("show")
const pv1 = ref(null)
const pv2 = ref(null)
const props = defineProps({
    data: {
        type: Object,
        default: null
    },
    type: Number
})
let timeInterval
const curStep = ref(1)
const sendStatus = ref(false)

const step2Form = ref({
    email: userInfo.value.email,
    code: ""
});

const step2Rules = {
    email: [{ required: true, trigger: "blur", message: t('form.email.required') }],
    code: [{ required: true, trigger: "change", message: t('form.captcha.required') }]
}

const countdown = ref(((new Date().getTime() - appStore.countdown) / 1000) > 60 ? 0 : (60 - (new Date().getTime() - appStore.countdown) / 1000).toFixed(0));
  if (countdown.value > 0) {
    timeInterval = setInterval(() => {
      if ((new Date().getTime() - appStore.countdown) / 1000 > 0 && (new Date().getTime() - appStore.countdown) / 1000 < 60) {
        countdown.value--
      } else {
        clearInterval(timeInterval)
        appStore.setCountdown(0)
        countdown.value = 0
      }
    }, 1000)
}

const sendBtnText = computed(() => {
    if (countdown.value == 0) {
      return t('forgotPassword.sendCode')
    } else {
      return `( ${countdown.value} )`
    }
  })

const disSend = computed(() => {
    return countdown.value > 0 || !step2Form.value.email
})

function sendCode() {
    countdown.value = 60
    appStore.setCountdown(new Date().getTime())
    timeInterval = setInterval(() => {
      if ((new Date().getTime() - appStore.countdown) / 1000 > 0 && (new Date().getTime() - appStore.countdown) / 1000 < 60) {
        countdown.value--
      } else {
        clearInterval(timeInterval)
        appStore.setCountdown(0)
        countdown.value = 0
      }
    }, 1000)
    editOwnMtPasswordSendCode({
      email: step2Form.value.email,
      qcc_language: serverLang()
    }).then(resp => {
        sendStatus.value = true
    }).catch(() => {
      clearInterval(timeInterval)
      appStore.setCountdown(0)
      countdown.value = 0
    })
}

const checkPwd = (rule, value, callback) => {
    if (!form.value.mt4_password && !form.value.mt4_password_investor) {
      return callback(new Error(''))
    }
    callback()
}

const d = reactive({
  form: {
    mt4_password: undefined,
    mt4_password_investor: undefined
  },
  rules: {
    mt4_password: [{ trigger: "blur", validator: checkPwd }],
    mt4_password_investor: [{ trigger: "blur", validator: checkPwd }],
  }
});

const { form, rules } = toRefs(d);

function step1() {
    proxy.$refs["postRef"].validate(valid => {
        if (valid && (!form.value.mt4_password || pv1.value.check()) && (!form.value.mt4_password_investor || pv2.value.check())) {
            curStep.value = 2
        }
    })
}

function save() {
    const { mt4_server, mt4_login } = props.data
    const { mt4_password, mt4_password_investor } = form.value
    const { email, code } = step2Form.value
    editOwnMtPasswordCheckCode({
        email, code, qcc_language: serverLang()
    }).then(resp => {
        editOwnMtPassword({
            mt4_server, mt4_login, mt4_password, mt4_password_investor,email,
            qcc_language: serverLang(),sign: resp.data
        }).then(resp => {
            dialogVisible.value = false
            clearInterval(timeInterval)
            appStore.setCountdown(0)
            countdown.value = 0
            window.showTip({
                title: t('common.success.action'),
                status: 'success'
            })
        })
    })
}

watch(dialogVisible, (n, o) => {
    if(!n) {
        curStep.value = 1
        form.value.mt4_password = undefined
        form.value.mt4_password_investor = undefined
        proxy.resetForm("postRef");
        sendStatus.value = false
    }
})

function handlePwd() {
    if (form.value.mt4_password) {
        form.value.mt4_password = form.value.mt4_password.replace(/[^a-zA-Z0-9!@#]/g, '')
    }
    if (form.value.mt4_password_investor) {
        form.value.mt4_password_investor = form.value.mt4_password_investor.replace(/[^a-zA-Z0-9!@#]/g, '')
    }
}
</script>

<style lang="scss">
.dialog-box {
    border-radius: 16px;
    padding: 0;

    .el-dialog__header {
        margin-right: 0;
        padding: 0;
        overflow: hidden;
    }

    .el-dialog__body {
        box-sizing: border-box;
        padding: 16px 22px;
        min-height: 250px;
    }

    .msg-header {
        border-radius: 16px 16px 0 0;
        width: 100%;
        height: 50px;
        position: relative;
        overflow: hidden;
        background-color: #0F3675;
        display: flex;
        align-items: center;
        color: #fff;

        .header-icon {
            width: 25px;
            height: 28px;
            margin-left: 22px;
            margin-right: 14px;
        }

        .header-title {
            font-size: 26px;
            font-weight: 700;
        }

        .header-close {
            cursor: pointer;
            position: absolute;
            bottom: 0;
            right: 20px;
            font-size: 32px;
        }
    }

    .msg-body {
        background-color: #ffffff;

        .account {
            font-size: 18px;
            font-weight: 700;
            color: rgba(51, 51, 51, 1);
            margin-bottom: 14px;
            width: 50%;
        }
    }
}

.send-btn {
    margin-left: auto;
    height: 40px;
    font-size: 20px;
    flex-grow: 1;
    flex-shrink: 0;
}
</style>