<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 { jiangliById, jiangliPost, jiangliUpdata } from '@/apis/user/userlist'

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: 'rewardsName', type: 'input', rules: [{ required: true, message: '请输入奖励名称' }] },
  { label: '奖励说明', field: 'rewardsDescribe', type: 'input', rules: [{ required: true, message: '请输入值奖励说明' }] },
  { label: '邀请好友数量', field: 'inviteNum', type: 'input', rules: [{ required: true, message: '请输入值奖励说明' }] },
  { label: '金币数量', field: 'goldCoinNum', type: 'input', rules: [{ required: true, message: '请输入金币数量' }] },
  {
    label: '排序',
    field: 'rewardsLevel',
    type: 'input-number',
    props: {
      min: 1,
      mode: 'button',
    },
  },
])

// 重置
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 jiangliUpdata(dataId.value, form)
      Message.success('修改成功')
    } else {
      await jiangliPost({ ...form })
      Message.success('新增成功')
    }
    emit('save-success')
    return true
  } catch (error) {
    return false
  }
}

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

// 修改
const onUpdate = async (id: number) => {
  reset()
  dataId.value = id
  const { data } = await jiangliById(id)
  Object.assign(form, data[0])
  visible.value = true
}

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

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