<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #parent="{ model, field }">
        <TreeSelect
          v-model:value="model[field]"
          :tree-data="treeData"
          placeholder="请选择"
          :fieldNames="{ children: 'children', label: 'name', value: 'id' }"
        ></TreeSelect>
      </template>
      <!--  -->
      <template #extends="{ model, field }">
        <Space
          v-for="(sight, index) in model[field]"
          :key="index"
          style="display: flex; margin-bottom: 8px"
          align="baseline"
        >
          <FormItem
            label="名称"
            :name="['extends', index, 'name']"
            :rules="{
              required: true,
              message: '请输入名称',
              trigger: 'change',
            }"
            :label-col="{ span: 10 }"
          >
            <Input v-model:value="sight.name" placeholder="请输入" class="w-full"></Input>
          </FormItem>
          <FormItem
            label="单位"
            :name="['extends', index, 'unit']"
            :rules="{
              required: true,
              message: '请输入单位',
              trigger: 'change',
            }"
            :label-col="{ span: 10 }"
          >
            <Input v-model:value="sight.unit" placeholder="请输入" class="w-full"></Input>
          </FormItem>
          <MinusCircleOutlined
            @click="removeSight(sight, model[field])"
            v-if="model[field].length > 1"
            :disabled="model[field].length === 1"
          />
        </Space>
        <FormItem>
          <div class="flex items-center justify-center w-full px-80px">
            <Button type="dashed" block @click="addSight(model[field])">
              <PlusOutlined />
              添加
            </Button>
          </div>
        </FormItem>
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { getTreeData } from '/@/utils/index'
  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 { TreeSelect, Space, FormItem, Input, Button } from 'ant-design-vue'
  import { addcrops, editcrops, getcrops, agriculturalBasicInfo } from '/@/api/sys/user'
  import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons-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: 100,
    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.data, 0, 'parent_id', 'id', 'children', 'key')
    }
    isUpdate.value = data?.isUpdate
    if (unref(isUpdate)) {
      const res = await agriculturalBasicInfo(data.id)
      await setFieldsValue({
        ...res,
        is_end: res.is_end === 1 ? true : false,
        extends: res.extends.length ? res.extends : [{ name: '', unit: '' }],
        category_id: res?.category?.id,
        parent_id: res.parent_id > 0 ? res.parent_id : undefined,
      })
    } else {
      setFieldsValue({
        extends: [{ name: '', unit: '' }],
      })
    }
  })
  const handleSubmit = async () => {
    try {
      const values = await validate()
      values.crop_type = 2
      values.is_end = values.is_end ? true : false
      if (values.id) {
        // 修改
        await editcrops(values.id, values)
      } else {
        // 新增
        await addcrops(values)
      }
      closeDrawer()
      emits('success')
    } finally {
      setDrawerProps({ confirmLoading: false })
    }
  }
  //添加
  const addSight = (e: any) => {
    e.push({
      name: '',
      unit: '',
    })
  }
  // 删除
  const removeSight = (item: any, e: any) => {
    let index = e.indexOf(item)
    if (index !== -1) {
      e.splice(index, 1)
    }
  }
</script>
