<template>
  <CommonDialog v-model:show="show" title="修改昵称" :showDivider="false">
    <FlexCol gap="gap.lg" padding="padding.md" width="600rpx">
      <Text textAlign="center" text="修改您在本村的昵称，可以方便大家认识您" fontConfig="contentSpeicalText" />
      <Height :height="10" />
      <Field v-model="name" placeholder="请输入昵称" type="text" showWordLimit :maxLength="30" />
      <Height :height="20" />
      <FlexRow justify="space-around" gap="gap.md">
        <FrameButton text="返回" @click="show = false" width="220rpx" />
        <FrameButton primary text="提交" @click="addSubmit" :loading="submiting" width="220rpx" />
      </FlexRow>
    </FlexCol>
  </CommonDialog>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { toast } from '@/components/dialog/CommonRoot';
import { showError } from '@/common/composeabe/ErrorDisplay';
import { useVillageStore } from '@/store/village';
import CommonDialog from '@/common/components/CommonDialog.vue';
import FrameButton from '@/common/components/FrameButton.vue';
import Text from '@/components/basic/Text.vue';
import FlexCol from '@/components/layout/FlexCol.vue';
import FlexRow from '@/components/layout/FlexRow.vue';
import Height from '@/components/layout/space/Height.vue';
import Field from '@/components/form/Field.vue';
import LightVillageApi from '@/api/light/LightVillageApi';

const show = ref(false);
const props = defineProps<{
  villageId: number;
  currentNick?: string;
}>();
const emit = defineEmits(['finish']);
const villageStore = useVillageStore();

const submiting = ref(false);
const name = ref('');

async function addSubmit() {
  try {
    submiting.value = true;
    await LightVillageApi.nicknameSave({
      villageId: props.villageId,
      villageNickname: name.value,
    });
    toast({ content: '提交成功' });
    show.value = false;
    villageStore.loadMyJoinedVillages();
    setTimeout(() => {
      villageStore.reloadVillageInfo();
    }, 500);
  } catch (e) {
    showError(e);
  } finally {
    submiting.value = false;
  }
}

defineExpose({
  show: () => {
    show.value = true;
    name.value = props.currentNick || '';
  },
});
</script>