<script setup>
import { user,webInfo } from '~/store/index'
import message from '/images/message.png'
import messageNew from '/images/message-new.png'
import { verityPhone, verityPhoneRule } from '~/utils/reg'
import { dealPhone } from '~/utils/helper'
import _request from '~/utils/_request'

const showClose = ref(true)
const userInfo = ref({})
initUserInfo()
async function initUserInfo() {
  const { code, data } = await request({ baseURL: window.GLOBAL_CONFIG.uc, url: '/user/main/detail', data: { user_id: user.value.user_id } })
  if (code === '1')
    userInfo.value = data
  if (!data.user_phone) {
    showClose.value = false
    initDialog(true, '绑定手机', 2)
  }
}

const hasMessage = ref(true)

const router = useRouter()
function logout() {
  localStorage.removeItem('userInfo')
  router.replace('/login')
}

const dialogVisible = ref(false)
const dialogType = ref(0)
const dialogTitle = ref('')

const infoFormRef = ref()
const verifyFormRef = ref()
const modifyFormRef = ref()
const oldFormRef = ref()
const infoForm = ref({
  user_headpic: '',
  user_realname: '',
})
const verifyForm = ref({
  PhoneNumbers: '',
  vcode: '',
})
const modifyForm = ref({
  user_password: '',
  user_confirm_password: '',
})
const oldForm = ref({
  old_password: '',
})

const sendVcode = ref('')
function verityVcode(rule, _value, callback) {
  if (_value !== '') {
    if (sendVcode.value !== verifyForm.value.vcode)
      callback(new Error('验证码错误，请重新输入'))
    else
      callback()
  } else {
    callback(new Error('验证码错误，请重新输入'))
  }
}

function verityPwd(rule, _value, callback) {
  if (_value !== '') {
    // let reg = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[\da-zA-Z]{8,10}$/ 不包含特殊字符
    const reg = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,}/
    if (!reg.test(_value))
      callback(new Error('密码格式不正确，请重新输入'))
    else
      callback()
  } else {
    callback(new Error('请输入新密码'))
  }
}

function verityConfirmPwd(rule, _value, callback) {
  if (_value !== '') {
    if (modifyForm.value.user_password !== modifyForm.value.user_confirm_password)
      callback(new Error('两次密码输入不匹配，请重新输入'))
    else
      callback()
  } else {
    callback(new Error('请输入确认新密码'))
  }
}

function verityOldPwd(rule, _value, callback) {
  if (_value !== '') {
    callback()
  } else {
    callback(new Error('请输入旧密码'))
  }
}

const infoRules = reactive({
  PhoneNumbers: [{ validator: verityPhoneRule, trigger: 'blur' }],
  vcode: [{ validator: verityVcode, trigger: 'blur' }],
  user_password: [{ validator: verityPwd, trigger: 'blur' }],
  user_confirm_password: [{ validator: verityConfirmPwd, trigger: 'blur' }],
  old_password: [{ validator: verityOldPwd, trigger: 'blur' }],
})

function initDialog(show, title, type) {
  dialogVisible.value = show
  dialogTitle.value = title
  dialogType.value = type
}

function initParams() {
  for (const key in infoForm.value) {
    infoForm.value[key] = '';
  }

  for (const key in verifyForm.value) {
    verifyForm.value[key] = '';
  }

  for (const key in modifyForm.value) {
    modifyForm.value[key] = '';
  }

  for (const key in oldForm.value) {
    oldForm.value[key] = '';
  }

  seconds.value = 60;
  second.value = 60;
}

const seconds = ref(60)
const second = ref(60)
async function handleSend() {
  if (second.value !== seconds.value || !verityPhone(verifyForm.value.PhoneNumbers))
    return

  const inval = setInterval(() => {
    if (second.value === 0) {
      second.value = seconds.value
      clearInterval(inval)
    } else {
      second.value--
    }
  }, 1000)

  const { code, data } = await request({ baseURL: window.GLOBAL_CONFIG.uc, url: 'openapi/sms/send.php', data: { type: 'common', PhoneNumbers: verifyForm.value.PhoneNumbers } })
  if (code === '1')
    sendVcode.value = String(data.vcode)
}

