<template>
  <view class="container">
    <uni-section class="mb-10" title="个人资料" type="line"></uni-section>
    <uni-list :border="true">
      <uni-list-item title="用户名称" :rightText="detail.self?.name">
        <template #footer>
          <view style="width:100%">
            <EditorListItem style="width:100%" v-model="modifyParams.name" placeholder="用户名称"
              :old-value="detail.self?.name" :not-allow-null="true" :components-type="ComponentsType.STRINGINPUT"
              @modify="modifyInfo" />
          </view>
        </template>
      </uni-list-item>
      <uni-list-item title="手机号码" :rightText="detail.self?.mobile" />
      <uni-list-item title="电子邮箱" :rightText="detail.self?.email">
        <template #footer>
          <view style="width:100%">
            <EditorListItem style="width:100%" v-model="modifyParams.email" placeholder="电子邮箱"
              :old-value="detail.self?.email" :not-allow-null="false" :components-type="ComponentsType.STRINGINPUT"
              @modify="modifyInfo" />
          </view>
        </template>
      </uni-list-item>
      <uni-list-item title="注册时间" :rightText="detail.self?.reg_time">
      </uni-list-item>
      <uni-list-item title="最近活动" :rightText="detail.self?.act_time">
      </uni-list-item>
    </uni-list>
    <view style="margin-top: 20rpx;" v-if="!showResetPwdForm">
      <custom-button width="100%" type="filled" color="#007aff" @click="handlerResetPwd()">重置密码</custom-button>
    </view>
    <view v-else>
      <uni-section class="mb-10" title="重置密码" type="line"></uni-section>
      <view style="padding:20rpx;background: #fff;">
        <uni-forms ref="formRef" :modelValue="resetPwdFormData" :rules="rules" validateTrigger="submit"
          label-position="top">
          <uni-forms-item label="原密码" required label-width="90px" name="old_pass">
            <uni-easyinput v-model="resetPwdFormData.old_pass" placeholder="请输入原登录密码" type="password" />
          </uni-forms-item>
          <uni-forms-item label="新密码" required label-width="90px" name="new_pass">
            <uni-easyinput v-model="resetPwdFormData.new_pass" placeholder="请输入新的登录密码" type="password" />
          </uni-forms-item>
          <uni-forms-item label="确认新密码" required label-width="90px" name="confirm_new_pass">
            <uni-easyinput v-model="resetPwdFormData.confirm_new_pass" placeholder="请再次输入新登录密码" type="password" />
          </uni-forms-item>
        </uni-forms>
        <view style="margin-bottom: 10px;display: flex;">
          <custom-button width="100%" type="filled" color="#f2f3f5" style="flex:1;margin-right: 5px;"
            @click="handlerCancelResetPwd()"><text style="color: #606266;">取消</text></custom-button>
          <custom-button width="100%" type="filled" color="#007aff" style="flex:1"
            @click="handlerConfirmResetPwd()">重置</custom-button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { getSelfInfo, setSelfInfo } from '@/api/base/client';
import { SelfInfoResParams } from '@/types/client';
import EditorListItem from '@/components/editor-list-item/editor-list-item.vue'
import { ComponentsType } from '@/enums/api'
import { useEmitt } from '@/logics/mitt/useEmitt';
import { Md5 } from 'ts-md5'

const detail = reactive<{ self?: SelfInfoResParams }>({
  self: undefined
})

const showResetPwdForm = ref(false)
const formRef = ref()
const { emitter } = useEmitt()

const resetPwdFormData = ref<{
  old_pass?: string
  new_pass?: string
  confirm_new_pass?: string
}>({

})

const modifyParams = ref<{
  name?: string,
  email?: string
}>({

})

