<template>
  <a-modal
    v-model:visible="visible"
    :title="title"
    :mask-closable="false"
    :esc-to-close="false"
    :width="width >= 500 ? 500 : '100%'"
    draggable
    @before-ok="save"
    @close="reset"
  >
    <GiForm ref="formRef" v-model="form" :options="options" :columns="columns">
    </GiForm>
  </a-modal>
</template>

<script setup lang="ts">
import { Message } from '@arco-design/web-vue'
import { useWindowSize } from '@vueuse/core'
import type { Columns, GiForm, Options } from '@/components/GiForm'

import { useResetReactive } from '@/hooks'
import { teamPost } from '@/apis/team/jiangli'
import { userListUpdata } from '@/apis/user/userlist'
import type { UserListResp } from '@/apis/user/type'

const emit = defineEmits<{
  (e: 'save-success'): void
}>()

const { width } = useWindowSize()

const dataId = ref()
const visible = ref(false)
const isUpdate = computed(() => !!dataId.value)
const title = computed(() => (isUpdate.value ? '修改用户信息' : '新增用户信息'))
const formRef = ref<InstanceType<typeof GiForm>>()

const [form, resetForm] = useResetReactive({

})
const options: Options = {
  form: { size: 'large' },
  btns: { hide: true },
}
const columns: Columns = reactive([
  { label: '名', field: 'firstName', type: 'input' },
  { label: '姓', field: 'lastName', type: 'input' },
  { label: '钱包地址', field: 'walletAddress', type: 'input' },
  { label: '空投数量', field: 'airdropCoin', type: 'input' },
  { label: '金币余额', field: 'goldCoinAmount', type: 'input' },
  { label: '金币总数量', field: 'goldCoinTotalHis', type: 'input' },
  { label: '用户余额', field: 'userAmount', type: 'input' },
])

// 重置
const reset = () => {
  formRef.value?.formRef?.resetFields()
  resetForm()
}

// 保存
const save = async () => {
  try {
    const isInvalid = await formRef.value?.formRef?.validate()
    if (isInvalid) return false
    if (isUpdate.value) {
      await userListUpdata(dataId.value, form)
      Message.success('修改成功')
    } else {
      await teamPost({ ...form })
      Message.success('新增成功')
    }
    emit('save-success')
    return true
  } catch (error) {
    return false
  }
}

// 新增
const onAdd = () => {
  reset()
  dataId.value = null
  visible.value = true
}

// 修改
const onUpdate = async (record: UserListResp) => {
  reset()
  dataId.value = record.id
  Object.assign(form, record)
  visible.value = true
}

defineExpose({ onAdd, onUpdate })
</script>

<style scoped lang="scss"></style>
