<template>
  <el-form ref="pwdRef" :model="user" :rules="rules" label-width="140px" style="width: 500px;height: 260px;">
    <el-form-item label="原手机号码">
      <el-input v-model="state.mobile" placeholder="请输入原手机号码" type="text" disabled/>
    </el-form-item>
    <el-form-item label="原手机号码验证码" prop="oldCode">
      <el-input
          v-model="user.oldCode"
          type="text"
          size="large"
          auto-complete="off"
          placeholder="请输入原手机号码验证码">
        <template #append>
          <el-button @click="startCountdown(0)" :disabled="isOldCounting">
            {{ isOldCounting ? `重新发送(${countDownOld})` : '发送验证码' }}
          </el-button>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item label="新手机号码" prop="mobile">
      <el-input v-model="user.mobile" :placeholder="user.oldCode !== ''?'请输入新手机号码':'请先输入原手机号码验证码'"
                type="text"/>
    </el-form-item>
    <el-form-item label="验证码" prop="code">
      <el-input
          v-model="user.code"
          type="text"
          size="large"
          auto-complete="off"
          :placeholder="user.oldCode !== ''?'请输入新手机号码验证码':'请先输入原手机号码验证码'"
      >
        <template #append>
          <el-button @click="startCountdown(1)" :disabled="isCounting">
            {{ isCounting ? `重新发送(${countdown})` : '发送验证码' }}
          </el-button>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submit">保存</el-button>
      <!--      <el-button type="danger" @click="close">关闭</el-button>-->
    </el-form-item>
  </el-form>
</template>

<script setup>
import {updateMobile} from "@/api/system/user";
import {sendCode} from "@/api/login.js";
import {ElMessage, ElMessageBox} from "element-plus";
import useUserStore from "@/store/modules/user.js";
import {createPay} from "@/api/computingResource.js";

const userStore = useUserStore()

const {proxy} = getCurrentInstance();

const props = defineProps({
  state: {
    type: Object
  }
})

const user = reactive({
  oldMobile: undefined,
  oldCode: '',
  mobile: undefined,
  code: undefined
});
const countdown = ref(60); // 倒计时时间，初始为60秒
const countDownOld = ref(60); // 倒计时时间，初始为60秒
const isCounting = ref(false); // 是否正在倒计时的标志
const isOldCounting = ref(false); // 是否正在倒计时的标志
const pwdRef = ref(null); // 是否正在倒计时的标志

const rules = ref({
  oldCode: [{required: true, message: "原手机号码验证码不能为空", trigger: "blur"}],
  code: [{required: true, message: "原手机号码验证码不能为空", trigger: "blur"}],
  mobile: [
    {required: true, message: '请输入新手机号码', trigger: 'blur'},
    {validator: validatePhone, trigger: 'blur'}
  ]
});

function validatePhone(rule, value, callback) {
  const reg = /^1[3456789]\d{9}$/
  if (!reg.test(value)) {
    callback(new Error('请输入正确的手机号'))
    return
  }
  callback()
}


function getCode(val) {
  const num = val === 0 ? props.state.mobile : user.mobile
  sendCode({mobile: num, scene: 2}).then(res => {
    if (res.data === true) {
      ElMessage({message: '短信已发送请注意查收', type: 'success'})
    }
  })
}

// 开始倒计时的方法
const startCountdown = (val) => {
  if (val === 0) {
    getCode(val)
    if (isOldCounting.value) return; // 如果已经在倒计时，则不重复开始
    isOldCounting.value = true; // 设置正在倒计时的标志为true
    const timer = setInterval(() => {
      if (countDownOld.value > 0) {
        countDownOld.value--; // 倒计时减1
      } else {
        clearInterval(timer); // 倒计时结束，清除定时器
        isOldCounting.value = false; // 设置正在倒计时的标志为false
        countDownOld.value = 60; // 重置倒计时时间
      }
    }, 1000); // 每1000毫秒（1秒）执行一次
  }
  if (val === 1) {
    pwdRef.value.validateField('mobile', valid => {
      getCode(val)
      if (valid) {
        if (isCounting.value) return; // 如果已经在倒计时，则不重复开始
        isCounting.value = true; // 设置正在倒计时的标志为true
        const timer = setInterval(() => {
          if (countdown.value > 0) {
            countdown.value--; // 倒计时减1
          } else {
            clearInterval(timer); // 倒计时结束，清除定时器
            isCounting.value = false; // 设置正在倒计时的标志为false
            countdown.value = 60; // 重置倒计时时间
          }
        }, 1000); // 每1000毫秒（1秒）执行一次
      }
    })
  }
};

/** 提交按钮 */
function submit() {
  proxy.$refs.pwdRef.validate(valid => {
    if (valid) {
      updateMobile(user).then(res => {
        if (res.code === 0 && res.data) {
          // proxy.$modal.msgSuccess("修改成功,请重新登录");
          ElMessageBox.confirm(
              '修改成功,请重新登录',
              '提示',
              {
                confirmButtonText: '确认',  // 确认按钮文字
                // cancelButtonText: '取消',   // 取消按钮文字
                showCancelButton: false,
                showClose: false,
                type: 'warning'             // 对话框类型（警告样式）
              }
          )
              .then(() => {
                userStore.logOut().then(() => {
                  location.href = '/index'
                })
              })
        }
      });
    }
  });
};

/** 关闭按钮 */
function close() {
  proxy.$tab.closePage();
};
</script>