const rules = {
  // 对name字段进行必填验证
  old_pass: {
    // name 字段的校验规则
    rules: [
      // 校验 name 不能为空
      {
        required: true,
        errorMessage: '原密码不能为空',
      }
    ]
  },
  new_pass: {
    // name 字段的校验规则
    rules: [
      // 校验 name 不能为空
      {
        required: true,
        errorMessage: '新密码不能为空',
      }
    ]
  },
  confirm_new_pass: {
    // name 字段的校验规则
    rules: [
      // 校验 name 不能为空
      {
        required: true,
        errorMessage: '再次确认密码不能为空',
      }, {
        validateFunction: function (rule: any, value: any, data: any, callback: any) {
          if (value !== data.new_pass) {
            callback('两次密码不一致')
          }
          return true
        }
      }
    ]
  }


}

const getUserInfo = async () => {
  const result: SelfInfoResParams = await getSelfInfo();
  detail.self = result
  modifyParams.value.name = result.name
  modifyParams.value.email = result.email
  uni.setNavigationBarTitle({
    title: result.name,
  })
}

// 修改用户名或邮箱
const modifyInfo = async () => {
  try {
    const { name, email } = modifyParams.value
    await setSelfInfo({
      name,
      email
    })
    uni.showToast(({
      icon: 'success',
      title: '修改成功'
    }))
    emitter.emit('set_user_name', name)
    uni.setNavigationBarTitle({
      title: name!,
    })
  } catch (e) {
    getUserInfo()
  }

}

// 显示重置密码表单
const handlerResetPwd = async () => {
  showResetPwdForm.value = true
}

// 取消重置密码
const handlerCancelResetPwd =  () => {
  resetPwdFormData.value = {}
  formRef.value?.clearValidate()
  showResetPwdForm.value = false
}

// 确认重置密码
const handlerConfirmResetPwd = async () => {
  const isValid = await formRef.value?.validate()
  if (!isValid) {
    return
  }
  const { old_pass, new_pass } = resetPwdFormData.value;
  await setSelfInfo({
    old_pass: Md5.hashStr(old_pass!) ,
    new_pass: Md5.hashStr(new_pass!) 
  })
  uni.showToast({
    icon: 'success',
    title: '重置成功'
  })
  handlerCancelResetPwd()
}
onMounted(() => {
  getUserInfo()
})

</script>
<script lang="ts">
export default {
  options: {
    styleIsolation: 'apply-shared', //解除样式隔离
  }

}
</script>
<style scoped>
.container {
  padding: 0 5px 40px 5px;
}

:deep(.uni-list-item__content-note) {
  overflow-wrap: break-word;
}

:deep(.uni-list-item__content) {
  flex-direction: row;
  align-items: center;
  flex: 0 0 80px;
}

:deep(.uni-list-item__content-title) {
  font-size: 13px;
  color: #3b4144a8;
}

:deep(.uni-list-item__extra) {
  flex: 1 1 auto;
}

:deep(.uni-list-item__extra-text) {
  color: #5d5959;
  font-size: 13px;
  width: 200px;
  text-overflow: ellipsis;
  text-align: right;
  text-wrap: wrap;
  overflow-wrap: anywhere;
  white-space-collapse: collapse;
}

.slot-box {
  /* #ifndef APP-NVUE */
  display: flex;
  /* #endif */
  flex-direction: row;
  align-items: center;
  width: 45px;
  background-color: rgb(201, 205, 212);
  border-radius: 4px;
  margin-right: 10px;
  height: 45px;
}


.slot-content {
  display: flex;
  justify-content: space-between;
  flex-direction: row;
  width: 100%;
  height: 45px;
}

.slot-panel {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
}

.slot-title {
  display: flex;
  font-size: 14px;
  color: #3b4144;
}

.slot-subtitle {
  display: flex;
  font-size: 12px;
  color: #999
}

.slot-desc {
  font-size: 12px;
  color: #999;
  max-width: 200px;
  max-height: 50px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;

}

:deep(.uni-section) {
  margin-top: 5px;
}
</style>