<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">
      <template #taskIcon>
        <a-upload :show-file-list="false" :custom-request="handleUpload">
          <template #upload-button>
            <a-button type="primary" shape="round">
              <template #icon>
                <icon-upload />
              </template>
              <template #default>上传</template>
            </a-button>
          </template>
        </a-upload>
      </template>
    </GiForm>
  </a-modal>
</template>

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

import { useResetReactive } from '@/hooks'
import { taskById, taskPost, taskUpdata } from '@/apis/task/taskhome'
import { TaskDisStatusList, TaskStatusList } from '@/constant/common'
import { uploadFile } from '@/apis'

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: 'name', type: 'input', rules: [{ required: true, message: '请输入任务名称' }] },
  { label: '名称日文', field: 'nameJa', type: 'input', rules: [{ required: true, message: '请输入名称日文' }] },
  { label: '名称韩文', field: 'nameKo', type: 'input', rules: [{ required: true, message: '请输入名称韩文' }] },
  { label: '名称泰语', field: 'nameTh', type: 'input', rules: [{ required: true, message: '请输入名称泰语' }] },
  { label: '名称越南语', field: 'nameVi', type: 'input', rules: [{ required: true, message: '请输入名称越南语' }] },
  { label: '名称俄语', field: 'nameRu', type: 'input', rules: [{ required: true, message: '请输入名称俄语' }] },
  { label: '名称英文', field: 'nameEn', type: 'input', rules: [{ required: true, message: '请输入名称英文' }] },
  { label: '名称葡萄牙语', field: 'namePt', type: 'input', rules: [{ required: true, message: '请输入名称葡萄牙语' }] },
  { label: '名称波斯语', field: 'nameFa', type: 'input', rules: [{ required: true, message: '请输入名称波斯语' }] },
  { label: '名称西班牙语', field: 'nameEs', type: 'input', rules: [{ required: true, message: '请输入名称西班牙语' }] },
  { label: '任务图标', field: 'taskIcon', type: 'upload', props: {
    multiple: false,
    limit: 1,
  }, rules: [{ required: true, message: '请上传任务图标' }] },
  { label: '任务链接', field: 'taskLink', type: 'input', rules: [{ required: true, message: '请输入任务链接' }] },
  {
    label: '任务分类',
    field: 'categoryCode',
    type: 'select',
    options: TaskStatusList,
    props: {
      multiple: false,
      allowClear: true,
      allowSearch: { retainInputValue: true },
      placeholder: '请选择任务分类',
    },
    rules: [{ required: true, message: '请选择任务分类' }],
  },
  {
    label: '状态',
    field: 'status',
    type: 'select',
    options: TaskDisStatusList,
    props: {
      multiple: false,
      allowClear: true,
      allowSearch: { retainInputValue: true },
      placeholder: '请选择状态',
    },
    rules: [{ required: true, message: '请选择状态' }],
  },
  { label: '金币数量', field: 'goldCoin', type: 'input', rules: [{ required: true, message: '请输入金币数量' }] },
  {
    label: '排序',
    field: 'sortNum',
    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 taskUpdata(dataId.value, form)
      Message.success('修改成功')
    } else {
      await taskPost({ ...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 taskById(id)
  Object.assign(form, data[0])
  visible.value = true
}
const handleUpload = (options: RequestOption) => {
  const controller = new AbortController()
  ;(async function requestWrap() {
    const { onProgress, onError, onSuccess, fileItem, name = 'file' } = options
    onProgress(20)
    const formData = new FormData()
    formData.append(name as string, fileItem.file as Blob)
    try {
      const res = await uploadFile(formData)
      form.taskIcon = res.data.url
      Message.success('上传成功')
      onSuccess(res)
    } catch (error) {
      onError(error)
    }
  })()
  return {
    abort() {
      controller.abort()
    },
  }
}
defineExpose({ onAdd, onUpdate })
</script>

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