<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 } from 'element-plus'
import Write from './components/Write.vue'
import { delProductRule, getProductRule } 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 getProductRule({
      ...searchParams.value,
      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: 'rule_name',
    label: '规格模版名称',
    minWidth: 100
  },
  {
    field: 'rule_value',
    label: '规格参数',
    minWidth: 140,
    slots: {
      default: (data: any) => {
        const row = data.row
        return (
          <>
            <div>
              {row.rule_value.map((item: any) => {
                return (
                  <>
                    <div>
                      {item.value}：
                      {item.detail.map((its: any, ind: number) => {
                        return (
                          <>
                            <span>{its}</span>
                            {ind != item.detail.length - 1 ? '、' : ''}
                          </>
                        )
                      })}
                    </div>
                  </>
                )
              })}
            </div>
          </>
        )
      }
    }
  },
  {
    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 delProductRule(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: 'rule_name',
    label: '规格名称',
    component: 'Input',
    componentProps: {
      placeholder: '请输入规格名称'
    }
  }
])
const searchParams = ref<{ rule_name: string }>({ rule_name: '' })

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>
