<template>
  <div class="pt-20px">
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary" @click="handleCreate"> 新增农作物 </a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <div class="flex items-center justify-center">
            <TableAction
              :actions="[
                { label: '编辑', onClick: handleEdit.bind(null, record) },
                {
                  label: '删除',
                  popConfirm: {
                    title: '是否确认删除',
                    placement: 'topRight',
                    confirm: handleDelete.bind(null, record),
                  },
                },
              ]"
            />
          </div>
        </template>
        <template v-if="column.key === 'crops'">
          <Button
            class="mx-2px"
            v-for="(item, index) in record['crops']"
            :key="index"
            type="link"
            >{{ item.name }}</Button
          >
        </template>
      </template>
    </BasicTable>
    <TownDrawer @register="registerDrawer" @success="handleSuccess" />
  </div>
</template>
<script lang="ts" setup>
  import { BasicTable, useTable, TableAction } from '/@/components/Table'
  import { deleteCrops, getcrops } from '/@/api/sys/user'
  import { message } from 'ant-design-vue'
  import { useDrawer } from '/@/components/Drawer'
  import TownDrawer from './TownDrawer.vue'
  import { Button } from 'ant-design-vue'
  import { columns, searchFormSchema } from './town.data'
  const [registerDrawer, { openDrawer }] = useDrawer()
  const [registerTable, { reload }] = useTable({
    title: '城镇农作物列表',
    api: async (e) => {
      const res = await getcrops({ type: 'all', ...e, crop_type: 2 })
      return res
    },
    rowKey: 'id',
    columns,
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
    },
    useSearchForm: false,
    showTableSetting: true,
    bordered: true,
    showIndexColumn: true,
  })

  const handleSuccess = () => {
    message.success('操作成功')
    reload()
  }
  const handleCreate = () => {
    openDrawer(true, {
      isUpdate: false,
    })
  }
  const handleEdit = (record: Recordable) => {
    openDrawer(true, {
      ...record,
      isUpdate: true,
    })
  }
  const handleDelete = async (record: Recordable) => {
    await deleteCrops(record.id)
    message.success('删除成功')
    reload()
  }
</script>
