<template>
  <div class="settings">
    <el-tabs tab-position="left">
      <el-tab-pane label="密码设置">
        <div class="form-wrapper">
          <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="rules"
            label-width="140px"
            class="demo-ruleForm"
            status-icon
          >
            <el-form-item label="旧密码：" v-if="from === 1" prop="old_password">
              <el-input type="password" v-model="ruleForm.old_password" placeholder="请输入旧密码" />
            </el-form-item>
            <el-form-item label="新密码：" prop="new_password">
              <el-input type="password" v-model="ruleForm.new_password" placeholder="请输入新密码" @input="blurValidate(ruleFormRef)" />
            </el-form-item>
            <el-form-item label="再次输入新密码：" prop="new_password2">
              <el-input type="password" v-model="ruleForm.new_password2" placeholder="请再次输入新密码" @input="blurValidate(ruleFormRef)" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary"   size="large" @click="submitForm(ruleFormRef)">
                提交
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>
      <el-tab-pane label="用户名设置">
        <div class="form-wrapper">
          <el-form
            ref="ruleFormRef2"
            :model="ruleForm2"
            :rules="rules2"
            label-width="140px"
            class="demo-ruleForm"
            status-icon
          >
            <el-form-item label="用户名：" prop="account">
              <el-input type="text" :disabled="!!user.profile.user_name" v-model="ruleForm2.account" placeholder="请输入用户名" />
            </el-form-item>
            <el-form-item v-if="!user.profile.user_name">
              <el-button type="primary"   size="large" @click="submitForm2(ruleFormRef2)">
                提交
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>
      <el-tab-pane label="手机号设置">
        <div class="form-wrapper">
          <el-form
            ref="ruleFormRef3"
            :model="ruleForm3"
            :rules="rules3"
            label-width="140px"
            class="demo-ruleForm"
            status-icon
          >
            <el-form-item label="手机号：" prop="mobile">
              <el-input type="text" :disabled="!!user.profile.mobile" v-model="ruleForm3.mobile" placeholder="请输入手机号" />
            </el-form-item>
            <el-form-item label="验证码：" prop="captcha">

              <div style="display: flex;align-items: center;justify-content: space-between;width: 100%;">
                <el-input type="text" :disabled="ruleForm3.mobile.length !== 11" v-model="ruleForm3.captcha" placeholder="请输入验证码" />
                <el-button v-if="!!user.profile.mobile" type="primary" @click="getCaptcha" style="width: 100px;" :disabled ="!can_send">{{smsMessage}}</el-button>
                <el-button v-else @click="getCaptcha2" type="primary" style="width: 100px;" :disabled ="!can_send">{{smsMessage}}</el-button>
              </div>
            </el-form-item>
            <el-form-item >
              <el-button v-if="!!user.profile.mobile" type="primary"   size="large" @click="submitForm3(ruleFormRef3)">
                解绑
              </el-button>
              <el-button v-else type="primary"   size="large" @click="submitForm4(ruleFormRef3)">
                绑定
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>
    </el-tabs>

  </div>
  <div class="mob-setting">
    <div class="info-wrap">
      <div class="row-wrap">
        <div class="img-outer">
          <img class="avatar" :src="img('gamer.png')" alt=""/>
        </div>
        <div class="info">
          <div class="account" v-if="user.profile.user_name" >{{ user.profile.user_name }}</div>
          <div class="account" v-else>未设置</div>
          <div class="mobile" v-if="user.profile.mobile">{{user.profile.mobile}}</div>
          <div class="mobile" v-else>未绑定</div>
        </div>
      </div>
      <div class="menu">
        <van-tabs v-model:active="active" animated color="#BD5B8F" background="transparent" title-inactive-color="#2F4858" title-active-color="">
          <van-tab title="密码设置" name="a"/>
          <van-tab title="用户名设置" name="b"/>
          <van-tab title="手机号设置" name="c"/>
        </van-tabs>
      </div>
    </div>
    <div v-if="active === 'a'" class="form-wrapper">
      <van-form @submit="onSubmit">
        <van-field
          v-if="from === 1"
          v-model="ruleForm.old_password"
          name="旧密码"
          label="旧密码"
          type="password"
          placeholder="请填写旧密码"
          :rules="[{ required: true, message: '请填写旧密码' },{ validator: checkAgeMob}]"
        />
        <van-field
          v-model="ruleForm.new_password"
          type="password"
          name="新密码"
          label="新密码"
          placeholder="请填写新密码"
          :rules="[{ required: true, message: '请填写新密码' },{ validator: checkAgeMob}]"
        />
        <van-field
          v-model="ruleForm.new_password2"
          type="password"
          name="新密码"
          label="新密码"
          placeholder="请再次填写新密码"
          :rules="[{ required: true, message: '请再次填写新密码' },{ validator: checkAgeMob}]"
        />
        <div style="margin: 16px;display: flex;flex-direction: row-reverse;">
          <van-button style="width: 100%;padding: 10px;" round block type="primary"  native-type="submit">
            提交
          </van-button>
        </div>
      </van-form>
    </div>
    <div v-else-if="active === 'b'" class="form-wrapper">
      <van-form @submit="onSubmit2">
        <van-field
          v-model="account"
          type="text"
          name="用户名"
          :readonly="!!user.profile.user_name"
          label="用户名"
          placeholder="请填写用户名"
          :rules="[{ required: true, message: '请填写用户名',trigger: 'onBlur' },{ pattern: pattern, message: '请输入以字母为开头，长度为6-20位的用户名'}]"
        />
        <div v-if="!user.profile.user_name" style="margin: 16px;display: flex;flex-direction: row-reverse;">
          <van-button round block style="width: 100%;padding: 10px;" type="primary"  native-type="submit">
            提交
          </van-button>
        </div>
      </van-form>
    </div>
    <div v-else-if="active === 'c'" class="form-wrapper">
      <van-form>
        <van-field
          v-model="ruleForm3.mobile"
          type="text"
          name="手机号"
          :readonly="!!user.profile.mobile"
          label="手机号"
          placeholder="请填写手机号"
          :rules="[{ required: true, message: '请填写手机号',trigger: 'onBlur' },{ pattern: pattern2, message: '请输入正确手机号'}]"
        />
        <van-field
          v-model="ruleForm3.captcha"
          type="number"
          name="验证码"
          label="验证码"
          placeholder="请输入验证码"
          :rules="[{ required: true, message: '请填写验证码' }]">
          <template #button>
            <van-button v-if="!!user.profile.mobile"  size="small" type="primary" style="min-width: 20vw;" :disabled="!can_send" @click="getCaptcha">{{ smsMessage }}</van-button>
            <van-button v-else size="small"  type="primary" style="min-width: 20vw;" :disabled="!can_send" @click="getCaptcha2">{{ smsMessage }}</van-button>
          </template>
        </van-field>
        <div style="margin: 16px;">
          <van-button v-if="!!user.profile.mobile" style="width: 100%;padding: 10px;" round block type="primary"  @click="onSubmit3">
            解绑
          </van-button>
          <van-button v-else round block type="primary" style="width: 100%;padding: 10px;"  @click="onSubmit4">
            绑定
          </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, inject } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { resetPassword, setPassword, userAccount, unbindCaptcha, clearMobile, bindCaptcha, bindMobile } from '@/api/index'
