<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <!--  -->
      <template #category_id="{ model, field }">
        <Select
          v-model:value="model[field]"
          :options="industryData"
          placeholder="请选择"
          @select="select"
          :fieldNames="{ label: 'name', value: 'id' }"
        ></Select>
      </template>
      <!--  -->
      <template #parent="{ model, field }">
        <TreeSelect
          v-model:value="model[field]"
          :tree-data="treeData"
          treeDefaultExpandAll
          placeholder="请选择"
          allowClear
          :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, jsonString } from '/@/utils/index'
  import { ref, computed, unref } from 'vue'
  import { BasicForm, useForm } from '/@/components/Form/index'
  import { accountFormSchema } from './base.data'
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer'
  import { TreeSelect, Space, FormItem, Input, Button, Select } from 'ant-design-vue'
  import {
    addcrops,
    editcrops,
    getcrops,
    agriculturalBasicInfo,
    getCropCate,
  } 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 industryData = ref<any>([])
  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(industryData).length === 0) {
      // 获取产业数据
      getIndustry()
      //获取上级数据
      getTree()
    }
    isUpdate.value = data?.isUpdate
    if (unref(isUpdate)) {
      const res = await agriculturalBasicInfo(data.id)
      //获取上级数据
      await getTree(res?.category?.id ?? null)
      const arr1 = jsonString(res.extends) ? JSON.parse(res.extends) : res.extends
      await setFieldsValue({
        ...res,
        is_end: res.is_end === 1 ? true : false,
        extends: arr1.length ? arr1 : [{ name: '', unit: '' }],
        category_id: res?.category?.id,
        parent_id: res.parent_id > 0 ? res.parent_id : undefined,
      })
    } else {
      setFieldsValue({
        extends: [{ name: '', unit: '' }],
      })
    }
  })

  // 获取产业数据
  const getIndustry = async () => {
    const res = await getCropCate()
    industryData.value = res
  }
  const select = (e) => {
    setFieldsValue({ parent_id: undefined })
    getTree(e)
  }
  // 获取上级数据
  const getTree = async (category = null) => {
    const res = await getcrops({ type: 'all', crop_type: 1, category })
    treeData.value = getTreeData(res.data, 0, 'parent_id', 'id', 'children', 'key', 0)
  }
  const handleSubmit = async () => {
    try {
      const values = await validate()
      values.crop_type = 1
      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>