function handleSubmit() {
  if (dialogType.value === 1) {
    infoFormRef.value?.validate(async (valid, fields) => {
      if (valid) {
        const { code, data } = await request({ baseURL: window.GLOBAL_CONFIG.uc, url: '/user/main/edit', data: { user_id: user.value.user_id, user_profile: infoForm.value } })
        if (code === '1') {
          initDialog(false, '', 0)
          ElMessage.success('保存成功！')
          initUserInfo()
        }
      } else {
        console.log('error submit!', fields)
      }
    })
  } else if (dialogType.value === 2) {
    if (showClose.value) {
      initDialog(false, '', 0)
      return
    }
    verifyFormRef.value?.validate(async (valid, fields) => {
      if (valid) {
        const { code, data } = await request({ baseURL: window.GLOBAL_CONFIG.uc, url: '/user/main/edit', data: { user_id: user.value.user_id, user_profile: { user_phone: verifyForm.value.PhoneNumbers } } })
        if (code === '1') {
          initDialog(false, '', 0)
          ElMessage.success('绑定成功！')
          initUserInfo()
        }
      } else {
        console.log('error submit!', fields)
      }
    })
  } else if (dialogType.value === 3) {
    modifyFormRef.value?.validate(async (valid, fields) => {
      if (valid) {
        const { code, data } = await request({ baseURL: window.GLOBAL_CONFIG.uc, url: '/user/main/edit', data: { user_id: user.value.user_id, user_main: { user_password: modifyForm.value.user_password } } })
        if (code === '1') {
          initDialog(false, '', 0)
          ElMessageBox.alert('<div class="p-30px">密码修改成功，请返回重新登录</div>', '', {
            dangerouslyUseHTMLString: true,
            confirmButtonText: '确定',
            center: true,
            customStyle: { "width": "auto", "border-radius": "24px", "padding": "5px 10px 30px" },
            confirmButtonClass: 'w-full h-48px',
            callback: (action) => {
              logout();
            }
          })
        }
      } else {
        console.log('error submit!', fields)
      }
    })
  } else if (dialogType.value === 4) {
    oldFormRef.value?.validate(async (valid, fields) => {
      if (valid) {
        const { code, data } = await _request({ baseURL: window.GLOBAL_CONFIG.uc, url: '/user/main/login', data: { user_name: userInfo.value.user_name, user_password: oldForm.value.old_password } })
        if (code === '1') {
          dialogType.value = 3;
        }
      }
    })
  } else if (dialogType.value === 5) {
    verifyFormRef.value?.validate(async (valid, fields) => {
      if (valid) {
        dialogType.value = 3;
      }
    })
  }
}

watch(
  () => dialogType.value, (val) => {
    initParams();
    if(val === 1) {
      infoForm.value = {
        user_headpic: userInfo.value.user_avatar.big,
        user_realname: userInfo.value.user_realname
      }
    } else if (val === 5) {
      verifyForm.value.PhoneNumbers = userInfo.value.user_phone;
      handleSend();
    }
  },
)

function goPersonalCenter() {
  let token = user.value.token
  user.value = null
  window.location.href = `https://qqyxt.bozedu.net/transfer.html?from=jlt&js_code=${webInfo.value?.js_code}&url_to=/page/profile.html&token=${token}`;
}
</script>

