<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
  >
    <!-- <BasicForm @register="registerForm"> </BasicForm> -->
    <Form class="w-full" :label-col="{ span: 4 }" ref="formRef" :model="modelRef">
      <FormItem
        label="产业"
        name="category_id"
        :rules="{
          required: true,
          message: '请选择产业',
          trigger: 'change',
        }"
      >
        <Select
          v-model:value="modelRef.category_id"
          placeholder="请选择产业"
          class="w-full"
          :options="categoryDate"
          :fieldNames="{ label: 'name', value: 'id' }"
        ></Select>
      </FormItem>
      <FormItem
        label="名称"
        name="name"
        :rules="{
          required: true,
          message: '请输入名称',
          trigger: 'change',
        }"
      >
        <Input v-model:value="modelRef.name" placeholder="请输入" class="w-full"></Input>
      </FormItem>
      <FormItem label="上级">
        <Select
          :options="parentDate"
          :fieldNames="{ label: 'name', value: 'id' }"
          v-model:value="modelRef.parent_id"
          placeholder="请选择"
          class="w-full"
        ></Select>
      </FormItem>
      <FormItem
        label="单位"
        name="unit"
        :rules="{
          required: true,
          message: '请输入单位',
          trigger: 'change',
        }"
      >
        <Input v-model:value="modelRef.unit" placeholder="请输入" class="w-full"></Input>
      </FormItem>
      <FormItem
        label="排序"
        name="sort"
        :rules="{
          required: true,
          message: '请输入排序',
          trigger: 'change',
        }"
      >
        <Input v-model:value="modelRef.sort" placeholder="请输入" class="w-full"></Input>
      </FormItem>
      <FormItem label="是否是结点" name="is_end">
        <Switch v-model:checked="modelRef.is_end" placeholder="请选择"></Switch>
      </FormItem>
      <!--  -->
      <template v-if="modelRef.is_end">
        <Space
          v-for="(sight, index) in modelRef.extends"
          :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: 8 }"
          >
            <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: 8 }"
          >
            <Input v-model:value="sight.unit" placeholder="请输入" class="w-full"></Input>
          </FormItem>
          <MinusCircleOutlined
            @click="removeSight(sight)"
            v-if="modelRef.extends.length > 1"
            :disabled="modelRef.extends.length === 1"
          />
        </Space>
        <FormItem>
          <div class="flex items-center justify-center w-full px-80px">
            <Button type="dashed" block @click="addSight">
              <PlusOutlined />
              添加
            </Button>
          </div>
        </FormItem>
      </template>
    </Form>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue'
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer'
  import { Form, Select, FormItem, Input, Switch, Button, Space } from 'ant-design-vue'
  import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons-vue'
  import { getCropCate, addcrops, getcrops, editcrops } from '/@/api/sys/user'
  import type { FormInstance } from 'ant-design-vue'
  const formRef = ref<FormInstance>()
  const categoryDate = ref([])
  const parentDate = ref([])
  const modelRef = ref({
    id: null,
    category_id: undefined, //产业ID
    name: '', //名称
    parent_id: undefined, //上级
    unit: '', //单位
    is_end: false, //是否是结点
    extends: [{ name: '', unit: '' }],
    sort: '', //排序
  })

  const addSight = () => {
    modelRef?.value.extends.push({
      name: '',
      unit: '',
    })
  }
  const removeSight = (item: any) => {
    let index = modelRef.value.extends.indexOf(item)
    if (index !== -1) {
      modelRef.value.extends.splice(index, 1)
    }
  }
  const emits = defineEmits(['success', 'register'])
  const isUpdate = ref(false)
  const getTitle = computed(() => (!isUpdate.value ? '新增农作物' : '编辑农作物'))
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    formRef.value?.resetFields()
    // 获取产业
    const res = await getCropCate()
    categoryDate.value = res
    //获取上级数据
    const resDate = await getcrops({ page: 1, per_page: 99999, crop_type: 1, type: 'all' })
    parentDate.value = resDate.filter((e) => !e.is_end)
    setDrawerProps({ confirmLoading: false })
    isUpdate.value = data?.isUpdate
    if (unref(isUpdate)) {
      modelRef.value = {
        category_id: data.category_id,
        name: data.name,
        parent_id: data.parent_id == 0 ? undefined : data.parent_id,
        unit: data.unit,
        is_end: data.is_end == 1 ? true : false,
        extends: data.extends.length ? JSON.parse(data.extends) : [],
        sort: data.sort,
        id: data.id,
      }
    } else {
      modelRef.value = {
        id: null,
        category_id: undefined, //产业ID
        name: '', //名称
        parent_id: undefined, //上级
        unit: '', //单位
        is_end: false, //是否是结点
        extends: [{ name: '', unit: '' }],
        sort: '', //排序
      }
    }
  })

  const handleSubmit = async () => {
    try {
      const values = await formRef.value?.validate()
      const params = {
        crop_type: 1,
        ...values,
      }
      setDrawerProps({ confirmLoading: true })
      if (modelRef.value.id) {
        // 修改
        await editcrops(modelRef.value.id, params)
      } else {
        // 新增
        await addcrops(params)
      }
      closeDrawer()
      emits('success')
    } finally {
      setDrawerProps({ confirmLoading: false })
    }
  }
</script>
