<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #crop="{ model, field }">
        <TreeSelect
          v-model:value="model[field]"
          :tree-data="treeData"
          placeholder="请选择"
          :fieldNames="{ children: 'children', label: 'name', value: 'id' }"
        ></TreeSelect>
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { getTreeData } from '/@/utils/index'
  import dayjs from 'dayjs'
  import { ref, computed, unref } from 'vue'
  import { BasicForm, useForm } from '/@/components/Form/index'
  import { accountFormSchema } from './town.data'
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer'
  import { addCropYields, editCropYields, getcrops } from '/@/api/sys/user'
  import { TreeSelect } from 'ant-design-vue'
  const emits = defineEmits(['success', 'register'])
  const isUpdate = ref(false)
  const treeData = ref([])
  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 })
    if (unref(treeData).length === 0) {
      const res = await getcrops({ type: 'all', crop_type: 2 })
      treeData.value = getTreeData(res.items, 0, 'parent_id', 'id', 'children', 'key')
    }
    isUpdate.value = data?.isUpdate
    if (unref(isUpdate)) {
      await setFieldsValue({
        id: data.id,
        quarter: data.quarter.toString(),
        time_year: dayjs(data.time_year.toString()),
        base_id: data.base_id,
        yield: data.yield,
        output: data.output,
        crop_id: data.crop_id,
        cultivated: data.cultivated,
      })
    }
  })

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