<template>
<view class="page">
  <uni-section :title="$t('user.userInfo')" type="line" />
  <uni-card :is-shadow="false">
    <view class="avatar-item flex-row align-center">
      <view style="color: #dd524d">*</view>
      <view style="margin: 10px 0">{{ $t('user.avatar') }}</view>
      <image class="avatar" :src="form.avatar ? form.avatar : '/static/common/avata.gif'" @click="changeAvatar" />
    </view>
    <uni-forms ref="formRef" :model="form" :rules="rules" err-show-type="toast" label-width="80px">
      <uni-forms-item :label="$t('user.phone')" name="mobile" required>
        <uni-easyinput v-model="form.mobile" :placeholder="$t('operation.PleaseFillIn')" :input-border="false" />
      </uni-forms-item>
    </uni-forms>
    <button type="primary" style="margin-top: 20px; margin-bottom: 10px" @click="submit">{{ $t('operation.save') }}</button>
  </uni-card>

  <uni-section :title="$t('user.updatePassword')" type="line" />
  <uni-card :is-shadow="false" style="margin-top: 10px">
    <uni-forms ref="pwdFormRef" :model="pwdForm" :rules="pwdRules" err-show-type="toast" label-width="80px">
      <uni-forms-item :label="$t('user.oldPassword')" name="oldPwd" required>
        <uni-easyinput v-model="pwdForm.oldPwd" type="password" :placeholder="$t('operation.PleaseFillIn')" :input-border="false" />
      </uni-forms-item>
      <uni-forms-item :label="$t('user.password')" name="pwd" required>
        <uni-easyinput v-model="pwdForm.pwd" type="password" :placeholder="$t('operation.PleaseFillIn')" :input-border="false" />
      </uni-forms-item>
      <uni-forms-item :label="$t('user.confirmPassword')" name="confirmPwd" required>
        <uni-easyinput v-model="pwdForm.confirmPwd" type="password" :placeholder="$t('operation.PleaseFillIn')" :input-border="false" />
      </uni-forms-item>
    </uni-forms>
    <button type="primary" style="margin-top: 20px; margin-bottom: 10px" @click="changePassword">{{ $t('operation.submit') }}</button>
  </uni-card>
</view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app'
import { getCurrentInstance, reactive, ref } from "vue";
import { updateAvatar, updateUserInfo, changePassword as change } from "@/api/login";
import $store from '@/store'

const formRef = ref()
const form = reactive({
  mobile: '',
})

const pwdFormRef = ref()
const pwdForm = reactive({
  oldPwd: '',
  pwd: '',
  confirmPwd: '',
})

const { appContext } = getCurrentInstance()
const t = appContext.config.globalProperties.$t
const rules = reactive({
  mobile: { rules: [{ required: true, errorMessage: t('user.phoneHint') }] }
})
const pwdRules = reactive({
  oldPwd: { rules: [{ required: true, errorMessage: t('user.oldPasswordHint') }] },
  pwd: { rules: [{ required: true, errorMessage: t('user.passwordHint') }] },
  confirmPwd: { rules: [{ required: true, errorMessage: t('user.confirmPasswordHint') }] },
})

const changeAvatar = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: async (res) => {
      const response = await updateAvatar(res.tempFilePaths[0])
      if (response.code === 0) {
        form.avatar = response.data
        toast(t('operation.success'))
        uni.$emit('updateUserInfo')
      }
    },
    fail: (error) => {
      console.log(error)
    }
  })
}

const submit = async () => {
  try {
    const valid = await formRef.value.validate()
    if (!valid) return

    const code = (await updateUserInfo(form.mobile)).code
    if (code === 0) {
      toast(t('operation.success'))
      uni.$emit('updateUserInfo')
    }
  } catch (e) {
    console.log(e)
  }
}

const userStore = $store('user')
const changePassword = async () => {
  try {
    const valid = await pwdFormRef.value.validate()
    if (!valid) return
    if (pwdForm.oldPwd === pwdForm.pwd) {
      toast(t('user.passwordError1'))
      return
    } else if (pwdForm.pwd !== pwdForm.confirmPwd) {
      toast(t('user.passwordError2'))
      return
    }

    const code = (await change(pwdForm.oldPwd, pwdForm.pwd)).code
    if (code === 0) {
      toast(t('operation.success'))
      await userStore.LogOut()
      uni.reLaunch({ url: '/pages/user/login' })
    }
  } catch (e) {
    console.log(e)
  }
}

const toast = (msg) => {
  uni.showToast({ title: msg, icon: 'none' })
}

const userInfo = ref({})
onLoad((options) => {
  const info = JSON.parse(options.info)
  userInfo.value = info
  form.mobile = info.mobile
  form.avatar = info.avatar
})
</script>

<style scoped lang="scss">
:deep(.uni-section) {
  background-color: transparent;

  .uni-section-header {
    padding: 10px 0;
  }
}
:deep(.uni-card) {
  margin: 0 !important;
  padding: 0 !important;

  .uni-card__content {
    padding: 0 10px !important;
  }
}

:deep(.uni-forms-item) {
  margin-bottom: 0;
  padding: 8px 0;
  border-bottom: 1px dashed #CACCCF;
}

.avatar-item {
  border-bottom: 1px dashed #CACCCF;
  padding: 14px 0;
}

.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  margin-left: 30px;
}
</style>