<script setup lang="ts">
import { fetchUserInfoUpdate } from '@/apis/user'
import ImageCropper from '@/components/image-cropper/image-cropper.vue'
import { useSystemLanguageStore } from '@/store/modules/system-language'
import { useUserStore } from '@/store/modules/user'
import type { InputInst } from 'naive-ui'
import { computed, nextTick, reactive, ref, useTemplateRef } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import PasswordChangeModal from './components/password-change-modal.vue'
import MailboxBindingModal from './components/mailbox-binding-modal.vue'
import { fetchUpload } from '@/apis/upload'

const userStore = useUserStore()
const systemLanguageStore = useSystemLanguageStore()
const router = useRouter()
const { t } = useI18n()

const inputRefs = useTemplateRef<InputInst | InputInst[]>('inputRefs')
const avatarInputRef = useTemplateRef('avatarInputRef')
const imageCropperRef = useTemplateRef<InstanceType<typeof ImageCropper> | null>('imageCropperRef')

const userInfoForm = ref({
  nickName: '',
  remark: userStore.userInfo.remark,
})

const userInfoFormItemEdit = reactive({
  nickName: false,
  remark: false,
})

const isShowPasswordChangeModal = ref(false)
const isShowMailboxBindingModal = ref(false)

const listItemLabelWidth = ref(systemLanguageStore.currentLanguageInfo.key === 'en' ? '168px' : '100px')
// const confirmBtnLoading = ref(true)
const saveBtnLoading = ref(false)

const currentLanguage = computed({
  get() {
    return systemLanguageStore.currentLanguageInfo.key
  },
  set(value: I18n.LangType) {
    systemLanguageStore.updateCurrentLanguageInfo(value)

    router.go(0)
  },
})

const userInfo = computed(() => userStore.userInfo)

const languageOptions = computed(() => {
  return systemLanguageStore.languageOptions.map((item) => ({ value: item.key, label: item.label }))
})

function userInfoUpdate(userInfo: {
  nickName?: string
  avatarUrl?: string
  mobilePhone?: string
  email?: string
  remark?: string
}) {
  return fetchUserInfoUpdate(userInfo).then(() => {
    userStore.fetchUpdateUserInfo()
  })
}

function handleAvatarUpdate() {
  avatarInputRef.value && avatarInputRef.value.click()
}

function handleAvatarUpload(e: Event) {
  const target = e.target as HTMLInputElement
  const file = target.files && target.files[0]

  if (imageCropperRef.value && file) {
    imageCropperRef.value.cropImage(URL.createObjectURL(file)).then((file) => {
      const formData = new FormData()
      formData.append('file', file)

      const loadingCtl = window.$message.loading(t('common_module.uploading'), { duration: 0 })

      fetchUpload<string>(formData)
        .then((res) => {
          userInfoUpdate({
            avatarUrl: res.data,
          })
            .then(() => {
              window.$message.success(t('common_module.save_success_message'))

              userStore.fetchUpdateUserInfo()
            })
            .catch(() => {
              window.$message.loading(t('common_module.save_fail_message'))
            })
            .finally(() => {
              loadingCtl.destroy()
            })
        })
        .catch(() => {
          window.$message.loading(t('common_module.save_fail_message'))
        })
    })
  }
}

function handleUserInfoFormItemEditUpdate(key: keyof typeof userInfoFormItemEdit, isSave = false) {
  !isSave && (userInfoForm.value[key] = userInfo.value[key])

  userInfoFormItemEdit[key] = !userInfoFormItemEdit[key]

  if (userInfoFormItemEdit[key]) {
    nextTick(() => {
      if (inputRefs.value && !Array.isArray(inputRefs.value)) {
        inputRefs.value.focus()
      }
    })
  }

  if (isSave) {
    userInfoUpdate({
      [key]: userInfoForm.value[key],
    }).then(() => {
      window.$message.success(t('common_module.successful_update'))
    })
  }
}
</script>