import Message from '@/utils/Message'
import { useStore } from '@/store/index'
import { showSuccessToast, showFailToast } from 'vant'

const { user } = useStore()
const img:any = inject('img')
const active = ref('a')
const ruleFormRef = ref<FormInstance>()
const ruleFormRef2 = ref<FormInstance>()
const ruleFormRef3 = ref<FormInstance>()
interface RuleForm {
  old_password: string
  new_password: string
  new_password2: string
  account?:string
}
const ruleForm = reactive<RuleForm>({
  old_password: '',
  new_password: '',
  new_password2: ''
})
const ruleForm2 = reactive({
  account: ''
})
const ruleForm3 = reactive({
  mobile: '',
  captcha: ''
})
const blurValidate = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  if (!ruleForm.new_password || !ruleForm.new_password2) return
  formEl.validateField(['new_password', 'new_password2']).then((res) => {
    console.log(res)
  }).catch((error) => {
    console.log(error)
  })
}
const checkAge = (_a:any, _b:any, callback:any) => {
  // ...args:any
  // const callback = args[2]
  if (!ruleForm.new_password2.length || !ruleForm.new_password.length) {
    return callback()
  }
  if (ruleForm.new_password2 !== ruleForm.new_password) {
    callback(new Error('两次输入的新密码不一致'))
  } else {
    callback()
  }
}
const rules2 = reactive<FormRules>({
  account: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { pattern: '^[a-zA-Z][a-zA-Z0-9]{5,19}$', message: '请输入以字母为开头，长度为6-20位的用户名', trigger: 'blur' }
  ]
})
const rules3 = reactive<FormRules>({
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/, message: '请输入正确手机号', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
})
const rules = reactive<FormRules>({
  old_password: [
    { required: true, message: '请输入旧密码', trigger: 'blur' },
    { min: 6, max: 20, message: '请输入6-20位密码', trigger: 'blur' }
  ],
  new_password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { validator: checkAge },
    { min: 6, max: 20, message: '请输入6-20位密码', trigger: 'blur' }
  ],
  new_password2: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { validator: checkAge },
    { min: 6, max: 20, message: '请输入6-20位密码', trigger: 'blur' }
  ]
})

