<script setup lang="tsx">
import { reactive, ref, unref } from 'vue'
import { useTable } from '@/hooks/web/useTable'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import { ContentWrap } from '@/components/ContentWrap'
import { BaseButton } from '@/components/Button'
import { ElDivider, ElMessage, ElMessageBox,ElTag } from 'element-plus'
import Write from './components/Write.vue'
import { delProductUnit,getUnitList } from '@/api/goods'
import { FormSchema } from '@/components/Form'
import { Search } from '@/components/Search'

const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const res = await getUnitList({
      ...searchParams.value,
      page: unref(currentPage) || 1,
      limit: unref(pageSize) || 10,
    })
    return {
      list: res.data.list,
      total: res.data.count || 0
    }
  }
})

const { dataList, loading, total, currentPage, pageSize } = tableState
const { getList } = tableMethods

const tableColumns = reactive<TableColumn[]>([
  {
    field: 'id',
    label: 'ID',
    width: 100
  },
  {
    field: 'name',
    label: '单位名称',
    minWidth: 100
  },
  {
    field: 'is_weigh',
    label: '是否称重',
    width: 200,
    align: 'center',
    slots: {
      default: (data: any) => {
        const row = data.row
        if (row.is_weigh == 1) {
          return (
            <>
          <ElTag >是</ElTag></>
          )
        } else {
          return (
          <>
            <ElTag type="info">否</ElTag></>
        )
        }
        
      }
    }
  },
  {
    field: 'is_show',
    label: '是否显示',
    width: 200,
    align: 'center',
    slots: {
      default: (data: any) => {
        const row = data.row
        if (row.is_show == 1) {
          return (
            <>
          <ElTag >是</ElTag></>
          )
        } else {
          return (
          <>
            <ElTag type="info">否</ElTag></>
        )
        }
      }
    }
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    width: 200,
    fixed: 'right',
    align: 'center',
    headerAlign: 'center',
    slots: {
      default: (data: any) => {
        const row = data.row
        return (
          <>
            <BaseButton link size="small" type="primary" onClick={() => action('edit', row)}>
              编辑
            </BaseButton>
            <ElDivider direction="vertical" />
            <BaseButton link size="small" type="danger" onClick={() => delAction(row)}>
              删除
            </BaseButton>
          </>
        )
      }
    }
  }
])

const dialogVisible = ref(false)
const currentRow = ref(0)
const dialogTitle = ref('')
const actionType = ref('')

const action = async (type: string, row?: any) => {
  actionType.value = type

  if (type == 'add') {
    dialogTitle.value = t('exampleDemo.add')
    currentRow.value = 0
  }
  if (type == 'edit') {
    dialogTitle.value = t('exampleDemo.edit')
    currentRow.value = row.id
  }
  
  dialogVisible.value = true
}
const delAction = (row: any) => {
  ElMessageBox.confirm('删除后无法恢复，是否删除?', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const re = await delProductUnit(row.id)
      if (re) {
        ElMessage({
          showClose: true,
          message: '删除成功',
          type: 'success'
        })
      }
      await getList()
    })
    .catch(() => {})
}
const save = async () => {
  getList()
  dialogVisible.value = false
}
const searchSchema = reactive<FormSchema[]>([
  {
    field: 'name',
    label: '单位名称',
    component: 'Input',
    componentProps: {
      placeholder: '请输入单位名称'
    }
  },
  {
    field: 'type',
    label: '类型',
    value: 'unit',
    hidden: true,
    componentProps: {
      placeholder: ''
    }
  },
  {
    field: 'pid',
    label: '类型',
    value: 0,
    hidden: true,
    componentProps: {
      placeholder: ''
    }
  },
  {
    field: 'is_show',
    label: '是否显示',
    component: 'Select',
    value: -1,
    componentProps: {
      placeholder: '全部',
      options: [
        {
          label: '全部',
          value: -1
        },
        {
          label: '显示',
          value: 1
        },
        {
          label: '隐藏',
          value: 0
        }
      ]
    }
  },
  {
    field: 'is_weigh',
    label: '是否称重',
    component: 'Select',
    value: -1,
    componentProps: {
      placeholder: '全部',
      options: [
        {
          label: '全部',
          value: -1
        },
        {
          label: '是',
          value: 1
        },
        {
          label: '否',
          value: 0
        }
      ]
    }
  }
])
const searchParams = ref<{ type: string,name: string,pid:number }>({ type: 'unit',name: '',pid: 0 })

const setSearchParams = (data: any) => {
  searchParams.value = data
  getList()
}
</script>

<template>
  <ContentWrap>
    <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" />

    <div class="mb-10px">
      <BaseButton type="primary" @click="action('add')">{{ t('exampleDemo.add') }}</BaseButton>
    </div>
    <Table
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :columns="tableColumns"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      stripe
      :data="dataList"
      :loading="loading"
      @register="tableRegister"
      :pagination="{
        total
      }"
    />
  </ContentWrap>

  <Write
    v-model="dialogVisible"
    :title="dialogTitle"
    ref="writeRef"
    :id="currentRow"
    @submit="save"
  />
</template>
