<template>
  <a-modal
    v-model:visible="visible"
    :title="`${editMember.teamId ? $t('sys.update') : $t('sys.add')}${$t(
      'material.name'
    )}`"
    width="480px"
    :after-close="onCancel"
    @ok="saveHandler"
  >
    <template #footer>
      <a-button class="action-bottom" size="middle" @click="visible = false">
        {{ $t('sys.cancel') }}
      </a-button>
      <a-button
        class="action-bottom"
        type="primary"
        size="middle"
        @click="saveHandler"
      >
        {{ $t('sys.save') }}
      </a-button>
    </template>

    <a-form
      ref="fromRef"
      :model="editMember"
      class="form"
      label-align="right"
      :label-col="{ span: 5 }"
    >
      <a-form-item
        name="userName"
        :label="$t('material.nickNameLabel')"
        :rules="[{ required: true, message: ui18n.t('material.ruleUserName') }]"
      >
        <a-input
          v-model:value="editMember.userName"
          :disabled="!!editMember.teamId"
          :placeholder="$t('material.ruleUserName')"
        />
      </a-form-item>
      <a-form-item
        name="remark"
        :label="$t('material.remarkLabel')"
        :rules="[{ required: true, message: $t('material.ruleRemark') }]"
      >
        <a-input
          v-model:value="editMember.remark"
          :placeholder="$t('material.ruleRemark')"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, defineProps, toRaw } from 'vue'

import type { Member, SetMemberProps } from '@/api'
import type { FormInstance } from 'ant-design-vue'
import { ui18n } from '@/lang'

export type EditMember = PartialPart<SetMemberProps, 'projectId'>

defineOptions({ name: 'edit-member' })

const props = defineProps<{
  member?: EditMember
  onSave: (data: EditMember) => void
  onCancel: () => void
}>()

const editMember = ref<EditMember>(
  props.member
    ? { ...props.member }
    : { userName: '', remark: '', bindAccount: '', roles: [], nickName: '' }
)
const fromRef = ref<FormInstance>()
const visible = ref(true)

const saveHandler = async () => {
  await fromRef.value?.validate()
  await props.onSave(toRaw(editMember.value))
  visible.value = false
}
</script>

<style lang="scss" scoped>
.footer {
  display: flex;
  justify-content: space-between;
  align-items: center;

  p {
    margin-bottom: 0;
    color: #646566;
    font-size: 14px;
  }
}
</style>