const submitForm = async(formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async(valid, fields) => {
    if (valid) {
      console.log('submit!')

      if (from.value === 1) {
        // 账号密码登录
        await resetPassword({ old_pass: ruleForm.old_password, new_pass: ruleForm.new_password }).then((res) => {
          console.log(res)
          Message.success(res.data.msg)
        }).catch((error) => {
          console.log(error)
          Message.error(error.data.msg)
        })
      } else if (from.value === 2) {
        await setPassword({ new_pass: ruleForm.new_password }).then((res) => {
          console.log(res)
          Message.success(res.data.msg)
        }).catch((error) => {
          console.log(error)
          Message.error(error.data.msg)
        })
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}
const submitForm2 = async(formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async(valid, fields) => {
    if (valid) {
      console.log('submit!')
      await userAccount({ account: ruleForm2.account.toLowerCase() }).then((res) => {
        console.log(res)
        Message.success(res.data.msg)
        user.getUserProfile()
      }).catch((error) => {
        console.log(error)
        Message.error(error.data.msg)
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}
const submitForm3 = async(formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async(valid, fields) => {
    if (valid) {
      console.log('submit!')
      await clearMobile({ captcha: ruleForm3.captcha }).then(async(res) => {
        console.log(res)
        Message.success(res.data.msg)
        await user.getUserProfile()
        ruleForm3.mobile = user.profile.mobile
        ruleForm3.captcha = ''
        clearInterval(interval)
        smsMessage.value = '获取验证码'
        can_send.value = true
      }).catch((error) => {
        console.log(error)
        Message.error(error.data.msg)
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}
const submitForm4 = async(formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async(valid, fields) => {
    if (valid) {
      console.log('submit!')
      await bindMobile({ mobile: ruleForm3.mobile, captcha: ruleForm3.captcha }).then(async(res) => {
        console.log(res)
        Message.success(res.data.msg)
        await user.getUserProfile()
        ruleForm3.mobile = user.profile.mobile
        ruleForm3.captcha = ''
        clearInterval(interval)
        smsMessage.value = '获取验证码'
        can_send.value = true
      }).catch((error) => {
        console.log(error)
        Message.error(error.data.msg)
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}
const can_send = ref<boolean>(true)
const smsMessage = ref<'获取验证码' | number>('获取验证码')
const VALID = 60

const from = ref<1 | 2>(1)
const getCaptcha = async() => {
  await unbindCaptcha().then((res) => {
    console.log(res)
    can_send.value = false
    smsMessage.value = VALID
    settimes()
    Message.success('验证码已发送，请注意查收')
  }).catch((error) => {
    console.log(error)
    Message.error(error.data.msg)
  })
}
const getCaptcha2 = async() => {
  await bindCaptcha({ mobile: ruleForm3.mobile }).then((res) => {
    console.log(res)
    can_send.value = false
    smsMessage.value = VALID
    settimes()
    Message.success('验证码已发送，请注意查收')
  }).catch((error) => {
    console.log(error)
    Message.error(error.data.msg)
  })
}
let interval:any
const settimes = () => {
  const setTimeFn = () => {
    (smsMessage.value as number)--
    if (smsMessage.value as number < 0 || can_send.value === true) {
      clearInterval(interval)
      can_send.value = true
      smsMessage.value = '获取验证码'
    }
  }
  interval = setInterval(function() {
    setTimeFn()
  }, 1000)
}

// mob
const checkAgeMob = (value:any, rule:any) => {
  console.log(value, rule)
  if (value.length < 6 || value.length > 20) {
    return '请输入6-20位密码'
  }
  return ''
}
const onSubmit = async() => {
  if (ruleForm.new_password2 !== ruleForm.new_password) {
    return showFailToast('两次输入的密码不一致！')
  }
  if (from.value === 1) {
    // 账号密码登录
    await resetPassword({ old_pass: ruleForm.old_password, new_pass: ruleForm.new_password }).then((res) => {
      console.log(res)
      showSuccessToast(res.data.msg)
    }).catch((error) => {
      console.log(error)
      showFailToast(error.data.msg)
    })
  } else if (from.value === 2) {
    await setPassword({ new_pass: ruleForm.new_password }).then((res) => {
      console.log(res)
      showSuccessToast(res.data.msg)
    }).catch((error) => {
      console.log(error)
      showFailToast(error.data.msg)
    })
  }
}
const onSubmit2 = async() => {
  await userAccount({ account: account.value.toLowerCase() }).then((res) => {
    console.log(res)
    showSuccessToast(res.data.msg)
    user.getUserProfile()
  }).catch((error) => {
    console.log(error)
    showFailToast(error.data.msg)
  })
}
const onSubmit3 = async() => {
  await clearMobile({ captcha: ruleForm3.captcha }).then(async(res) => {
    console.log(res)
    showSuccessToast(res.data.msg)
    await user.getUserProfile()
    ruleForm3.mobile = user.profile.mobile
    ruleForm3.captcha = ''
    clearInterval(interval)
    smsMessage.value = '获取验证码'
    can_send.value = true
  }).catch((error) => {
    console.log(error)
    showFailToast(error.data.msg)
  })
}
const onSubmit4 = async() => {
  await bindMobile({ mobile: ruleForm3.mobile, captcha: ruleForm3.captcha }).then(async(res) => {
    console.log(res)
    showSuccessToast(res.data.msg)
    await user.getUserProfile()
    ruleForm3.mobile = user.profile.mobile
    ruleForm3.captcha = ''
    clearInterval(interval)
    smsMessage.value = '获取验证码'
    can_send.value = true
  }).catch((error) => {
    console.log(error)
    showFailToast(error.data.msg)
  })
}
const pattern = ref<RegExp>(/^[a-zA-Z][a-zA-Z0-9]{5,19}$/)
const pattern2 = ref<RegExp>(/^(?:(?:\+|00)86)?1[3-9]\d{9}$/)
const account = ref<string>('')
onMounted(async() => {
  from.value = parseInt(localStorage.getItem('from') as string)as 1 | 2
  console.log(from.value)

  await user.getUserProfile()
  ruleForm2.account = user.profile?.user_name
  ruleForm3.mobile = user.profile?.mobile
  account.value = user.profile?.user_name
})

</script>

<style lang="scss" scoped>
.settings{
  width: 100%;
  background-color: #fff;
  min-height: 40rem;
  padding: 3rem;
  box-sizing: border-box;
  .form-wrapper{
    width: 70%;
    padding-top: 1rem;
  }
}
.mob-setting{
  display: none;
  width: 100vw;
  min-height: calc(100vh - 60px);
  .info-wrap{
    width: 100%;
    height: 50vw;
    background-image: linear-gradient(#FFE8D2, #C4FCF0);
    overflow: hidden;
    position: relative;
    .row-wrap{
      display: flex;
      align-items: center;
      margin-top: 8vw;
      padding-left: 5vw;
    }
    .img-outer{
      // margin: 10vw 0 0 5vw;
      background-color: #fff;
      border-radius: 50%;
      width: 24vw;
      height: 24vw;
      display: flex;
      align-items: center;
      justify-content: center;
      overflow: hidden;
      box-shadow: 1px 3px 4px rgba($color: #000000, $alpha: .5);
    }
    .avatar{
      width: 20vw;
      height: 20vw;
      border-radius: 50%;
    }
    .info{
      margin-left: 2vw;
      .account{
        font-size: 14px;
        margin-bottom: 2vw;
      }
      .mobile{
        font-size: 13px;
      }
    }
  }
  .menu{
    width: 100vw;
    height: 44px;
    position: absolute;
    bottom: 1px;
    left: 0;
  }
}
</style>