<template>
  <div class="line header h-77px w-full" >
    <div class="flex items-center justify-end pl-8 pr-15">

      <div class="flex items-center py-8px" >
        <!-- <img :src="hasMessage ? messageNew : message" alt="" class="mr-6"> -->
        <el-popover placement="bottom" :teleported="false" trigger="click" :width="130">
          <!-- <div class="item cursor-pointer text-center" @click="initDialog(true, '个人信息', 1)">
            个人信息
          </div> -->
          <div class="item cursor-pointer text-center" @click="goPersonalCenter()">
            个人中心
          </div>
          <div class="item cursor-pointer text-center" @click="initDialog(true, '绑定手机', 2)">
            绑定手机
          </div>
          <div class="item cursor-pointer text-center" @click="initDialog(true, '修改密码', 4)">
            修改密码
          </div>
          <!-- <div class="item cursor-pointer text-center" @click="logout">
            退出登录
          </div> -->
          <template #reference>
            <div class="flex flex-col items-center justify-center cursor-pointer">
              <el-avatar :src="userInfo.user_avatar?.big" class="align-middle" />
            <p class="text-16px mt-5px">{{userInfo.user_realname}}</p>
            </div>
          </template>
        </el-popover>

      </div>
    </div>

    <el-dialog v-model="dialogVisible" class="_" :title="dialogTitle" width="400px" destroy-on-close :show-close="showClose" :close-on-click-modal="false" @close="initDialog(false, '', 0)">
      <el-form v-if="dialogType === 1" ref="infoFormRef" label-position="top" :model="infoForm" :rules="infoRules" class="demo-ruleForm">
        <el-form-item label="头像">
          <common-upload v-model="infoForm.user_headpic" tip="上传比例限制1:1<br />建议上传小于500KB的jpg,jpeg,png格式图片" />
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="infoForm.user_realname" />
        </el-form-item>
      </el-form>
      <template v-if="dialogType === 2">
        <el-form v-if="!showClose" ref="verifyFormRef" label-position="top" :model="verifyForm" :rules="infoRules" class="demo-ruleForm">
          <el-form-item label="手机号码" prop="PhoneNumbers">
            <el-input v-model="verifyForm.PhoneNumbers" />
          </el-form-item>
          <el-form-item label="验证码" prop="vcode">
            <el-input v-model="verifyForm.vcode" />
            <div class="code absolute bottom-4px right-15px text-sm">
              <el-button v-if="second !== seconds" class="mb-8px h-32px w-72px" type="info">
                {{ second }}s
              </el-button>
              <br>
              <el-button class="h-32px w-72px" type="primary" :disabled="seconds === second && verityPhone(verifyForm.PhoneNumbers) ? false : true" @click="handleSend">
                发送
              </el-button>
            </div>
          </el-form-item>
        </el-form>
        <div class="text-center text-16px leading-30px" v-else>
          <div>你已绑定手机</div>
          <div>{{ dealPhone(userInfo.user_phone) }}</div>
        </div>
      </template>
      <el-form ref="oldFormRef" v-if="dialogType === 4" label-position="top" :model="oldForm" :rules="infoRules" class="demo-ruleForm">
        <el-form-item label="旧密码" prop="old_password">
          <el-input v-model="oldForm.old_password" type="password" show-password />
        </el-form-item>
        <div class="text-right">
          <div class="inline-block cursor-pointer text-hex-04A4D0 border-b border-hex-04A4D0" @click="dialogType=5">手机号码验证修改</div>
        </div>
      </el-form>
      <el-form v-if="dialogType === 5" label-position="top" class="demo-ruleForm">
        <div class="text-center text-16px leading-30px mb-20px">已向手机号{{ dealPhone(verifyForm.PhoneNumbers) }}的手机号发送验证码，请输入验证码验证</div>
        <el-form ref="verifyFormRef" label-position="top" :model="verifyForm" :rules="infoRules" class="demo-ruleForm">
          <el-form-item label="验证码" prop="vcode">
            <el-input v-model="verifyForm.vcode" />
            <div class="code absolute bottom-4px right-15px text-sm">
              <el-button v-if="second !== seconds" class="mb-8px h-32px w-72px" type="info">
                {{ second }}s
              </el-button>
              <br>
              <el-button class="h-32px w-72px" type="primary" :disabled="seconds === second && verityPhone(verifyForm.PhoneNumbers) ? false : true" @click="handleSend">
                发送
              </el-button>
            </div>
          </el-form-item>
        </el-form>
        <div class="text-right">
          <div class="inline-block cursor-pointer text-hex-04A4D0 border-b border-hex-04A4D0" @click="dialogType=4">旧密码验证修改</div>
        </div>
      </el-form>
      <el-form v-if="dialogType === 3" ref="modifyFormRef" label-position="top" :model="modifyForm" :rules="infoRules" class="demo-ruleForm">
        <el-form-item label="新密码" prop="user_password">
          <el-input v-model="modifyForm.user_password" type="password" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="user_confirm_password">
          <el-input v-model="modifyForm.user_confirm_password" type="password" show-password />
        </el-form-item>
      </el-form>
      <el-button class="mt-30px h-48px w-full" type="primary" @click="handleSubmit">
        {{ dialogType === 2 && !showClose ? '绑定' : '确认' }}
      </el-button>
      <div v-if="dialogType === 3" class="tip">
        密码要求：字母数字结合，最少设置8个字符，包含字母大小写和数字特殊符号（所有密码通用设置）
      </div>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
@use "~/styles/dialog.scss";
:deep() {
  .el-popover.el-popper {
    min-width: 130px !important;
  }
  .item {
    line-height: 40px;
    &:hover {
      background: #e8f7e0;
      border-radius: 8px;
    }
  }
}
</style>
