<script setup lang="tsx">
import { reactive, ref, unref, useTemplateRef } 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 { Dialog } from '@/components/Dialog'
import { BaseButton } from '@/components/Button'
import { ElDivider, ElMessage, ElMessageBox } from 'element-plus'
import Write from './components/Write.vue'
import { categoryData } from '@/api/goods/types'
import { TableImage } from '@/components/tableImage'
import {
  getProductCategory,
  putProductCategory,
  delProductCategory,
  addProductCategory
} from '@/api/goods'
const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const res = await getProductCategory({
      pid: -1,
      page: unref(currentPage) || 1,
      limit: unref(pageSize) || 10
    })
    return {
      list: res.data,
      total: res.data.length || 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: 'pic',
    label: '分类图标',
    minWidth: 140,
    slots: {
      default: (data: any) => {
        const row = data.row
        return <TableImage src={row.pic} />
      }
    }
  },
  {
    field: 'sort',
    align: 'center',
    headerAlign: 'center',
    label: '排序',
    width: 100
  },
  {
    field: 'is_show',
    label: '状态',
    width: 120,
    slots: {
      default: (data: any) => {
        const row = data.row
        return <>{row.is_show == 1 ? '启用' : '禁用'}</>
      }
    }
  },
  {
    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()
const dialogTitle = ref('')
const actionType = ref('')
const saveLoading = ref(false)
const writeRef = useTemplateRef('writeRef')

const action = async (type: string, row?: any) => {
  actionType.value = type
  if (type == 'add') {
    dialogTitle.value = t('exampleDemo.add')
    currentRow.value = undefined
  }
  if (type == 'edit') {
    dialogTitle.value = t('exampleDemo.edit')
    currentRow.value = {
      pid: row.pid,
      id: row.id,
      name: row.name,
      is_show: row.is_show == 1 ? true : false,
      image: row.image ? [row.image] : [], //一口价
      sort: row.sort
    }
  }
  dialogVisible.value = true
}
const delAction = (row: any) => {
  ElMessageBox.confirm('删除后无法恢复，是否删除?', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const re = await delProductCategory(row.id)
      if (re) {
        ElMessage({
          showClose: true,
          message: '删除成功',
          type: 'success'
        })
      }
      await getList()
    })
    .catch(() => {})
}
const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    const data: categoryData = {
      id: formData.id || '',
      name: formData.name, //分类名称
      pid: formData.pid, //类型
      is_show: formData.is_show ? 1 : 0, //是否启用
      image: formData.image[0] || '', //一口价
      sort: formData.sort
    }
    try {
      let re: any = {}
      if (actionType.value === 'edit') {
        re = await putProductCategory(data)
      } else if (actionType.value === 'add') {
        re = await addProductCategory(data)
      }
      if (re.status == 200) {
        ElMessage({
          showClose: true,
          message: '添加成功',
          type: 'success'
        })
        getList()
        dialogVisible.value = false
      }
    } catch (error) {
      console.log(error)
    } finally {
      saveLoading.value = false
    }
  }
}
const load = async (row: any, _: unknown, resolve: any) => {
  const res = await getProductCategory({
    pid: row.id,
    page: 1,
    limit: 100
  })
  resolve(res.data)
  console.log(res)
}
</script>

<template>
  <ContentWrap>
    <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"
      default-expand-all
      row-key="id"
      lazy
      :load="load"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      stripe
      :data="dataList"
      :loading="loading"
      @register="tableRegister"
      :pagination="{
        total
      }"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
    <Write ref="writeRef" :current-row="currentRow" />
    <template #footer>
      <BaseButton type="primary" :loading="saveLoading" @click="save">
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
