<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 { thrusterById, thrusterPost, thrusterUpdata } from '@/apis/production/thruster'

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: 'consumeGoldCoin', type: 'input', rules: [{ required: true, message: '请输入消耗金币数量' }] },
  { label: '消耗真实货币数量', field: 'realMoney', type: 'input', rules: [{ required: true, message: '请输入消耗真实货币数量' }] },
  { label: '每秒产量', field: 'numericalValue', type: 'input', rules: [{ required: true, message: '请输入每秒产量' }] },
  { label: '等级', field: 'level', type: 'input', rules: [{ required: true, message: '请输入等级' }] },
])

// 重置
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 thrusterUpdata(dataId.value, form)
      Message.success('修改成功')
    } else {
      await thrusterPost({ ...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 thrusterById(id)
  Object.assign(form, data[0])
  visible.value = true
}

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

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