<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm"> </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import dayjs from 'dayjs'
  import { ref, computed, unref } from 'vue'
  import { BasicForm, useForm } from '/@/components/Form/index'
  import { accountFormSchema } from './shrimp-flows'
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer'
  import { addShrimpFlows, editShrimpFlows } from '/@/api/sys/user'
  const emits = defineEmits(['success', 'register'])
  const isUpdate = ref(false)
  const getTitle = computed(() => (!isUpdate.value ? '新增流向' : '编辑流向'))
  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    baseColProps: { span: 24 },
    schemas: accountFormSchema,
    showActionButtonGroup: false,
  })
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    resetFields()
    setDrawerProps({ confirmLoading: false })
    isUpdate.value = data?.isUpdate
    if (unref(isUpdate)) {
      await setFieldsValue({
        id: data.id,
        quarter: data.quarter.toString(),
        year: dayjs(data.year.toString()),
        area: data.area,
        sales: data.sales,
        unit: data.unit,
      })
    } else {
      setFieldsValue({
        unit: '吨',
      })
    }
  })

  const handleSubmit = async () => {
    try {
      const values = await validate()
      values.year = dayjs(values.year.toString()).format('YYYY')
      setDrawerProps({ confirmLoading: true })
      if (values.id) {
        // 修改
        await editShrimpFlows(values.id, values)
      } else {
        // 新增
        await addShrimpFlows(values)
      }
      closeDrawer()
      emits('success')
    } finally {
      setDrawerProps({ confirmLoading: false })
    }
  }
</script>
<style lang="less" scoped>
  :deep(.ant-picker) {
    width: 100%;
  }
</style>