<template>
  <div class="h-full min-h-fit flex-col rounded-[20px] bg-white p-6 shadow-[0_2px_2px_#0000000a]">
    <ImageCropper ref="imageCropperRef" />

    <div class="ml-[56px] pt-[6px]">
      <ul>
        <li class="font-600 flex items-center text-[18px]">
          <i class="iconfont icon-personal-info text-theme-color"></i>
          <span class="ml-[4px]">{{ t('personal_settings_module.basic_information_setting') }}</span>
        </li>

        <li class="mb-[30px] mt-[24px] flex items-center">
          <h4 class="font-600 list-item-label mr-[19px] text-[14px]">{{ t('common_module.avatar') }}：</h4>

          <div
            class="group relative h-[60px] w-[60px] cursor-pointer overflow-hidden rounded-full bg-[#EAECEC]"
            @click="handleAvatarUpdate"
          >
            <img class="h-full w-full object-cover" :src="userInfo.avatarUrl" alt="Avatar" />

            <div
              class="flex-center absolute bottom-0 h-[26px] w-full bg-[rgba(0,0,0,0.4)] text-[10px] text-white opacity-0 transition group-hover:opacity-100"
            >
              <span>{{ t('common_module.change') }}</span>
            </div>

            <input ref="avatarInputRef" type="file" class="hidden" accept="image/*" @change="handleAvatarUpload" />
          </div>
        </li>

        <li class="mb-[30px] mt-[24px] flex items-center">
          <h4 class="font-600 list-item-label mr-[19px] text-[14px]">
            {{ t('personal_settings_module.account_nickname') }}：
          </h4>

          <div v-if="userInfoFormItemEdit.nickName" class="flex">
            <div class="flex w-[220px] items-center">
              <n-input
                ref="inputRefs"
                v-model:value="userInfoForm.nickName"
                :placeholder="t('personal_settings_module.please_enter_the_account_nickname')"
                type="text"
                size="small"
              />
            </div>

            <div class="ml-[20px] flex items-center">
              <n-button class="!mr-[6px]" size="tiny" @click="handleUserInfoFormItemEditUpdate('nickName')">
                <i class="iconfont icon-close"></i>
              </n-button>
              <n-button
                type="primary"
                size="tiny"
                :loading="saveBtnLoading"
                @click="handleUserInfoFormItemEditUpdate('nickName', true)"
              >
                <i class="iconfont icon-queren"></i>
              </n-button>
            </div>
          </div>

          <div v-else class="flex items-center text-[14px] text-[#999]">
            <span class="mr-[5px]">{{ userInfo.nickName || '-' }}</span>

            <i
              class="iconfont icon-edit1 cursor-pointer px-[5px]"
              @click="handleUserInfoFormItemEditUpdate('nickName')"
            ></i>
          </div>
        </li>

        <li class="mb-[30px] mt-[24px] flex items-center">
          <h4 class="font-600 list-item-label mr-[19px] text-[14px]">
            {{ t('personal_settings_module.personal_profile') }}：
          </h4>

          <div v-if="userInfoFormItemEdit.remark" class="flex">
            <div class="flex w-[220px] items-center">
              <n-input
                ref="inputRefs"
                v-model:value="userInfoForm.remark"
                type="textarea"
                size="small"
                :placeholder="t('personal_settings_module.please_enter_a_personal_profile')"
                :autosize="{ minRows: 4, maxRows: 4 }"
              />
            </div>

            <div class="ml-[20px] flex items-center">
              <n-button class="!mr-[6px]" size="tiny" @click="handleUserInfoFormItemEditUpdate('remark')">
                <i class="iconfont icon-close"></i>
              </n-button>
              <n-button
                type="primary"
                size="tiny"
                :loading="saveBtnLoading"
                @click="handleUserInfoFormItemEditUpdate('remark', true)"
              >
                <i class="iconfont icon-queren"></i>
              </n-button>
            </div>
          </div>

          <div v-else class="flex items-center text-[14px] text-[#999]">
            <span class="mr-[5px]">{{ userInfo.remark || '-' }}</span>

            <i
              class="iconfont icon-edit1 cursor-pointer px-[5px]"
              @click="handleUserInfoFormItemEditUpdate('remark')"
            ></i>
          </div>
        </li>

        <li class="mb-[30px] mt-[24px] flex items-center">
          <h4 class="font-600 list-item-label mr-[19px] text-[14px]">{{ t('common_module.mobile_phone_number') }}：</h4>

          <div class="text-[14px] text-[#999]">{{ userInfo.mobilePhone || '-' }}</div>
        </li>

        <li class="mb-[30px] mt-[24px] flex items-center">
          <h4 class="font-600 list-item-label mr-[19px] text-[14px]">{{ t('common_module.email') }}：</h4>

          <div class="text-[14px] text-[#999]">
            <span v-if="userInfo.email">{{ userInfo.email }}</span>
            <span v-else class="text-theme-color cursor-pointer select-none" @click="isShowMailboxBindingModal = true">
              {{ t('personal_settings_module.click_bind_email') }}
            </span>
          </div>
        </li>

        <li class="mb-[30px] mt-[24px] flex items-center">
          <h4 class="font-600 list-item-label mr-[19px] text-[14px]">{{ t('common_module.password') }}：</h4>

          <div
            class="text-theme-color cursor-pointer select-none text-[14px]"
            @click="isShowPasswordChangeModal = true"
          >
            {{ t('personal_settings_module.click_to_set_password') }}
          </div>
        </li>
      </ul>

      <ul class="mt-[60px]">
        <li class="font-600 flex items-center text-[18px]">
          <i class="iconfont icon-language text-theme-color"></i>
          <span class="ml-[4px]">{{ t('personal_settings_module.language_setting') }}</span>
        </li>

        <li class="mb-[8px] ml-[121px] mt-[8px]">
          <h5 class="text-[12px] text-[#999]">{{ t('personal_settings_module.language_setting_doc') }}</h5>
        </li>

        <li class="mb-[30px] flex items-center">
          <h4 class="font-600 list-item-label mr-[19px] text-[14px]">{{ t('common_module.language') }}：</h4>

          <div class="w-[200px]">
            <n-select v-model:value="currentLanguage" :options="languageOptions" />
          </div>
        </li>
      </ul>
    </div>

    <PasswordChangeModal v-model:is-show-password-change-modal="isShowPasswordChangeModal" />
    <MailboxBindingModal v-model:is-show-mailbox-binding-modal="isShowMailboxBindingModal" />
  </div>
</template>

<style lang="scss" scoped>
.list-item-label {
  width: v-bind('listItemLabelWidth');
  text-align: end;
}
</style>
